Skip to content

fix(post-processing): raise when a rename would duplicate a column label - #45043

Merged
rusackas merged 2 commits into
apache:masterfrom
SEPURI-SAI-KRISHNA:fix/rename-partial-collision-guard
Oct 13, 2026
Merged

rusackas merged 2 commits into
apache:masterfrom
SEPURI-SAI-KRISHNA:fix/rename-partial-collision-guard

Conversation

@SEPURI-SAI-KRISHNA

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

Copy link
Copy Markdown
Contributor

SUMMARY

rename's collision guard tests whether every new name already exists, so it misses a mapping where only one of them does. {"a": "b", "c": "z"} on a frame holding [a, b, c] slips past it and pandas produces ['b', 'b', 'z']. Details in #45042.

What makes a mapping invalid is introducing a duplicate label, not a target label happening to be present, so this guards on that instead:

-    try:
-        _rename_level = df.columns.get_level_values(level=level)
-    except (IndexError, KeyError) as err:
-        raise InvalidPostProcessingError from err
-
-    if all(new_name in _rename_level for new_name in columns.values()):
+    try:
+        renamed_columns = df.iloc[:0].rename(columns=columns, level=level).columns
+    except (IndexError, KeyError) as err:
+        raise InvalidPostProcessingError from err
+
+    if renamed_columns.duplicated().sum() > df.columns.duplicated().sum():
         raise InvalidPostProcessingError(_("Label already exists"))

Renaming an empty slice asks pandas the same question the real call will answer, with the same arguments, so the guard cannot drift from the operation it guards. It also keeps the existing level validation, since a bad level still raises IndexError or KeyError there.

Two notes on why it is shaped this way:

  • Flipping all to any was the obvious fix and is not enough. It rejects a mapping that renames onto a label it vacates itself, and it still misses two sources pointing at one new label.
  • Counts are compared rather than asking whether the result holds any duplicate, so a frame that arrives with duplicate labels stays renameable. Earlier operations can produce one, and a later rename of an unrelated column should not start failing because of it.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

On a frame whose columns are [a, b, c]:

mapping before after
{"a": "b"} raises Label already exists raises (unchanged)
{"a": "x", "c": "z"} ['x', 'b', 'z'] unchanged
{"a": "b", "c": "z"} ['b', 'b', 'z'] raises Label already exists
{"a": "z", "b": "z"} ['z', 'z', 'c'] raises Label already exists
{"a": "b", "b": "d"} ['b', 'd', 'c'] unchanged
{"a": "b", "b": "a"} raises Label already exists ['b', 'a', 'c']

Rows three and four are the fix. The last row is the one relaxation: a straight swap produces a unique index and pandas handles it, so it is no longer rejected.

A duplicate label is worth rejecting because df["b"] then comes back as a DataFrame where callers expect a Series, and the duplicate travels on to the next post-processing operation.

TESTING INSTRUCTIONS

pytest tests/unit_tests/pandas_postprocessing/

Five tests are added:

test covers fails on
test_should_raise_exception_partial_duplication a two-entry mapping where one target collides master
test_should_raise_exception_partial_duplication_on_multiindex the same on a MultiIndex with level=0 master
test_should_raise_exception_two_sources_one_new_label two columns renamed to the same new label master and any
test_should_rename_onto_a_label_the_same_mapping_vacates a target the mapping itself frees up any
test_should_rename_a_frame_that_already_holds_duplicate_labels renaming around a pre-existing duplicate neither, it pins behaviour master already has

The existing duplication tests both drive the guard with a single-entry mapping, where "every new name exists" and "the result holds a duplicate" are the same condition, which is why this was invisible. The three tests that do pass a two-entry mapping rename onto free names, so they never reach the guard and are unaffected.

The suite goes from 180 to 185 passing with no existing test modified. ruff check, ruff format --check and pre-commit run mypy are clean, and pylint rates the changed source file 10.00/10. The error message is unchanged and already extracted, so there is no messages.pot change.

The slice carries no rows, so the guard stays cheap: 0.5 ms on a 1000 column frame and 1.7 ms on a 5000 column one.

ADDITIONAL INFORMATION

@codeant-ai-for-open-source

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

Copy link
Copy Markdown
Contributor

CodeAnt PR Risk: Medium Risk

  • The PR needs attention before merging because comparing duplicate counts can miss a newly created collision when an existing duplicate is resolved.
  • For columns [a, a, b] with a→c and b→a, the result [c, c, a] has the same duplicate count, so the rename is allowed despite creating a collision on c.

Assessed commit: 3b73eb63949d

@codecov

codecov Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.56%. Comparing base (27d5c36) to head (3b73eb6).
⚠️ Report is 5 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #45043   +/-   ##
=======================================
  Coverage   82.55%   82.56%           
=======================================
  Files        3005     3005           
  Lines      186589   186616   +27     
  Branches    43235    43240    +5     
=======================================
+ Hits       154046   154076   +30     
+ Misses      29781    29778    -3     
  Partials     2762     2762           
Flag Coverage Δ
hive 36.26% <0.00%> (+<0.01%) ⬆️
mysql 55.15% <0.00%> (-0.01%) ⬇️
postgres 55.16% <0.00%> (-0.01%) ⬇️
presto 38.12% <0.00%> (+<0.01%) ⬆️
python 86.36% <100.00%> (+<0.01%) ⬆️
sqlite 54.89% <0.00%> (-0.01%) ⬇️
unit 79.44% <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.

@pull-request-size pull-request-size Bot added size/L and removed size/M labels Oct 7, 2026
@SEPURI-SAI-KRISHNA SEPURI-SAI-KRISHNA changed the title fix(post-processing): raise when any rename target already exists fix(post-processing): raise when a rename would duplicate a column label Oct 7, 2026
@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Contributor Author

Good catch, and it is a regression I introduced. Confirmed:

df = pd.DataFrame({"a": [1], "b": [2], "c": [3]})
list(df.rename(columns={"a": "b", "b": "d"}).columns)
# ['b', 'd', 'c'], unique

b is vacated by the same mapping, so any rejects a rename that master accepts and that produces a perfectly good index.

The real problem is that the guard tests whether a target label is present rather than whether the rename introduces a duplicate. Flipping all to any keeps the wrong test and only moves which cases it gets wrong. Running that down turned up two more:

  • {"a": "z", "b": "z"} gives ['z', 'z', 'c']. Master misses it and any misses it too, since neither z exists beforehand for a presence test to find.
  • A frame that arrives with duplicate labels, which earlier operations can produce, must stay renameable. Asking whether the result holds any duplicate would make every later rename on such a frame fail, so the guard compares duplicate counts and only rejects a rename that adds one.

Pushed that guard: rename an empty slice, df.iloc[:0], with the same arguments the real call uses, then compare counts. No rows are copied, so it costs 0.5 ms on a 1000 column frame. Three more tests, covering your case and the two above. The full behaviour matrix is in the PR body.

One relaxation worth a maintainer's eye: a straight swap, {"a": "b", "b": "a"}, used to raise and now succeeds with ['b', 'a', 'c']. That is a unique index pandas handles fine, so I treated it as part of the same correction rather than preserving an accidental rejection. I can keep swaps rejected if that is preferred.

@netlify

netlify Bot commented Oct 7, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 3b73eb6
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ac61f92db4ffc0008712156
😎 Deploy Preview https://deploy-preview-45043--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.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Contributor Author

I do not think this one holds. Taking the example as written:

df = pd.DataFrame([[1, 2, 3]], columns=["a", "a", "b"])
list(df.rename(columns={"a": "c", "b": "a"}).columns)
# ['c', 'c', 'a']

Duplicate count is 1 before and 1 after, and nunique is 2 before and 2 after, so nothing merged. The c, c pair is the pair that was already duplicated, relabelled. Master allows this mapping as well, so the guard is not changing behaviour here either.

The premise is that an existing duplicate can be resolved. It cannot. rename maps by label, so every occurrence of a moves to the same target and a duplicate group can never be split. That makes the count monotone non-decreasing, which is why "the count went up" is exactly "two previously distinct labels merged", and that is the collision worth rejecting.

Checked rather than argued. Over every mapping on frames of 1 to 4 columns drawn from 3 labels onto 4 targets, 6840 in all, the guard agrees with nunique dropping in every case and the count never decreased once:

guard = new.duplicated().sum() > idx.duplicated().sum()
truth = new.nunique() < idx.nunique()
# 6840 mappings checked, 0 disagreements

If there is a case where the count does decrease I would like to see it, since that is the one thing that would break this.

@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. Went through the CodeAnt back-and-forth and the monotonicity argument holds up -- rename maps by label, so the image of the distinct labels can only shrink, never grow, which is exactly why comparing duplicate counts catches every real collision without over-rejecting. Good tests.

@rusackas
rusackas merged commit bffb563 into apache:master Oct 13, 2026
80 checks passed
villebro pushed a commit that referenced this pull request Oct 16, 2026
@SEPURI-SAI-KRISHNA
SEPURI-SAI-KRISHNA deleted the fix/rename-partial-collision-guard 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A post-processing rename mapping that partially collides creates a duplicate column label

3 participants