codeant-ai-for-open-source[bot] commented on code in PR #40954:
URL: https://github.com/apache/superset/pull/40954#discussion_r3806604536


##########
superset-frontend/packages/superset-ui-chart-controls/src/sections/anomalyDetection.tsx:
##########
@@ -0,0 +1,204 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { legacyValidateInteger, legacyValidateNumber } from 
'@superset-ui/core';
+import { ControlPanelSectionConfig } from '../types';
+import { displayTimeRelatedControls } from '../utils';
+
+const validateRange =
+  (
+    check: (n: number) => boolean,
+    message: string,
+  ): ((v: unknown) => string | false) =>
+  (v: unknown) => {
+    const n = Number(v);
+    return Number.isFinite(n) && check(n) ? t(message) : false;
+  };
+
+const validateMinRollingWindow = validateRange(
+  n => n < 3,
+  'Rolling window must be >= 3',
+);
+const validatePositiveNumber = validateRange(
+  n => n <= 0,
+  'Value must be a positive number',
+);
+const validateConfidenceInterval = validateRange(
+  n => n <= 0 || n >= 1,
+  'Confidence interval must be between 0 and 1 (exclusive)',
+);
+export const ANOMALY_DEFAULT_DATA = {
+  anomalyDetectionEnabled: false,
+  anomalyDetectionMethod: 'zscore',
+  anomalyDetectionRollingWindow: 14,
+  anomalyDetectionSensitivity: 3.0,
+  anomalyDetectionConfidenceInterval: 0.8,
+  anomalyDetectionSeasonalityYearly: null,
+  anomalyDetectionSeasonalityWeekly: null,
+  anomalyDetectionSeasonalityDaily: null,
+};
+
+export const anomalyDetectionControls: ControlPanelSectionConfig = {
+  label: t('Anomaly Detection'),
+  expanded: false,
+  visibility: displayTimeRelatedControls,
+  controlSetRows: [
+    [
+      {
+        name: 'anomalyDetectionEnabled',
+        config: {
+          type: 'CheckboxControl',
+          label: t('Enable anomaly detection'),
+          renderTrigger: false,
+          default: ANOMALY_DEFAULT_DATA.anomalyDetectionEnabled,
+          description: t('Enable anomaly detection on the time series'),
+        },
+      },
+    ],
+    [
+      {
+        name: 'anomalyDetectionMethod',
+        config: {
+          type: 'SelectControl',
+          label: t('Detection method'),
+          choices: [
+            ['zscore', t('Z-Score')],
+            ['mad', t('MAD (Median Absolute Deviation)')],
+            ['prophet', t('Prophet (Seasonality-aware)')],
+          ],
+          default: ANOMALY_DEFAULT_DATA.anomalyDetectionMethod,
+          description: t(
+            'Algorithm to use for anomaly detection. Z-Score uses rolling mean 
and standard deviation. MAD uses rolling median absolute deviation which is 
more robust to outliers. Prophet uses Facebook Prophet to model seasonality and 
flags points outside the confidence interval.',
+          ),
+        },
+      },
+    ],
+    [
+      {
+        name: 'anomalyDetectionRollingWindow',
+        config: {
+          type: 'TextControl',
+          label: t('Rolling window'),
+          validators: [legacyValidateInteger, validateMinRollingWindow],
+          default: ANOMALY_DEFAULT_DATA.anomalyDetectionRollingWindow,
+          description: t(
+            'Size of the rolling window for computing statistics. Must be >= 
3.',
+          ),
+          visibility: ({ controls }) =>
+            controls?.anomalyDetectionMethod?.value !== 'prophet',
+        },
+      },
+    ],
+    [
+      {
+        name: 'anomalyDetectionSensitivity',
+        config: {
+          type: 'TextControl',
+          label: t('Sensitivity'),
+          validators: [legacyValidateNumber, validatePositiveNumber],
+          default: ANOMALY_DEFAULT_DATA.anomalyDetectionSensitivity,
+          description: t(
+            'Threshold for anomaly detection. Higher values mean fewer 
anomalies are detected. Typical values: 2.0 (more sensitive) to 4.0 (less 
sensitive).',
+          ),
+          visibility: ({ controls }) =>
+            controls?.anomalyDetectionMethod?.value !== 'prophet',
+        },
+      },
+    ],
+    [
+      {
+        name: 'anomalyDetectionConfidenceInterval',
+        config: {
+          type: 'TextControl',
+          label: t('Confidence interval'),
+          validators: [legacyValidateNumber, validateConfidenceInterval],
+          default: ANOMALY_DEFAULT_DATA.anomalyDetectionConfidenceInterval,
+          description: t(
+            'Width of the confidence interval. Should be between 0 and 1',
+          ),
+          visibility: ({ controls }) =>
+            controls?.anomalyDetectionMethod?.value === 'prophet',
+        },
+      },
+    ],
+    [
+      {
+        name: 'anomalyDetectionSeasonalityYearly',
+        config: {
+          type: 'SelectControl',
+          freeForm: true,
+          label: t('Yearly seasonality'),
+          choices: [
+            [null, t('default')],
+            [true, t('Yes')],
+            [false, t('No')],
+          ],

Review Comment:
   **Suggestion:** `freeForm: true` allows arbitrary strings even though the 
backend only supports `None`, booleans, or integer Fourier orders for Prophet 
seasonality. An invalid value such as `foo` is passed through unchanged and 
then supplied to Prophet, which can raise a model-configuration error instead 
of producing chart data. Restrict free-form input to valid integer values or 
normalize invalid values before submitting the post-processing operation. [api 
mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Prophet anomaly chart requests can fail during processing.
   - ❌ Timeseries chart data may not render after invalid input.
   - ⚠️ All three seasonality controls permit the same invalid values.
   ```
   </details>
   
   [![Use CodeAnt 
Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill)
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** 
superset-frontend/packages/superset-ui-chart-controls/src/sections/anomalyDetection.tsx
   **Line:** 144:151
   **Comment:**
        *Api Mismatch: `freeForm: true` allows arbitrary strings even though 
the backend only supports `None`, booleans, or integer Fourier orders for 
Prophet seasonality. An invalid value such as `foo` is passed through unchanged 
and then supplied to Prophet, which can raise a model-configuration error 
instead of producing chart data. Restrict free-form input to valid integer 
values or normalize invalid values before submitting the post-processing 
operation.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve 
this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40954&comment_hash=a2330f504f55b13c949f3af00e6712ef9959b3d4f4e09b7cf654e9190c1282f7&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40954&comment_hash=a2330f504f55b13c949f3af00e6712ef9959b3d4f4e09b7cf654e9190c1282f7&reaction=dislike'>👎</a>



##########
superset-frontend/plugins/plugin-chart-echarts/src/types.ts:
##########
@@ -69,6 +69,7 @@ export enum ForecastSeriesEnum {
   ForecastTrend = '__yhat',
   ForecastUpper = '__yhat_upper',
   ForecastLower = '__yhat_lower',
+  Anomaly = '__anomaly',

Review Comment:
   **Suggestion:** The new `__anomaly` suffix is treated as a reserved series 
marker by `extractForecastSeriesContext`, so any legitimate metric whose name 
already ends with `__anomaly` will be misclassified as an anomaly series, 
renamed to the text before the suffix, rendered as a red scatter plot, and 
potentially merged with another series. Use an unambiguous reserved encoding or 
ensure the marker is only interpreted for columns generated by anomaly 
post-processing. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Legitimate `__anomaly` metrics render as red scatter points.
   - ❌ Series names can collide during forecast-context aggregation.
   - ⚠️ Tooltips may merge unrelated metric and anomaly values.
   ```
   </details>
   
   [![Use CodeAnt 
Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill)
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset-frontend/plugins/plugin-chart-echarts/src/types.ts
   **Line:** 72:72
   **Comment:**
        *Logic Error: The new `__anomaly` suffix is treated as a reserved 
series marker by `extractForecastSeriesContext`, so any legitimate metric whose 
name already ends with `__anomaly` will be misclassified as an anomaly series, 
renamed to the text before the suffix, rendered as a red scatter plot, and 
potentially merged with another series. Use an unambiguous reserved encoding or 
ensure the marker is only interpreted for columns generated by anomaly 
post-processing.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve 
this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40954&comment_hash=b231920f43bfa6e2681131962e2e6b1be14dd4095c956dbc9f665fefdd58b155&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40954&comment_hash=b231920f43bfa6e2681131962e2e6b1be14dd4095c956dbc9f665fefdd58b155&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to