mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
fix(python): use flat validation aliases after nested choices (#5270)
Closes #5269 ## Summary Embedded tables store Pydantic field names. To reconstruct an aliased field, use a flat validation alias when the stored row has the field name and none of the supplied aliases resolves. The follow-up checks the full nested path. A `profile` value that is null or lacks `userId` allows fallback to the stored `user_id`. A supplied `profile.userId` takes precedence, including when its value is null. Before adding a flat alias, check whether it would make an earlier nested choice resolve. For an address stored as Paris with an alternate address in Rome, adding `shipping` would make `shipping.alternate` take precedence. Use `destination` in that case so the result includes the complete stored address. ## Validation - Reproduced the shortened Rome address and both missing-profile failures on the prior PR commit. The six synchronous and asynchronous cases pass with the follow-up. - Covered a safe same-root fallback, supplied nested values, the original flat-alias regression, and shared-key guards. - Passed all 99 Pydantic tests on Pydantic 2.14.4 with the Embedded native library. On the minimum supported Pydantic 2.7.4, 96 tests passed and three newer-version cases were skipped. - Passed the repository-pinned Ruff lint and format checks. Independent reviewers repeated the native round trips and test coverage.
This commit is contained in:
@@ -29,6 +29,7 @@ import numpy as np
|
||||
import pyarrow as pa
|
||||
import pyarrow.compute as pc
|
||||
import pydantic
|
||||
from pydantic_core import PydanticUndefined
|
||||
from typing_extensions import Annotated
|
||||
|
||||
from lancedb._lancedb import fts_query_to_json
|
||||
@@ -89,71 +90,86 @@ def _top_level_alias_key(alias: Any) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _top_level_alias_keys(alias: Any) -> set[str]:
|
||||
options = alias.choices if isinstance(alias, pydantic.AliasChoices) else (alias,)
|
||||
return {
|
||||
key for option in options if (key := _top_level_alias_key(option)) is not None
|
||||
}
|
||||
def _alias_choices(alias: Any) -> tuple[Any, ...]:
|
||||
return (
|
||||
tuple(alias.choices) if isinstance(alias, pydantic.AliasChoices) else (alias,)
|
||||
)
|
||||
|
||||
|
||||
def _single_component_alias(alias: Any) -> str | None:
|
||||
# AliasChoices validates against the first matching source, so only use
|
||||
# its first option as a field-name fallback.
|
||||
option = alias.choices[0] if isinstance(alias, pydantic.AliasChoices) else alias
|
||||
if isinstance(option, pydantic.AliasPath) and len(option.path) != 1:
|
||||
if isinstance(alias, pydantic.AliasPath) and len(alias.path) != 1:
|
||||
# A nested path needs a structured payload; do not infer one here.
|
||||
return None
|
||||
return _top_level_alias_key(option)
|
||||
return _top_level_alias_key(alias)
|
||||
|
||||
|
||||
def _has_alias_value(alias: Any, row: dict) -> bool:
|
||||
if isinstance(alias, pydantic.AliasPath):
|
||||
return alias.search_dict_for_path(row) is not PydanticUndefined
|
||||
return isinstance(alias, str) and alias in row
|
||||
|
||||
|
||||
def _rows_to_models(model: type[T], rows: List[dict]) -> List[T]:
|
||||
"""Build ``model`` instances from result rows.
|
||||
|
||||
A table created from a LanceModel stores each field under its name, while
|
||||
pydantic validates an aliased field by its alias. Pass a row's value under
|
||||
the alias when the row has the field name but none of the aliases, so a
|
||||
model with aliases can read the tables it wrote; rows keyed by any alias
|
||||
still work.
|
||||
A table created from a LanceModel stores each field under its name. Use a
|
||||
flat validation alias for a stored value when no supplied alias resolves.
|
||||
"""
|
||||
if model.model_config.get("validate_by_alias", True) is False:
|
||||
# Name-only validation: pydantic reads field names and ignores aliases.
|
||||
return [model(**row) for row in rows]
|
||||
# populate_by_name is the pre-2.11 spelling; an explicit new flag wins.
|
||||
if model.model_config.get(
|
||||
"validate_by_name", model.model_config.get("populate_by_name", False)
|
||||
):
|
||||
return [model(**row) for row in rows]
|
||||
|
||||
aliases = {
|
||||
name: field.validation_alias or field.alias
|
||||
name: _alias_choices(field.validation_alias or field.alias)
|
||||
for name, field in model.model_fields.items()
|
||||
}
|
||||
# populate_by_name is the pre-2.11 spelling; an explicit new flag wins.
|
||||
accepts_by_name = model.model_config.get(
|
||||
"validate_by_name",
|
||||
model.model_config.get("populate_by_name", False),
|
||||
)
|
||||
# Every top-level key some field reads, including the first step of an
|
||||
# AliasPath and each choice of an AliasChoices.
|
||||
alias_keys = {}
|
||||
for name, alias in aliases.items():
|
||||
keys = _top_level_alias_keys(alias)
|
||||
if not keys or accepts_by_name:
|
||||
keys.add(name)
|
||||
alias_keys[name] = keys
|
||||
readers = {}
|
||||
for name, keys in alias_keys.items():
|
||||
for key in keys:
|
||||
for name, choices in aliases.items():
|
||||
keys = {
|
||||
key for alias in choices if (key := _top_level_alias_key(alias)) is not None
|
||||
}
|
||||
for key in keys or {name}:
|
||||
readers.setdefault(key, set()).add(name)
|
||||
renames = {
|
||||
name: target
|
||||
for name, alias in aliases.items()
|
||||
if (target := _single_component_alias(alias)) is not None
|
||||
|
||||
renames = {}
|
||||
for name, choices in aliases.items():
|
||||
# Do not move a source that another field reads.
|
||||
and target != name
|
||||
and not (readers.get(name, set()) - {name})
|
||||
# Do not add a source that another field accepts. Introducing a shared
|
||||
# alias key could change that field's Pydantic selection.
|
||||
and not (readers.get(target, set()) - {name})
|
||||
}
|
||||
if readers.get(name, set()) - {name}:
|
||||
continue
|
||||
targets = []
|
||||
for index, alias in enumerate(choices):
|
||||
target = _single_component_alias(alias)
|
||||
if target is None:
|
||||
continue
|
||||
# Do not add a key that another field accepts.
|
||||
if target == name or readers.get(target, set()) - {name}:
|
||||
break
|
||||
targets.append((target, index))
|
||||
if targets:
|
||||
renames[name] = targets
|
||||
|
||||
for row in rows:
|
||||
for name, target in renames.items():
|
||||
if name in row and not any(key in row for key in alias_keys[name]):
|
||||
for name, targets in renames.items():
|
||||
choices = aliases[name]
|
||||
if name not in row or any(
|
||||
_has_alias_value(alias, row) for alias in choices
|
||||
):
|
||||
continue
|
||||
for target, index in targets:
|
||||
candidate = {target: row[name]}
|
||||
# Adding a flat alias can make an earlier path under the same
|
||||
# root point inside the stored value instead of to the value.
|
||||
if any(_has_alias_value(alias, candidate) for alias in choices[:index]):
|
||||
continue
|
||||
row[target] = row.pop(name)
|
||||
break
|
||||
return [model(**row) for row in rows]
|
||||
|
||||
|
||||
|
||||
@@ -827,8 +827,9 @@ def test_aliased_lance_model_reads_back_its_own_table(mem_db):
|
||||
[
|
||||
pydantic.AliasChoices("userId"),
|
||||
pydantic.AliasPath("userId"),
|
||||
pydantic.AliasChoices(pydantic.AliasPath("profile", "userId"), "userId"),
|
||||
],
|
||||
ids=["alias-choices", "alias-path"],
|
||||
ids=["alias-choices", "alias-path", "nested-alias-with-flat-choice"],
|
||||
)
|
||||
def test_aliased_lance_model_with_complex_validation_alias_reads_back_its_own_table(
|
||||
mem_db, validation_alias
|
||||
@@ -845,6 +846,104 @@ def test_aliased_lance_model_with_complex_validation_alias_reads_back_its_own_ta
|
||||
assert item.user_id == 1
|
||||
|
||||
|
||||
@pytest.fixture(
|
||||
params=["shadowed", "safe"], ids=["shadowed-flat-alias", "same-root-safe"]
|
||||
)
|
||||
def stored_address_alias_case(request):
|
||||
class City(LanceModel):
|
||||
city: str
|
||||
|
||||
choices = [pydantic.AliasPath("shipping", "alternate"), "shipping"]
|
||||
address = {"city": "Paris"}
|
||||
address_type = City
|
||||
if request.param == "shadowed":
|
||||
|
||||
class Address(City):
|
||||
alternate: Optional[City] = None
|
||||
|
||||
choices.append("destination")
|
||||
address["alternate"] = {"city": "Rome"}
|
||||
address_type = Address
|
||||
|
||||
class Order(LanceModel):
|
||||
address: address_type = Field(validation_alias=pydantic.AliasChoices(*choices))
|
||||
|
||||
order = Order.model_validate({choices[-1]: address})
|
||||
return Order, order, address
|
||||
|
||||
|
||||
def test_alias_choices_preserve_stored_address(mem_db, stored_address_alias_case):
|
||||
Order, order, address = stored_address_alias_case
|
||||
tbl = mem_db.create_table("orders", schema=Order)
|
||||
tbl.add([order])
|
||||
assert tbl.search().to_arrow().to_pylist() == [{"address": address}]
|
||||
|
||||
[result] = tbl.search().to_pydantic(Order)
|
||||
assert result.model_dump() == {"address": address}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_alias_choices_preserve_stored_address_async(
|
||||
mem_db_async, stored_address_alias_case
|
||||
):
|
||||
Order, order, address = stored_address_alias_case
|
||||
tbl = await mem_db_async.create_table("orders", schema=Order)
|
||||
await tbl.add([order])
|
||||
query = await tbl.search()
|
||||
assert (await query.to_arrow()).to_pylist() == [{"address": address}]
|
||||
|
||||
[result] = await query.to_pydantic(Order)
|
||||
assert result.model_dump() == {"address": address}
|
||||
|
||||
|
||||
@pytest.fixture(
|
||||
params=[
|
||||
(None, 42),
|
||||
({"name": "Pat"}, 42),
|
||||
({"userId": 7}, 7),
|
||||
({"userId": None}, None),
|
||||
],
|
||||
ids=["null-profile", "missing-leaf", "supplied-leaf", "supplied-null-leaf"],
|
||||
)
|
||||
def profile_alias_case(request):
|
||||
class Item(LanceModel):
|
||||
user_id: Optional[int] = Field(
|
||||
validation_alias=pydantic.AliasChoices(
|
||||
pydantic.AliasPath("profile", "userId"), "userId"
|
||||
)
|
||||
)
|
||||
|
||||
profile, expected = request.param
|
||||
fields = (
|
||||
[("userId", pa.int64())]
|
||||
if profile and "userId" in profile
|
||||
else [("name", pa.string())]
|
||||
)
|
||||
data = pa.table(
|
||||
{"user_id": [42], "profile": pa.array([profile], type=pa.struct(fields))}
|
||||
)
|
||||
return Item, data, expected
|
||||
|
||||
|
||||
def test_alias_choices_read_actual_nested_value(mem_db, profile_alias_case):
|
||||
Item, data, expected = profile_alias_case
|
||||
tbl = mem_db.create_table("items", data=data)
|
||||
|
||||
[result] = tbl.search().to_pydantic(Item)
|
||||
assert result.user_id == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_alias_choices_read_actual_nested_value_async(
|
||||
mem_db_async, profile_alias_case
|
||||
):
|
||||
Item, data, expected = profile_alias_case
|
||||
tbl = await mem_db_async.create_table("items", data=data)
|
||||
|
||||
[result] = await (await tbl.search()).to_pydantic(Item)
|
||||
assert result.user_id == expected
|
||||
|
||||
|
||||
def test_lower_priority_alias_takes_precedence_over_field_name(mem_db):
|
||||
class Item(LanceModel):
|
||||
user_id: int = Field(
|
||||
@@ -999,8 +1098,9 @@ async def test_aliased_lance_model_reads_back_its_own_table_async(mem_db_async):
|
||||
[
|
||||
pydantic.AliasChoices("userId"),
|
||||
pydantic.AliasPath("userId"),
|
||||
pydantic.AliasChoices(pydantic.AliasPath("profile", "userId"), "userId"),
|
||||
],
|
||||
ids=["alias-choices", "alias-path"],
|
||||
ids=["alias-choices", "alias-path", "nested-alias-with-flat-choice"],
|
||||
)
|
||||
async def test_aliased_lance_model_with_complex_validation_alias_reads_back_async(
|
||||
mem_db_async, validation_alias
|
||||
|
||||
Reference in New Issue
Block a user