Repository navigation
fix(post-processing): overwrite when a rename targets an existing column - #45083
sadpandajoe merged 10 commits into
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
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 20Pre-#19116 Worth noting the condition has to test both halves, which I had wrong at first. On nothing relying on the duplicates, that matches what I found. The one thing in the repo that reads a label back is Separately, your |
EnxDev
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
EnxDev
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
#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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
| overwritten_df = append_df.loc[:, overwritten.keys()].rename( | ||
| columns=overwritten | ||
| ) | ||
| _base_df.loc[:, overwritten_df.columns] = overwritten_df |
There was a problem hiding this comment.
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.
…s-existing-target # Conflicts: # superset/utils/pandas_postprocessing/utils.py
|
Resolved on the shape you gave, keyed by target since a rename means the two 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 You were right that the bulk set breaks wider than NaN alone. Six of eight Added Re-censused against the new base: 13 conditions, 12 fail a named test when |
EnxDev
left a comment
There was a problem hiding this comment.
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.
…umn (#45083) Co-authored-by: Enzo Martellucci <[email protected]> Co-authored-by: Evan Rusackas <[email protected]>
SUMMARY
_append_columnsdecides 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: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 forcum,diffandrolling, where@validate_column_argsguarantees the mapping's keys are columns ofbase_df. It does not hold for the geography operations, where the keys areappend_df's column names.geodetic_parsepasses{"latitude": "latitude"}whenever the caller keeps the default column name, andlatitudeis not inbase_dfat all, so a presence-only test would send it down the append path.pd.concatunions the index rather than aligning, so anappend_dfthat does not sharebase_df's index would change the row count.#45086 has since made the geography helpers carry
df's own index, so that no longer reachespd.concatthrough those two callers. The helper is general, though, and the invariant it owns is that a mapping which renames nothing never changesbase_df's row count.test_append_columns_never_adds_rows_for_a_non_renaming_mappingpins 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 TypeErrorand 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 whatdiffandcumhand 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 raisesValueError: Setting with non-unique columns is not allowed, which surfaces as a 500.{"y": "w", "z": "w"}appended both and returned a frame carryingwtwice. Both now raiseInvalidPostProcessingError("Columns mapped to the same target: ..."), which is a 400. Measured through real operations,rolling,cumanddiffall returnstatus=400with that message.geohash_decodeandgeodetic_parsealready wrapped this call inexcept 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.
z['y', 'z', 'z']df["z"]is a DataFrame['y', 'z'][10, 20]{"y": "z"},zpresent['y', 'z', 'z']['y', 'z'], overwritten{"y": "z", "z": "w"}['y', 'z', 'z', 'w']['y', 'z', 'w']{"y": "y"}['y'], overwritten{"y": "y2"}, noy2['y', 'y2'], appended{"latitude": "latitude"}, source not inbase_df{"y": "z", "z": "z"}ValueError, a 500InvalidPostProcessingError, a 400{"y": "w", "z": "w"}['y', 'z', 'w', 'w']InvalidPostProcessingError, a 400base_dfis 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_dfsharesbase_df's index, andbase_dfis never mutated.TESTING INSTRUCTIONS
Six tests are added to
tests/unit_tests/pandas_postprocessing/test_utils.py, seven cases in all:test_append_columns_overwrites_a_target_already_in_base_df{"y": "z"}withzpresent, the case from the issue, plus thatbase_dfis not mutatedtest_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 namestest_append_columns_writes_in_place_when_the_target_names_the_source{"latitude": "latitude"}withappend_dfonbase_df's index, as the geography helpers pass it since #45086, asserting the values landtest_append_columns_never_adds_rows_for_a_non_renaming_mappingappend_dfcarries a rowbase_dfdoes not, pinning that the row count is unchangedtest_append_columns_rejects_two_sources_mapped_to_one_targetbase_dftest_append_columns_widens_an_int_target_the_new_values_do_not_fit{"y": "z"}withzan int column and a NaN in the source, pinning the dtype fallback on the path only a rename reachesThe 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_sourcegained a value assertion, because withappend_dfon a 0-based index the.locwrite aligned on the index and wrote[nan, nan]while the test only checked shape.ADDITIONAL INFORMATION
columnsmapping that renames onto an existing column duplicates its label #45082