From 4632bce81b89a22d9499a895a956cdc89866c694 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=BF=97=E8=B0=A6?= <89645338+simpleqt@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:27:20 +0800 Subject: [PATCH] fix(python)!: let rename_columns reuse a name freed by the same call (#4936) BREAKING CHANGE: Every source name in the map must exist in the input selection. A name created by another entry in the same map is no longer a valid source. With `a` present and `x` and `y` absent, `rename_columns({"a": "x", "x": "y"})` used to apply `a -> x` and then `x -> y`, returning the data under `y`. It now raises `ValueError: Cannot rename column 'x' because it does not exist` because `x` is absent from the input. Migration: rename directly with `{"a": "y"}`, or use two successive `rename_column("a", "x")` and `rename_column("x", "y")` calls when the ordered behavior is intended. The docstring states this rule and a test pins it. This is marked with `!` for release notes and labeled `breaking-change`. ## Why `Permutation.rename_columns` applied its map one entry at a time by calling `rename_column` in a loop. Each entry was validated against the intermediate state left by the previous ones, so a map in which one column's new name is another entry's old name was rejected: ``` perm.rename_columns({"id": "value", "value": "data"}) ValueError: Cannot rename column `id` to `value` because a column with that name already exists ``` The name is free once the whole map is applied, which is the only state a caller can observe. Column swaps were impossible for the same reason. The method documents renaming a *map* of columns, so the map should be one rename. ## Change Validate the map against its final state: collect the names that survive unchanged plus the new names accepted so far, and reject only a genuine collision with either. Then build the new selection from the original one in a single pass, so no entry sees another's intermediate result. The source name is checked against the original selection, which produces the breaking change above. Existing behaviour is preserved: renaming to a name that survives the call still raises; renaming a column that does not exist still raises; two entries mapping to the same target still raises; error messages are unchanged, and `rename_column` itself is untouched. ## Testing `test_rename_columns_frees_names_for_the_same_call` covers chained rename, full swap, the ordered-source rejection above, a repeated target (still an error, and `self` is never modified), `None` keys/values, and the empty-map no-op. `test_rename_columns_empty_map_keeps_pinned_version` covers the pinned-version behavior. `test_permutation.py`: **83 passed**, rename subset **8 passed**. The native extension in this checkout was too old to import the branch's Python package, so the tests ran against the 0.41.0 wheel's native module with the branch's `permutation.py` overlaid; the changed method is pure Python. Signed-off-by: simpleqt <2015900818@qq.com> --- python/python/lancedb/permutation.py | 40 +++++++++++++++++++--- python/python/tests/test_permutation.py | 44 +++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 4 deletions(-) diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index 6ef96c149..5f0179f1e 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -1245,7 +1245,20 @@ class Permutation: Rename the given columns in the permutation If any of the columns do not exist then an error will be raised - If any of the new names already exist then an error will be raised + If any of the new names already exist then an error will be raised, unless + that name is itself renamed by the same call + + The map is applied as one rename, so a name freed by the same call can be + reused: ``rename_columns({"a": "b", "b": "c"})`` yields ``b`` and ``c`` + rather than failing because ``b`` still exists part-way through. + + Every key must name a column that exists in the input selection. A name + created by another entry in the same map is not a valid source: + ``rename_columns({"a": "x", "x": "y"})`` raises when ``x`` is absent from + the input. Use successive ``rename_column`` calls for ordered renames: + ``rename_column("a", "x")`` then ``rename_column("x", "y")``. + + An empty map returns this permutation unchanged. Note: this does not actually modify the underlying dataset. It only changes the name of the column that is visible from this permutation. This is a @@ -1253,11 +1266,30 @@ class Permutation: No data will be copied. """ assert column_map is not None, "column_map is required" + if not column_map: + # Rebuilding the selection would copy the permutation and drop the + # version it is pinned to, so a map that renames nothing is a no-op. + return self - new_permutation = self + new_selection = {} + occupied = {name for name in self.selection if name not in column_map} for old_name, new_name in column_map.items(): - new_permutation = new_permutation.rename_column(old_name, new_name) - return new_permutation + if old_name is None or new_name is None: + raise ValueError("Cannot rename a column to or from `None`") + if old_name not in self.selection: + raise ValueError( + f"Cannot rename column `{old_name}` because it does not exist" + ) + if new_name in occupied: + raise ValueError( + f"Cannot rename column `{old_name}` to `{new_name}` because a " + "column with that name already exists" + ) + occupied.add(new_name) + + for name, value in self.selection.items(): + new_selection[column_map.get(name, name)] = value + return self._with_selection(new_selection) def select_columns(self, columns: list[str]) -> "Permutation": """ diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index cd6b19a20..6e1319d5d 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -1244,6 +1244,50 @@ def test_rename_columns(some_permutation: Permutation): some_permutation.rename_columns({"value": "id"}) +def test_rename_columns_frees_names_for_the_same_call(some_permutation: Permutation): + # `value` is still present when `id` is renamed, but the map is one rename, + # so the name is free by the time the whole map has been applied. + renamed = some_permutation.rename_columns({"id": "value", "value": "data"}) + assert renamed.schema == pa.schema([("value", pa.int64()), ("data", pa.int64())]) + assert some_permutation.schema.names == ["id", "value"] + + swapped = some_permutation.rename_columns({"id": "value", "value": "id"}) + assert swapped.schema == pa.schema([("value", pa.int64()), ("id", pa.int64())]) + + # A source must exist in the input, not be created by an earlier entry: + # ordered renames need successive rename_column calls instead. + with pytest.raises(ValueError, match="does not exist"): + some_permutation.rename_columns({"id": "x", "x": "y"}) + + # A target repeated within the map is still a collision. + with pytest.raises(ValueError, match="a column with that name already exists"): + some_permutation.rename_columns({"id": "x", "value": "x"}) + assert some_permutation.schema.names == ["id", "value"] + + # None is rejected here instead of failing later on a name that cannot exist. + with pytest.raises(ValueError, match="to or from `None`"): + some_permutation.rename_columns({"id": None}) + with pytest.raises(ValueError, match="to or from `None`"): + some_permutation.rename_columns({None: "x"}) + + # An empty map must stay a no-op so the permutation keeps its pinned version. + assert some_permutation.rename_columns({}) is some_permutation + + +def test_rename_columns_empty_map_keeps_pinned_version(tmp_path): + db = connect(tmp_path) + tbl = db.create_table("base", pa.table({"id": [1, 2], "value": [10, 20]})) + permutation_tbl = permutation_builder(tbl).execute() + perm = Permutation.from_tables(tbl, permutation_tbl) + expected = perm.__getitems__([0, 1]) + + # Rebuilding the selection would copy the permutation, which materializes the + # base table at its current version and loses the pin. + tbl.update(where="id = 1", values={"value": 999}) + assert perm.__getitems__([0, 1]) == expected + assert perm.rename_columns({}).__getitems__([0, 1]) == expected + + def test_select_columns(some_permutation: Permutation): assert some_permutation.select_columns(["id"]).schema == pa.schema( [("id", pa.int64())]