Skip to content

fix(post-processing): overwrite when a rename targets an existing column - #45083

Merged
sadpandajoe merged 10 commits into
apache:masterfrom
SEPURI-SAI-KRISHNA:fix/append-columns-existing-target
Nov 19, 2026
Merged

sadpandajoe merged 10 commits into
apache:masterfrom
SEPURI-SAI-KRISHNA:fix/append-columns-existing-target

Conversation

@SEPURI-SAI-KRISHNA

@SEPURI-SAI-KRISHNA SEPURI-SAI-KRISHNA commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

SUMMARY

_append_columns decides whether a mapping entry overwrites a column or appends one by asking whether its source and target names match. A rename can land on a label the frame already has, and that entry is appended, so the result carries two columns under the same name.

#45018 introduced that split to fix the mixed-mapping case in #45017. @EnxDev flagged this residual in review there, and I recorded it on #45017, which auto-closed when #45018 merged. This is it on its own.

An entry is now appended only when its target is a label the result does not already have, meaning the target differs from the source and is not already in base_df:

appended = {
    key: value
    for key, value in columns.items()
    if value != key and value not in base_df.columns
}
overwritten = {key: value for key, value in columns.items() if key not in appended}

Both halves of that condition are needed, and I had this wrong at first. On #45018 I suggested keying only on value in base_df.columns, saying it subsumes the matching case "since a {"y": "y"} target is present by definition". That holds for cum, diff and rolling, where @validate_column_args guarantees the mapping's keys are columns of base_df. It does not hold for the geography operations, where the keys are append_df's column names. geodetic_parse passes {"latitude": "latitude"} whenever the caller keeps the default column name, and latitude is not in base_df at all, so a presence-only test would send it down the append path. pd.concat unions the index rather than aligning, so an append_df that does not share base_df's index would change the row count.

#45086 has since made the geography helpers carry df's own index, so that no longer reaches pd.concat through those two callers. The helper is general, though, and the invariant it owns is that a mapping which renames nothing never changes base_df's row count. test_append_columns_never_adds_rows_for_a_non_renaming_mapping pins exactly that, and it is the one test that fails against the presence-only form.

The overwrite branch writes one column at a time, keyed by target, because once the source name may differ from the target it is the target that says which column to write. The write is guarded with except TypeError and falls back to plain column replacement: pandas 3 raises instead of widening a column's dtype when the new values do not fit it, and a NaN never fits an int64 column, which is what diff and cum hand back for an integer metric. That guard is master's, added by the pandas 3 bump in #45325, and @EnxDev caught in review that resolving the conflict with a single bulk assignment would have dropped it for every overwrite.

Two sources mapped to one target are now rejected. Splitting the mapping exposed a shape that previously produced nonsense either way: {"y": "z", "z": "z"} put two sources in the overwrite half, and assigning them together raises ValueError: Setting with non-unique columns is not allowed, which surfaces as a 500. {"y": "w", "z": "w"} appended both and returned a frame carrying w twice. Both now raise InvalidPostProcessingError ("Columns mapped to the same target: ..."), which is a 400. Measured through real operations, rolling, cum and diff all return status=400 with that message. geohash_decode and geodetic_parse already wrapped this call in except ValueError -> InvalidPostProcessingError(_("Invalid geodetic string")), so those two were reporting the wrong cause for it.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A: backend only.

base_df = DataFrame({"y": [1, 2], "z": [3, 4]})
append_df = DataFrame({"y": [10, 20]})
_append_columns(base_df, append_df, {"y": "z"})
columns z
before ['y', 'z', 'z'] two columns, df["z"] is a DataFrame
after ['y', 'z'] [10, 20]
mapping before after
{"y": "z"}, z present ['y', 'z', 'z'] ['y', 'z'], overwritten
{"y": "z", "z": "w"} ['y', 'z', 'z', 'w'] ['y', 'z', 'w']
{"y": "y"} ['y'], overwritten unchanged
{"y": "y2"}, no y2 ['y', 'y2'], appended unchanged
{"latitude": "latitude"}, source not in base_df written in place unchanged
{"y": "z", "z": "z"} ValueError, a 500 InvalidPostProcessingError, a 400
{"y": "w", "z": "w"} ['y', 'z', 'w', 'w'] InvalidPostProcessingError, a 400

base_df is still left untouched in every case, which the new tests assert.

To check the change is confined to the bug I ran the old and the new helper over every mapping from frames of one to three columns onto four target names, against four index shapes including a reversed and a string index: 336 mappings. 176 of them map two or more sources onto one target, the invalid input the new code rejects. Of the remaining 160, 60 are identical and 100 differ, and in all 100 the difference is that the old result carried a duplicate column label and the new one does not. None are unexplained, no row counts change when append_df shares base_df's index, and base_df is never mutated.

TESTING INSTRUCTIONS

pytest tests/unit_tests/pandas_postprocessing

Six tests are added to tests/unit_tests/pandas_postprocessing/test_utils.py, seven cases in all:

test covers on master
test_append_columns_overwrites_a_target_already_in_base_df {"y": "z"} with z present, the case from the issue, plus that base_df is not mutated fails
test_append_columns_splits_a_mapping_by_whether_the_target_exists {"y": "z", "z": "w"}, where both halves are renames and the split cannot be read off the names fails
test_append_columns_writes_in_place_when_the_target_names_the_source {"latitude": "latitude"} with append_df on base_df's index, as the geography helpers pass it since #45086, asserting the values land passes
test_append_columns_never_adds_rows_for_a_non_renaming_mapping the same mapping where append_df carries a row base_df does not, pinning that the row count is unchanged passes, guards against the presence-only form
test_append_columns_rejects_two_sources_mapped_to_one_target both duplicate-target shapes, with the target in and not in base_df fails, 2 cases
test_append_columns_widens_an_int_target_the_new_values_do_not_fit {"y": "z"} with z an int column and a NaN in the source, pinning the dtype fallback on the path only a rename reaches fails

The full post-processing suite is 215 passed, up from 208 on master, with one existing test changed: test_append_columns_writes_in_place_when_the_target_names_the_source gained a value assertion, because with append_df on a 0-based index the .loc write aligned on the index and wrote [nan, nan] while the test only checked shape.

ADDITIONAL INFORMATION

@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt  CodeAnt PR Risk

🟢  Low Risk

  • The PR appears safe to merge; no actionable issues were identified in the review.

Assessed commit: 5c3ecaa67474

@codecov

codecov Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.62%. Comparing base (88d07ba) to head (5c3ecaa).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #45083   +/-   ##
=======================================
  Coverage   85.62%   85.62%           
=======================================
  Files        3107     3107           
  Lines      214589   214593    +4     
  Branches    50782    50783    +1     
=======================================
+ Hits       183734   183738    +4     
  Misses      27435    27435           
  Partials     3420     3420           
Flag Coverage Δ
hive 33.99% <11.11%> (-0.01%) ⬇️
mysql 51.64% <11.11%> (-0.01%) ⬇️
postgres 51.68% <11.11%> (-0.01%) ⬇️
presto 35.68% <11.11%> (-0.01%) ⬇️
python 88.25% <100.00%> (+<0.01%) ⬆️
sqlite 51.35% <11.11%> (-0.01%) ⬇️
unit 83.46% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Contributor Author

Thanks for digging out the provenance, that is a better argument for this change than the one in the description. Confirmed:

base_df = DataFrame({"y": [1, 2], "z": [3, 4]})
append_df = DataFrame({"y": [10, 20]})
base_df.assign(**{"z": append_df["y"]})
#    y   z
# 0  1  10
# 1  2  20

Pre-#19116 assign gives exactly what this PR gives, ['y', 'z'] with z overwritten, so this is a restore rather than a new contract. I will add that to the description.

Worth noting the condition has to test both halves, which I had wrong at first. assign keyed on nothing but the target label, and the closest single test to that is value in base_df.columns. That one is not enough, because the geography operations pass append_df's own column names as keys: geodetic_parse passes {"latitude": "latitude"} when the caller keeps the default name, and latitude is in neither frame's overlap. Presence-only sends it to concat, which unions the index, so a non-0-based frame gains a row per parsed row. Hence value != key and value not in base_df.columns, with a test for that case.

On nothing relying on the duplicates, that matches what I found. The one thing in the repo that reads a label back is flatten, and it goes through df.columns rather than df[label], so it is indifferent.

Separately, your assign point explains the other half of what the bot flagged on #45018. assign aligns on the index, so the geography operations' bare DataFrame() used to produce silently null coordinates; #19116's concat turned that into extra rows too. Same root cause, older than the row count symptom. That one is #45085 with a fix in #45086.

@sadpandajoe
sadpandajoe requested a review from EnxDev October 8, 2026 17:12

@EnxDev EnxDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked this out locally and the split holds up. The post-processing suite passes (189), and I also tried a swap mapping and a rename onto an existing metric after a pivot: both overwrite in place, and the pivot case keeps its MultiIndex.

Left one non-blocking note inline about two sources mapped onto the same target.

overwritten_df = append_df.loc[:, overwritten.keys()].rename(
columns=overwritten
)
_base_df.loc[:, overwritten_df.columns] = overwritten_df

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: if two sources point at the same existing target, like {"y": "z", "z": "z"}, both land in overwritten and this line raises ValueError: Setting with non-unique columns is not allowed. That isn't an InvalidPostProcessingError, so the chart data request comes back as a 500 rather than a 400. On master it just returned a duplicate z.

The same mapping with a new target ({"y": "w", "z": "w"}) still goes through concat and duplicates w. Could we reject duplicate targets up front with an InvalidPostProcessingError? That covers both cases. Fine as a follow-up too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, and it is worse than non-blocking: this PR introduces the 500. Confirmed by running both versions of _append_columns against the same frames:

master
  OK     {"y":"z","z":"z"} -> cols=['y', 'z', 'z']
  OK     {"y":"w","z":"w"} -> cols=['y', 'z', 'w', 'w']
this PR
  RAISES {"y":"z","z":"z"} -> ValueError: Setting with non-unique columns is not allowed.
  OK     {"y":"w","z":"w"} -> cols=['y', 'z', 'w', 'w']

So I took your suggestion rather than leaving it as a follow-up, and rejected duplicate targets up front. It covers both rows, since no split of the mapping can serve two sources writing to one target.

this PR + guard
  RAISES {"y":"z","z":"z"} -> InvalidPostProcessingError: Columns mapped to the same target: z
  RAISES {"y":"w","z":"w"} -> InvalidPostProcessingError: Columns mapped to the same target: w
  OK     {"y":"z","z":"y"} -> cols=['y', 'z']
  OK     {"y":"z"}         -> cols=['y', 'z']

InvalidPostProcessingError.status is 400, and measured through the real operations it is a 400 in each: rolling, cum and diff all return Columns mapped to the same target: z.

One thing the guard fixes that is not obvious from the line you commented on. geohash_decode and geodetic_parse already wrap _append_columns in except ValueError: raise InvalidPostProcessingError(_("Invalid geodetic string")), so for those two callers the ValueError was arriving as a 400 with the wrong cause named. Raising inside _append_columns goes past that:

geodetic_parse(df, geodetic="p", longitude="x", latitude="x")
  -> InvalidPostProcessingError: Columns mapped to the same target: x  status=400

Added as a parametrized test over both of your mappings. 193 passed in tests/unit_tests/pandas_postprocessing/, and the new string is in messages.pot.

@pull-request-size pull-request-size Bot added size/L and removed size/M labels Oct 14, 2026
@netlify

netlify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit b334d50
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ae5c6a189bda34c39c33f25
😎 Deploy Preview https://deploy-preview-45083--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions github-actions Bot added the i18n Namespace | Anything related to localization label Oct 14, 2026

@EnxDev EnxDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The duplicate-target guard covers both shapes I raised earlier, and the parametrized test pins each one. The post-processing suite passes at this head (193).

Left two notes inline. Both come from #45086 landing on master after this branch was cut: the latitude test passes while it writes NaNs, and the docstring's concat rationale no longer matches what the geography callers do.

`z`. `{'latitude': 'latitude'}` names a target that is not in `base_df` at
all, which `geodetic_parse` does whenever the caller keeps the default
column name, and that must keep being written in place: appending it would
concatenate, and `pd.concat` unions the index rather than aligning to

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#45086 made the geography helpers build their frames on df's own index, so after a rebase the concat path lines up for geodetic_parse and wouldn't add rows anymore.

The value != key half is still harmless to keep. The reason given here just won't hold once this rebases, so it's worth rewording, or dropping if nothing else depends on it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reworded. You were right that the old wording stops being true once #45086 is in: the geography helpers carry df's own index now, so that path no longer gains rows through those two callers.

Dropped the "would gain a row per parsed row" claim and kept the part that still holds, that pd.concat unions the index rather than aligning, so an append_df not sharing base_df's index would change the row count. _append_columns is general, so the invariant is the helper's own rather than something the geography callers happen to provide.

I kept value != key rather than dropping it, but only because there is now a test that depends on it. See the other thread: with the indexes aligned nothing was guarding it, so I added one that pins the row-count invariant and fails against the presence-only form.

@EnxDev EnxDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both of my earlier notes are handled. The latitude test now puts append_df on index=[5, 6] and asserts the values, and the docstring explains the value != key half by the row-count invariant, not by what the geography callers used to do.

I ran the post-processing suite at this head and got 204 passed. I also swapped in the presence-only condition to check the new test does its job: test_append_columns_never_adds_rows_for_a_non_renaming_mapping fails with 3 rows against 2, so that half is pinned.

No further notes from me, looks good to merge.

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Oct 29, 2026
overwritten_df = append_df.loc[:, overwritten.keys()].rename(
columns=overwritten
)
_base_df.loc[:, overwritten_df.columns] = overwritten_df

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This conflicts with master now. #45325 (the pandas 3 bump) rewrote this block as a per-column loop with a TypeError fallback, because pandas 3 raises instead of upcasting when .loc writes a NaN into an int column.

If the resolution keeps this bulk set, every overwrite loses that fallback, plain {"y": "y"} included. On 3.0.6 this line throws as soon as it gets a NaN-bearing column for an int one, which is what diff hands back for an int metric. Running master's loop by target keeps both fixes:

for source, target in overwritten.items():
    try:
        _base_df.loc[:, [target]] = append_df[[source]].rename(
            columns={source: target}
        )
    except TypeError:
        _base_df[target] = append_df[source]

That held up on 3.0.6 for a rename onto an int column, the same-name case, a swap and a pivoted frame. Nothing in test_utils.py covers the fallback yet, so a case with an int z and a NaN in the source would pin it.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Contributor Author

Resolved on the shape you gave, keyed by target since a rename means the two
names differ:

for source, target in overwritten.items():
    try:
        _base_df.loc[:, [target]] = append_df[[source]].rename(
            columns={source: target}
        )
    except TypeError:
        _base_df[target] = append_df[source]

The added rename is free. Against master's loop on the five same-name shapes
(lossless float into int64, NaN into int64, float into float, int into int,
fractional float into int64) both forms take the same branch and return equal
frames. The swap, the plain append and three MultiIndex shapes are right too.

You were right that the bulk set breaks wider than NaN alone. Six of eight
cases raise under it, plain {"y": "y"} included.

Added test_append_columns_widens_an_int_target_the_new_values_do_not_fit for
the fallback: an int z, a NaN in the source, reached through a rename, which
is the path only this PR creates. 215 pass in the directory, pre-commit clean.

Re-censused against the new base: 13 conditions, 12 fail a named test when
reverted on their own. The thirteenth is the list-wrap on the write target,
which no reachable input separates. Only a tuple-keyed mapping would, and
validate_column_args matches keys against level 0 on a MultiIndex frame, so
one cannot arrive. On a real pivot cross product the two forms are identical,
and rolling with {"sum_m": "sum_n"} over one comes out correct.

@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Oct 31, 2026

@rusackas rusackas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks!

@EnxDev EnxDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The conflict resolution keeps master's per-column write and its TypeError fallback, now keyed by target, so my pandas 3 note is handled. I merged this with current master and ran the post-processing suite on pandas 3.1.1: 220 passed. Taking the fallback out makes test_append_columns_widens_an_int_target_the_new_values_do_not_fit fail, so that test is doing its job.

No further notes from me, this looks good to merge. GitHub has it blocked because asf-allowlist-check became a required check after this head was pushed, so it hasn't run here. Merging master in should clear that.

@sadpandajoe
sadpandajoe merged commit 1705596 into apache:master Nov 19, 2026
73 checks passed
hainenber pushed a commit that referenced this pull request Nov 21, 2026
@SEPURI-SAI-KRISHNA
SEPURI-SAI-KRISHNA deleted the fix/append-columns-existing-target branch November 21, 2026 15:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

i18n Namespace | Anything related to localization size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A post-processing columns mapping that renames onto an existing column duplicates its label

4 participants