Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
fix(memo): reject a stable type ID on object (#2841)
Jiangzhou54e7dbb9a243
diff --git a/python/cocoindex/_internal/memo_fingerprint.py b/python/cocoindex/_internal/memo_fingerprint.pyindex 8a15933e..3adee2b5 100644--- a/python/cocoindex/_internal/memo_fingerprint.py+++ b/python/cocoindex/_internal/memo_fingerprint.py@@ -166,19 +166,17 @@ _CLASS_OBJECT_OWNER_IDENTITY: tuple[Fingerprintable, Fingerprintable] = ()-# Resolved identity parts per (type, key function owner, class object?). Every-# registry write clears it; until then a type's declared ID, module and-# qualified name are not read again.+# Resolved identity parts per (type, key function owner). Every registry write+# clears it; until then a type's declared ID, module and qualified name are not+# read again._type_identity_cache: dict[- tuple[type, type | None, bool], tuple[Fingerprintable, Fingerprintable]+ tuple[type, type | None], tuple[Fingerprintable, Fingerprintable]] = {}def _type_identity_parts(typ: type,fallback_owner: type | None = None,- *,- is_class_object: bool = False,) -> tuple[Fingerprintable, Fingerprintable]:"""Return stable type ID or module+qualname type identity parts.@@ -192,17 +190,17 @@ def _type_identity_parts(type's own declared or registered stable ID still wins, but when no stableID applies the identity stays with the key function's owner type."""- key = (typ, fallback_owner, is_class_object)+ key = (typ, fallback_owner)parts = _type_identity_cache.get(key)if parts is None:parts = _type_identity_cache[key] = _resolve_type_identity_parts(- typ, fallback_owner, is_class_object+ typ, fallback_owner)return partsdef _resolve_type_identity_parts(- typ: type, fallback_owner: type | None, is_class_object: bool+ typ: type, fallback_owner: type | None) -> tuple[Fingerprintable, Fingerprintable]:stable_type_id = next((@@ -214,8 +212,6 @@ def _resolve_type_identity_parts()if not isinstance(stable_type_id, str):for owner in typ.__mro__:- if is_class_object and owner is object and typ is not object:- breakregistry = _memo_type_registry.get(owner)if registry is not None and registry.stable_type_id is not None:stable_type_id = registry.stable_type_id@@ -246,15 +242,10 @@ def _canonicalize_registered_memo_key(tag = "shook"bound = functools.partial(registry.state_fn, obj)state_methods.append(_make_state_fn_entry(bound, registry.state_fn))- if isinstance(obj, type):- # Class objects keep the identity of the metaclass owner whose- # registration supplied the key function.- identity = _type_identity_parts(owner, is_class_object=True)- else:- # Instances resolve identity on the runtime type, so a subclass can- # override an inherited registered stable ID by declaring or- # registering its own; the automatic identity falls back to the owner.- identity = _type_identity_parts(type(obj), fallback_owner=owner)+ # Identity resolves on the runtime type (the metaclass, for a class object),+ # so a subtype can override an inherited stable ID by declaring or+ # registering its own; the automatic identity falls back to the owner.+ identity = _type_identity_parts(type(obj), fallback_owner=owner)return (tag,*identity,@@ -284,7 +275,7 @@ def _canonicalize_class_object(*_CLASS_OBJECT_OWNER_IDENTITY,# This synthesized identity is already canonical; do not re-enter memo-key# dispatch, where a registration on ``object`` could intercept it.- ("seq", _type_identity_parts(cls, is_class_object=True)),+ ("seq", _type_identity_parts(cls)),)@@ -394,7 +385,8 @@ def register_memo_type(registered base type wins. Each call replaces the full registration for``typ``: omitting ``stable_type_id`` clears any previous registered stabletype ID, and omitting ``key_fn`` or passing ``None`` clears any previous- key/state functions.+ key/state functions. ``object`` cannot take a stable type ID: through the+ MRO it would apply to every type."""if not isinstance(typ, type):@@ -422,6 +414,11 @@ def register_memo_type("register_memo_type() stable_type_id must be a str, "f"got {type(stable_type_id).__name__}")+ if stable_type_id is not None and typ is object:+ raise TypeError(+ "register_memo_type() cannot give object a stable_type_id: "+ "it would apply to every type"+ )_register_memo_type_registry(typ,diff --git a/python/tests/internal/test_memo_fingerprint.py b/python/tests/internal/test_memo_fingerprint.pyindex 3830345d..0c4cb7f3 100644--- a/python/tests/internal/test_memo_fingerprint.py+++ b/python/tests/internal/test_memo_fingerprint.py@@ -486,8 +486,18 @@ def _class_object_ignores_own_id_under_key_owner(declared: bool) -> _Build:return build+def _class_object_takes_its_metaclass_id(case: _Case) -> tuple[object, object]:+ # A class keyed through a base metaclass's key function takes the ID declared+ # on its own metaclass, as an instance takes the one declared on its class.+ base_meta = _derive(type, "BaseMeta")+ case.register(base_meta, lambda cls: ("entry", 1))+ sub_meta = _derive(base_meta, "SubMeta", __coco_memo_type_id__="test.SubMeta/v1")+ ref = _derive(_Keyed, "Ref", __coco_memo_type_id__="test.SubMeta/v1")+ return sub_meta("Entry", (), {}), ref(1)++def _class_objects_ignore_object_key_fn(case: _Case) -> tuple[object, object]:- case.register(object, lambda obj: "same", stable_type_id="test.Object/v1")+ case.register(object, lambda obj: "same")return _derive(_Unkeyed, "Entry"), _derive(_Unkeyed, "Other")@@ -676,6 +686,9 @@ def _memo_key_leads_back_to_parent(registered: bool) -> _Build:True,id="class-own-registered-id-differs",),+ pytest.param(+ _class_object_takes_its_metaclass_id, True, id="class-metaclass-own-id"+ ),pytest.param(_class_object_distinct_from_its_instance,False,@@ -734,6 +747,7 @@ def test_type_identity("state_fn requires a memo key function",),(_Unkeyed, (), {"stable_type_id": 123}, "stable_type_id must be a str"),+ (object, (), {"stable_type_id": "test.All/v1"}, "cannot give object"),],)def test_register_memo_type_rejects_invalid_calls(@@ -797,8 +811,8 @@ def test_shared_values_match_independent_values(shared: object) -> None:def test_freed_memo_keys_are_not_back_references() -> None:- # A key returned by `__coco_memo_key__` (or by the built-in key function- # for classes) is freed once encoded, so the next one can reuse its `id()`.+ # A key returned by `__coco_memo_key__` is freed once encoded, so the next+ # one can reuse its `id()`.class Row:def __init__(self, uid: int, ts: str) -> None:self.uid, self.ts = uid, ts@@ -806,21 +820,9 @@ def test_freed_memo_keys_are_not_back_references() -> None:def __coco_memo_key__(self) -> object:return (self.uid, self.ts)- class A:- pass-- class B:- pass-- class C:- pass-assert memo_fingerprint([Row(1, "t1"), Row(2, "t2")]) != memo_fingerprint([Row(1, "t1"), Row(3, "t3")])- assert fingerprint_call(_dummy_fn, ([A, B],), {}, []) != fingerprint_call(- _dummy_fn, ([A, C],), {}, []- )def test_shared_dataclass_matches_independent_values() -> None: