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


##########
superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx:
##########
@@ -341,22 +296,43 @@ export default function PivotTableChart(props: 
PivotTableProps) {
 
   const unpivotedData = useMemo(
     () =>
-      data.reduce(
-        (acc: Record<string, any>[], record: Record<string, any>) => [
-          ...acc,
-          ...metricNames
+      // `data` is now one entry per rollup level. Tag every record with the
+      // row/column dimension labels of the level that produced it (mirroring
+      // the METRIC_KEY injection used for the full rows/cols below) so
+      // PivotData can slot each pre-computed value without re-aggregating.
+      // buildGroupbyCombinations already applied transposePivot, so the 
level's
+      // groupby is display-oriented and is not transposed again here.
+      data.flatMap((query: QueryData) => {
+        let levelRows = query.groupby.rows.map(getColumnLabel);
+        let levelCols = query.groupby.columns.map(getColumnLabel);
+        if (metricsLayout === MetricsLayoutEnum.ROWS) {
+          levelRows = combineMetric
+            ? [...levelRows, METRIC_KEY]
+            : [METRIC_KEY, ...levelRows];
+        } else {
+          levelCols = combineMetric
+            ? [...levelCols, METRIC_KEY]
+            : [METRIC_KEY, ...levelCols];
+        }
+        return query.data.flatMap((record: Record<string, any>) =>
+          metricNames
             .map((name: string) => ({
               ...record,
               [METRIC_KEY]: name,
               value: record[name],
               // Mark currency column for per-cell currency detection in 
aggregators
               __currencyColumn: currencyCodeColumn,
+              // The level this record belongs to (used by PivotData 
placement).
+              rows: levelRows,
+              columns: levelCols,

Review Comment:
   **Suggestion:** Using plain `rows` and `columns` as internal metadata keys 
can overwrite real dataset fields with the same names, which corrupts grouping 
keys and cross-filter payloads for charts whose source columns are named `rows` 
or `columns`. Store these rollup tags under reserved internal keys (for example 
`__rows` / `__columns`) and read those keys in PivotData instead. [incorrect 
variable usage]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Pivot tables misplace cells for `rows`/`columns` dimensions.
   - ⚠️ Cross-filter callbacks send wrong filter values to backend.
   - ⚠️ Totals/subtotals inconsistent when dimension names collide.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. In Superset, create a Pivot Table chart using a dataset that has a 
physical column
   named `rows` or `columns`, and include that column in the chart’s groupby 
(so it appears
   in `formData.groupbyRows` or `formData.groupbyColumns`). This chart type is 
wired to the
   `PivotTableChart` visualization via the plugin entrypoint at
   
`superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/index.ts:36-75`, 
which
   calls `loadChart: () => import('../PivotTableChart')`.
   
   2. When the chart queries run, the backend response is converted into 
`DataRecord` rows
   where each column alias becomes a key, including any column named `rows` or 
`columns`.
   This is documented in `transformProps` at
   
`superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts:73-76`,
   and those `DataRecord[]` arrays are wrapped into `QueryData` objects 
(`types.ts:65-68`)
   and passed to `PivotTableChart` as the `data: QueryData[]` prop
   (`transformProps.ts:216-220`).
   
   3. Inside `PivotTableChart`, the `unpivotedData` memo at
   
`superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx:297-335`
   flattens each `QueryData` level. For every underlying `record: DataRecord`, 
it builds a
   new object with `...record` and then assigns rollup metadata: `rows: 
levelRows` and
   `columns: levelCols` at lines `325-327`. If the original `record` already 
had a field
   named `rows` or `columns` (because the dataset column was named that), these 
assignments
   at `326-327` overwrite the real data values with the rollup tag arrays.
   
   4. During rendering, `TableRenderer` creates a `PivotData` instance
   (`TableRenderers.tsx:104-110`), which iterates records in
   `react-pivottable/utilities.ts:1120-1239`. There, `record.rows` and 
`record.columns` are
   read as rollup tags (`const recordRows = (record.rows as string[]) ?? null; 
const
   recordColumns = (record.columns as string[]) ?? null;` at lines 
`1126-1129`), and
   `levelRows` / `levelColumns` are derived from them. For a dimension whose 
label is
   literally `'rows'` or `'columns'`, the aggregator then builds row/column 
keys using
   `record[row]` / `record[col]` (`utilities.ts:1134-1139`), but because 
`record.rows` /
   `record.columns` were overwritten with the tag arrays in step 3, the key 
values for those
   dimensions become metadata strings instead of the true cell values. These 
corrupted keys
   propagate into click handlers in `TableRenderers.tsx:94-120` and header 
click handlers in
   `TableRenderers.tsx:124-152`, which construct `filters: 
Record<string,string>` from those
   row/column values and pass them to `PivotTableChart.toggleFilter`
   (`PivotTableChart.tsx:493-551`). As a result, for charts whose source 
columns are named
   `rows` or `columns`, pivot placement and emitted cross-filter payloads are 
incorrect
   because the metadata tags have silently overwritten the real data.
   ```
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d5d63c6edb524ddf9352c6a738edecf8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=d5d63c6edb524ddf9352c6a738edecf8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <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-pivot-table/src/PivotTableChart.tsx
   **Line:** 326:327
   **Comment:**
        *Incorrect Variable Usage: Using plain `rows` and `columns` as internal 
metadata keys can overwrite real dataset fields with the same names, which 
corrupts grouping keys and cross-filter payloads for charts whose source 
columns are named `rows` or `columns`. Store these rollup tags under reserved 
internal keys (for example `__rows` / `__columns`) and read those keys in 
PivotData instead.
   
   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%2F41184&comment_hash=903c7ef006ee394b728e882a0ef42a04153c3989806ab41decf2d37ccd03b365&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41184&comment_hash=903c7ef006ee394b728e882a0ef42a04153c3989806ab41decf2d37ccd03b365&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