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
feat(memo): add stable memo type identifiers (#2256)
Max X Rong7ab9f74fb9f0
diff --git a/docs/src/content/docs/advanced_topics/memoization_keys.mdx b/docs/src/content/docs/advanced_topics/memoization_keys.mdxindex 53a55a00..ef4d6859 100644--- a/docs/src/content/docs/advanced_topics/memoization_keys.mdx+++ b/docs/src/content/docs/advanced_topics/memoization_keys.mdx@@ -1,9 +1,10 @@---title: "*Memoization keys* & states"description: >- Customize how CocoIndex fingerprints memoized inputs via __coco_memo_key__ or- registered functions, and layer state validation (e.g. mtime, then content hash)- on top β plus NotMemoKeyable to opt out for stateful types.+ Customize how CocoIndex fingerprints memoized inputs via __coco_memo_key__,+ registered memo key functions, or stable type IDs, and layer state validation+ (e.g. mtime, then content hash) on top β plus NotMemoKeyable to opt out for+ stateful types.rust_description: >Customize how CocoIndex fingerprints memoized inputs through the MemoInputtrait, layer state validation (e.g. mtime, then content hash) on top with@@ -17,6 +18,32 @@ CocoIndex detects [logic, input, and context changes](../programming_guide/funct- **Memoization keys** β how to control what CocoIndex uses as the fingerprint for your objects.- **Memo states** β how to add post-fingerprint validation to check freshness beyond simple equality.+<Lang only="python">++- **Stable type IDs** β how to keep a type's memo namespace stable across refactors.++:::tip[Choose the smallest mechanism]+Most values need no customization. CocoIndex already handles primitives, containers, dataclasses, Pydantic models, class objects, and other picklable objects.++- Only one function should transform or ignore an argument β use [`memo_key=`](#override-at-the-call-site-with-memo_key).+- You control the type and every use should share the same key β define [`__coco_memo_key__`](#define-__coco_memo_key__-when-you-control-the-type).+- You don't control the type and every use should share the same key β [register a key function](#register-a-key-function-when-you-dont-control-the-type).+- A matching key still needs a freshness check, such as mtime or ETag β use a [memo state](#memo-state-validation).+- A class may move or be renamed while keeping the same memo namespace β use a [stable type ID](#use-stable-type-ids-across-refactors).+- A value must never participate in memoization β inherit from [`NotMemoKeyable`](#preventing-memoization).+:::++Fingerprinting happens at these points:++- **Function arguments** β when the function is called.+- **Change-detected context values** β when they are provided (for example, by `builder.provide()`), before `use_context()` reads them.+- **`deps` values** β once, when the `@coco.fn(..., deps=...)` or `@coco.fn.as_async(..., deps=...)` decorator is applied.+- **`coco.LogicDep` values** β once, when the `LogicDep` is constructed (normally at module import).++A stable type ID or a memo key function must be in place before a value is fingerprinted. For `deps` and `LogicDep` values, that means before the decorator runs or the `LogicDep` is constructed.++</Lang>+<Lang only="rust">Both go through one trait, `MemoInput`, which keeps **identity** and **freshness** apart: its `write_memo_key` method is the key; its optional `memo_state` method is the state. The arguments of a `#[cocoindex::function(memo)]` function must implement `MemoInput`, unless `memo_key(..)` transforms or skips them. A `context_key!` value takes part only when the key is declared with `detect_change`.@@ -27,11 +54,11 @@ Both go through one trait, `MemoInput`, which keeps **identity** and **freshness<Lang only="python">-For each data value (function argument, `deps` value, or context value), CocoIndex derives a canonical form with this precedence:+For each data value, CocoIndex derives a canonical form with this precedence:-1. If the object implements **`__coco_memo_key__()`**, CocoIndex uses its return value.-2. Otherwise, if you registered a **memo key function** for the object's type, CocoIndex uses that.-3. Otherwise, CocoIndex falls back to structural canonicalization for a limited set of primitives/containers.+1. If the object implements **`__coco_memo_key__()`**, CocoIndex uses its return value. This applies to class instances, not class objects (`type`).+2. Otherwise, if a **memo key function** is registered for the object's type, CocoIndex uses it.+3. Otherwise, CocoIndex uses its built-in canonicalization.The following types are handled automatically (no custom key needed):@@ -39,7 +66,7 @@ The following types are handled automatically (no custom key needed):- **Containers**: `list`, `tuple`, `dict`, `set`, `frozenset` (recursively canonicalized)- **Dataclass instances**: all fields included in definition order- **Pydantic v2 models**: all fields included-- **Class objects** (`type`): identified by module and qualified name+- **Class objects** (`type`): identified by a stable type ID when configured, otherwise by module and qualified name- **Other picklable objects**: used as a fallback via `pickle`</Lang>@@ -166,25 +193,104 @@ impl cocoindex::MemoInput for UserRow {<Lang only="python">+The method is used whenever a `UserRow` is fingerprinted as a function argument, `deps` value, or change-detected context value. For example:++```python+import cocoindex as coco+[email protected](memo=True)+def format_user(row: UserRow) -> str:+ print("format_user executed")+ return f"{row.user_id}: updated at {row.updated_at}"+```++Inside a processing component, the first update executes `format_user`. When logic and context also remain unchanged, a later update with another `UserRow` containing the same `user_id` and `updated_at` reuses the cached result. Changing either value changes the memo key, so the function executes again.+### Register a key function (when you don't control the type)-If you can't add `__coco_memo_key__` (stdlib / third-party types), register a handler:+If you can't add `__coco_memo_key__` (stdlib / third-party types), register a key function:```pythonfrom pathlib import Path-from cocoindex import register_memo_key_function+from cocoindex import register_memo_typedef path_key(p: Path) -> object:p = p.resolve()st = p.stat()return (str(p), st.st_mtime_ns, st.st_size)-register_memo_key_function(Path, path_key)+register_memo_type(Path, path_key)```- Registration is **MRO-aware**: if you register both a base class and a subclass, the **most specific** match wins.- Your key function must return the same kinds of stable objects as `__coco_memo_key__` (small primitives/tuples).+### Use stable type IDs across refactors++By default, CocoIndex identifies types in memo keys by their module and qualified name (`module.QualName`). If you move or rename a class, set `__coco_memo_type_id__` with an ordinary string (for new entries) or `coco.prev_type_id()` (for existing automatic entries):++```python+from dataclasses import dataclass+from typing import ClassVar+import cocoindex as coco++# Ordinary string for new entries:+@dataclass+class NewEntry:+ __coco_memo_type_id__: ClassVar[str] = "com.example.NewEntry/v1"++ id: str+ content: str++# Retain existing automatic entries:+@dataclass+class SourceEntry: # Moved to new_package.models+ __coco_memo_type_id__: ClassVar[str] = coco.prev_type_id(+ "old_package.models",+ "SourceEntry",+ )++ name: str+ version: int+```++Declare `prev_type_id` on each moved class; like any class attribute, a base-class declaration propagates to subclasses.++For types you don't control, register the ID with `register_memo_type()`:++```python+from some_library import ExternalRecord+import cocoindex as coco++coco.register_memo_type(+ ExternalRecord,+ lambda record: (record.id, record.version),+ stable_type_id="com.example.ExternalRecord/v1",+)+```++Each call replaces the type's entire registration. If a type needs a key function, state function, and stable type ID, pass them together in one call.++- **Inheritance**: Declaring `__coco_memo_type_id__` on a base class is a deliberate statement that the family shares the same namespace, and propagates to subclasses. For dataclass and Pydantic instances, when a subclass's fields differ, field tuples keep payloads distinct; a subclass can and should override the ID by declaring its own `__coco_memo_type_id__` when semantics diverge.+- **Precedence**: Type identity resolution follows this precedence:+ 1. **Declared stable type ID** (`__coco_memo_type_id__`, own or inherited).+ 2. **Registered stable type ID** (most specific registration across the type's MRO via `register_memo_type()`).+ 3. **Automatic fallback** (the canonical `module.QualName` of the type or, for a value handled by a registered key function, of the type the function is registered on).++:::note[Pickle fallback]+Types that fall back to pickle are fingerprinted from their pickle bytes, which name the class by module and qualified name, so a stable type ID has no effect on them. Register a memo key function together with the stable type ID.+:::++### Class objects as inputs++When passing a class object itself (such as `ProductRow` rather than an instance `ProductRow(...)`), CocoIndex fingerprints only the class identity (its declared/registered stable ID or module + qualname), without invoking `__coco_memo_key__` methods or hashing class attributes.++To customize memoization for class objects globally, register a memo key function on the class's custom metaclass or on `type`.++:::caution[Avoid colliding class objects]+Unlike instances (where field tuples keep payloads distinct), raw class objects do not hash schema attributes or field tuples. Classes sharing an inherited stable type ID will produce identical fingerprints. If a memoized function accepts class objects and must distinguish between them, declare a distinct `__coco_memo_type_id__` on each class or provide a custom `memo_key=` at the call site.+:::+</Lang><Lang only="rust">@@ -217,7 +323,7 @@ There is no `register_memo_key_function` registry: a newtype or a call-site `mem### Override at the call site with `memo_key=`-The two approaches above are **type-level**: every memoized function sees the same fingerprint for a given object. To customize fingerprinting **only for a specific function**, pass `memo_key=` to `@coco.fn` (or `@coco.fn.as_async`). It maps parameter names to either a callable (transform the value before fingerprinting) or `None` (exclude the parameter entirely).+The approaches above are **type-level**: every memoized function sees the same fingerprint for a given object. To customize fingerprinting **only for a specific function**, pass `memo_key=` to `@coco.fn` (or `@coco.fn.as_async`). It maps parameter names to either a callable (transform the value before fingerprinting) or `None` (exclude the parameter entirely).</Lang>@@ -237,9 +343,16 @@ The two approaches above are **type-level**: every memoized function sees the sa<Fragment slot="python">```python[email protected](memo=True, memo_key={"entry": lambda e: (e.name, e.version), "extra": None})-def transform(entry: SourceDataEntry, extra: str) -> str:- ...+ memo=True,+ memo_key={+ "entry": lambda entry: (entry.name, entry.version),+ "request_id": None,+ },+)+def transform(entry: SourceDataEntry, request_id: str) -> str:+ # request_id is request metadata and does not affect the result.+ return f"{entry.name}@{entry.version}"```</Fragment>@@ -267,7 +380,7 @@ Each entry in `memo_key`:- **Callable** β applied to the argument; its return value is fingerprinted in place of the original. Semantically the same as `__coco_memo_key__()` on the type, but scoped to this one function. Useful when the type's default fingerprint is correct everywhere *else*, and only this function should treat the argument differently.- **`None`** β the parameter is excluded from the memo key. Changing its value never invalidates the cache. Useful for arguments that don't affect the result (logger handles, debug flags, request-scoped context that isn't part of the computation).-- **Not listed** β the parameter is fingerprinted normally (type-level `__coco_memo_key__`, registered handler, or default canonicalization).+- **Not listed** β the parameter is fingerprinted normally (type-level `__coco_memo_key__`, registered memo key function, or default canonicalization).It works for every parameter kind:@@ -302,16 +415,6 @@ async fn declare_nested(ctx: &Ctx, target: DirTarget, content: String) -> Result</Lang>-<Lang only="python">--:::tip[Picking the right tool]-- You control the type and the fingerprint is the same wherever it's used β **`__coco_memo_key__`**.-- You don't control the type but want a global handler β **`register_memo_key_function`**.-- Only *this* function should treat an argument specially (transform or skip it) β **`memo_key=`**.-:::--</Lang>-<Lang only="rust">:::tip[Picking the right tool]@@ -330,16 +433,16 @@ Sometimes fingerprint matching alone isn't enough to decide whether a cached res- **Async validation**: for an S3 object, send a HEAD request to check freshness β an inherently async operation.- **Stateful validation**: for HTTP resources, store the last fetch time and use `If-Modified-Since` on the next run.-Memo state validation addresses these by letting you attach a **state function** to your objects. It runs *after* a fingerprint match, giving you a chance to check freshness before the cached result is reused.+Memo state validation addresses these by letting you attach a **state function** to your objects. <Lang only="python">A state function captures initial state when a memo entry is created and, after a later fingerprint match, checks freshness before the cached result is reused. For ordinary function arguments, initial state is captured after a cache miss executes the function. For change-detected context values, initial state is captured when the value is provided.</Lang><Lang only="rust">It runs *after* a fingerprint match, giving you a chance to check freshness before the cached result is reused.</Lang>### How it works<Lang only="python">-When CocoIndex finds a fingerprint match, it calls each state function with the stored state from the previous run:+CocoIndex calls each state function with the state from the previous invocation:-1. **First run** (no previous state): `prev_state` is `coco.NON_EXISTENCE`. Use `coco.is_non_existence(prev_state)` to detect this.-2. **Subsequent runs**: `prev_state` is whatever you returned last time.+1. **Initial state capture**: `prev_state` is `coco.NON_EXISTENCE`. Use `coco.is_non_existence(prev_state)` to detect this.+2. **Validation after a later fingerprint match**: `prev_state` is whatever the state function returned previously.Your state function returns a `coco.MemoStateOutcome(state=..., memo_valid=...)`:@@ -414,7 +517,9 @@ class LocalFile:# Identity only β which file is it?return str(self.path.resolve())- def __coco_memo_state__(self, prev_state: tuple[int, str] | coco.NonExistenceType) -> coco.MemoStateOutcome:+ def __coco_memo_state__(+ self, prev_state: tuple[int, str] | coco.NonExistenceType+ ) -> coco.MemoStateOutcome:st = os.stat(self.path)new_mtime = st.st_mtime_nsif coco.is_non_existence(prev_state):@@ -429,7 +534,9 @@ class LocalFile:return coco.MemoStateOutcome(state=prev_state, memo_valid=True)# mtime changed β read content and check hashcontent_hash = hashlib.sha256(self.path.read_bytes()).hexdigest()- return coco.MemoStateOutcome(state=(new_mtime, content_hash), memo_valid=content_hash == prev_hash)+ return coco.MemoStateOutcome(+ state=(new_mtime, content_hash), memo_valid=content_hash == prev_hash+ )```</Fragment>@@ -484,24 +591,35 @@ This works for simple cases. State validation becomes useful when you need multi### Register a state function (when you don't control the type)-Pass a `state_fn` keyword argument to `register_memo_key_function`. The state function receives the object as its first argument and `prev_state` as its second. Annotate `prev_state` with the expected type:+Pass a `state_fn` keyword argument together with a callable `key_fn` to `register_memo_type`; `state_fn` cannot be registered by itself. The state function receives the object as its first argument and `prev_state` as its second. Annotate `prev_state` with the expected type:```pythonfrom pathlib import Path-from cocoindex import register_memo_key_function+import cocoindex as cocodef path_key(p: Path) -> object:return str(p.resolve())-def path_state(p: Path, prev_state: tuple[int, int] | coco.NonExistenceType) -> coco.MemoStateOutcome:+def path_state(+ p: Path, prev_state: tuple[int, int] | coco.NonExistenceType+) -> coco.MemoStateOutcome:st = p.stat()new_state = (st.st_mtime_ns, st.st_size)memo_valid = not coco.is_non_existence(prev_state) and new_state == prev_statereturn coco.MemoStateOutcome(state=new_state, memo_valid=memo_valid)-register_memo_key_function(Path, path_key, state_fn=path_state)+coco.register_memo_type(+ Path,+ path_key,+ state_fn=path_state,+ stable_type_id="stdlib.pathlib.Path/v1",+)```+A registered `state_fn` cannot be layered onto a type's own `__coco_memo_key__`. The intrinsic method takes precedence over registry functions, so neither the registered key function nor its state function is used. If you control the type, define `__coco_memo_state__` alongside `__coco_memo_key__`. The registry has no independent state-only attachment for a third-party type that already defines `__coco_memo_key__`.++Omit `stable_type_id` if the type does not need a stable type ID. When a type needs both state validation and a stable type ID, provide them in the same registration call.+</Lang><Lang only="rust">@@ -559,6 +677,7 @@ A state method can return an `Awaitable`. CocoIndex handles this automatically:- **In an async CocoIndex function**: awaitables from all state methods are gathered concurrently.- **In a sync CocoIndex function**: if no event loop is running, CocoIndex uses `asyncio.run()`. If a loop is already running, it raises an error β switch to an async function or use `@coco.fn.as_async`.+- **For change-detected context values**: initial state is captured synchronously at `builder.provide()`. If `builder.provide()` runs inside an active event loop, use a synchronous state function; an async state function must be initialized by providing the value outside that loop.```pythonimport cocoindex as coco@@ -735,7 +854,13 @@ In either case, attempting to use the type as a memo key raises a clear error.## Choosing keys and states- **Keep keys small and deterministic**: use identifiers and versions, not full payloads. No <Lang only="python">`id(obj)`, </Lang>pointer addresses, or random values.-- **Separate identity from freshness**: put stable identifiers (file path, URL, primary key) in the key. Put freshness checks (mtime, ETag, version) in the state.+- **Separate identity from freshness**: put stable key values (file path, URL, primary key) in the key. Put freshness checks (mtime, ETag, version) in the state.- **Use state validation for expensive checks**: if freshness validation is costly (content hashing, network calls), a state function lets you do it only when the fingerprint matches, and only when a cheap pre-check (mtime) fails.- **Use <Lang only="python">`MemoStateOutcome(state=new_state, memo_valid=True)`</Lang><Lang only="rust">`MemoStateDecision::new(&new_state, true)`</Lang> for cheap state updates**: when a cheap property changes (mtime) but the expensive check (content hash) confirms nothing meaningful changed, mark the memo valid while updating the state. This avoids re-executing the function and avoids re-checking the expensive property next time.- **<Lang only="python">Mark stateful types as `NotMemoKeyable`</Lang><Lang only="rust">Leave `MemoInput` unimplemented for stateful types</Lang>**: prevent subtle bugs from incorrect memoization of types with side effects.++<Lang only="python">++- **Choose stable type IDs deliberately**: use a globally unique, durable name, and bump its version when two type/schema versions should not share memo entries. Do not reuse a stable type ID for unrelated types.++</Lang>diff --git a/docs/src/content/docs/programming_guide/function.mdx b/docs/src/content/docs/programming_guide/function.mdxindex 5b672370..9d3e6434 100644--- a/docs/src/content/docs/programming_guide/function.mdx+++ b/docs/src/content/docs/programming_guide/function.mdx@@ -174,6 +174,8 @@ When a memoized function's cache hits, its **body does not run** β and neither<LangTabs><Fragment slot="python">+The fragment below omits the enclosing `App` and processing component. Treat the calls as invocations of the same processing component across successive application updates.+```python@coco.fn(memo=True)async def inner(text: str) -> str:@@ -185,11 +187,11 @@ async def outer(text: str) -> str:print("outer ran")return await inner(text) + "!"-# First call: both print, both bodies execute+# First component update: both print, both bodies execute.result = await outer("hello")-# Second call with same inputs: nothing prints β outer's cached value is returned-# directly, and inner is not invoked at all.+# Later component update with the same input: nothing prints. The cached value+# from outer is returned directly, and inner is not invoked at all.result = await outer("hello")```@@ -378,7 +380,7 @@ async fn summarize(_ctx: &Ctx, text: &str) -> Result<String> { /* ... */ }<Lang only="python">-The value is canonicalized through the [memoization-key pipeline](../advanced_topics/memoization_keys), which honors `__coco_memo_key__()`, registered memo key functions, and the standard handling for primitives, dataclasses, and Pydantic models.+The value is canonicalized through the [memoization-key pipeline](../advanced_topics/memoization_keys), including custom memo keys, registered memo key functions, stable type IDs, and built-in handling for primitives, containers, dataclasses, Pydantic models, and class objects.:::caution[Snapshotted at decoration time]`deps` is evaluated **once** when the decorator is applied (typically at module import), not re-evaluated per call. For per-call or per-instance values (instance attributes in a bound method, request-scoped config, anything that changes at runtime) pass them as regular function arguments instead, so the memoization layer observes each new value.diff --git a/python/cocoindex/_internal/api.py b/python/cocoindex/_internal/api.pyindex 240de6b4..6a3a20df 100644--- a/python/cocoindex/_internal/api.py+++ b/python/cocoindex/_internal/api.py@@ -111,7 +111,9 @@ from .runner import (from .memo_fingerprint import (memo_fingerprint,+ prev_type_id,register_memo_key_function,+ register_memo_type,NotMemoKeyable,)@@ -1012,7 +1014,9 @@ __all__ = ["serialize_by_pickle",# .memo_fingerprint"memo_fingerprint",+ "prev_type_id","register_memo_key_function",+ "register_memo_type","NotMemoKeyable",# .pending_marker"MaybePendingS",diff --git a/python/cocoindex/_internal/function.py b/python/cocoindex/_internal/function.pyindex ac846392..cb0ef9e6 100644--- a/python/cocoindex/_internal/function.py+++ b/python/cocoindex/_internal/function.py@@ -2245,7 +2245,8 @@ class _FunctionDecorator:string or model identifier. The value is canonicalized via thememoization-key pipeline (see:doc:`/advanced_topics/memoization_keys` for the full contract,- including ``__coco_memo_key__()`` and registered key functions)+ including ``__coco_memo_key__()``, registered memo key functions,+ stable type IDs, and built-in handling)and folded into the function's logic fingerprint; when thecanonical form changes, memoized results are invalidated andthe change propagates to callers according to ``logic_tracking``diff --git a/python/cocoindex/_internal/memo_fingerprint.py b/python/cocoindex/_internal/memo_fingerprint.pyindex 70737a90..8a15933e 100644--- a/python/cocoindex/_internal/memo_fingerprint.py+++ b/python/cocoindex/_internal/memo_fingerprint.py@@ -32,12 +32,13 @@ _KeyFn = typing.Callable[[typing.Any], typing.Any]_StateFn = typing.Callable[[typing.Any, typing.Any], typing.Any]-class _MemoFns(typing.NamedTuple):- key_fn: _KeyFn+class _MemoTypeRegistry(typing.NamedTuple):+ key_fn: _KeyFn | None = Nonestate_fn: _StateFn | None = None+ stable_type_id: str | None = None-_memo_fns: dict[type, _MemoFns] = {}+_memo_type_registry: dict[type, _MemoTypeRegistry] = {}class StateFnEntry(typing.NamedTuple):@@ -119,6 +120,174 @@ def canonical_module_name(obj: typing.Any) -> str:return mod+class _PreviousTypeId(str):+ """A prior automatic type identity carried through the stable-ID path."""++ __slots__ = ("_identity_parts",)+ _identity_parts: tuple[str, str]++ def __new__(cls, module: str, qualname: str) -> typing.Self:+ marker = super().__new__(cls, f"{len(module)}:{module}{qualname}")+ object.__setattr__(marker, "_identity_parts", (module, qualname))+ return marker++ def __setattr__(self, name: str, value: object) -> typing.NoReturn:+ raise AttributeError(f"{type(self).__name__} is immutable")++ def __delattr__(self, name: str) -> typing.NoReturn:+ raise AttributeError(f"{type(self).__name__} is immutable")++ def __reduce__(self) -> tuple[type[_PreviousTypeId], tuple[str, str]]:+ return type(self), self._identity_parts+++def prev_type_id(module: str, qualname: str) -> str:+ """Return a marker that reuses a type's prior automatic identity."""+ return _PreviousTypeId(module, qualname)+++def _register_memo_type_registry(typ: type, registry: _MemoTypeRegistry) -> None:+ """Register memo configuration for one exact Python type."""+ _memo_type_registry[typ] = registry+ _type_identity_cache.clear()+ _sync_plain_canonical_form_overridden()+++def _unregister_memo_type_registry(typ: type) -> None:+ """Best-effort removal of an exact-type memo registration."""+ _memo_type_registry.pop(typ, None)+ _type_identity_cache.clear()+ _sync_plain_canonical_form_overridden()+++_CLASS_OBJECT_OWNER_IDENTITY: tuple[Fingerprintable, Fingerprintable] = (+ canonical_module_name(type),+ type.__qualname__,+)+++# 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.+_type_identity_cache: dict[+ tuple[type, type | None, bool], 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.++ The stable type ID case still returns two parts to preserve the existing+ module/qualname identity shape used by type-aware canonical forms. The+ tagged first slot keeps stable type IDs disjoint from ordinary module+ names; ``None`` fills the qualname slot.++ ``fallback_owner`` anchors the automatic module/qualname identity to the+ type that owns a registered key function selected via MRO: the runtime+ type's own declared or registered stable ID still wins, but when no stable+ ID applies the identity stays with the key function's owner type.+ """+ key = (typ, fallback_owner, is_class_object)+ 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+ )+ return parts+++def _resolve_type_identity_parts(+ typ: type, fallback_owner: type | None, is_class_object: bool+) -> tuple[Fingerprintable, Fingerprintable]:+ stable_type_id = next(+ (+ vars(c)["__coco_memo_type_id__"]+ for c in typ.__mro__+ if "__coco_memo_type_id__" in vars(c)+ ),+ None,+ )+ 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:+ break+ registry = _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+ break+ if isinstance(stable_type_id, _PreviousTypeId):+ return stable_type_id._identity_parts+ if isinstance(stable_type_id, str):+ return (("__coco_memo_type_id__", stable_type_id), None)+ fallback_owner = typ if fallback_owner is None else fallback_owner+ return (+ canonical_module_name(fallback_owner),+ getattr(fallback_owner, "__qualname__", None),+ )+++def _canonicalize_registered_memo_key(+ obj: object,+ owner: type,+ registry: _MemoTypeRegistry,+ _seen: dict[int, int],+ state_methods: list[StateFnEntry],+) -> Fingerprintable:+ key_fn = registry.key_fn+ assert key_fn is not None+ key = key_fn(obj)+ tag = "hook"+ if registry.state_fn is not None:+ 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)+ return (+ tag,+ *identity,+ _canonicalize(key, _seen, state_methods),+ )+++def _canonicalize_class_object(+ cls: type,+ _seen: dict[int, int],+ state_methods: list[StateFnEntry],+) -> Fingerprintable:+ """Canonicalize a class object without invoking memo attributes on it."""++ metaclass: type = type(cls)+ for owner in metaclass.__mro__:+ if owner is object:+ break+ registry = _memo_type_registry.get(owner)+ if registry is not None and registry.key_fn is not None:+ return _canonicalize_registered_memo_key(+ cls, owner, registry, _seen, state_methods+ )++ return (+ "hook",+ *_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)),+ )++def _is_dataclass_instance(obj: object) -> bool:"""Check if obj is a dataclass instance (not a class)."""return dataclasses.is_dataclass(obj) and not isinstance(obj, type)@@ -143,8 +312,7 @@ def _canonicalize_dataclass(fields = dataclasses.fields(obj) # type: ignore[arg-type]return ("dataclass",- canonical_module_name(typ),- typ.__qualname__,+ *_type_identity_parts(typ),tuple((field.name, _canonicalize(getattr(obj, field.name), _seen, state_methods))for field in fields@@ -166,8 +334,7 @@ def _canonicalize_pydantic(field_names = obj.__pydantic_fields__.keys() # type: ignore[attr-defined]return ("pydantic",- canonical_module_name(typ),- typ.__qualname__,+ *_type_identity_parts(typ),tuple((name, _canonicalize(getattr(obj, name), _seen, state_methods))for name in field_names@@ -194,19 +361,86 @@ class NotMemoKeyable:)-def register_memo_key_function(- typ: type, key_fn: _KeyFn, *, state_fn: _StateFn | None = None-) -> None:- """Register a memo key function for a type.+def register_memo_type(+ typ: type,+ key_fn: _KeyFn,+ *,+ state_fn: _StateFn | None = None,+ stable_type_id: str | None = None,+) -> None: ...- Resolution is MRO-aware: the most specific registered base type wins.- If *state_fn* is provided it is stored separately and used for memo state- validation (see ``_canonicalize``).+def register_memo_type(+ typ: type,+ key_fn: None = None,+ *,+ state_fn: None = None,+ stable_type_id: str,+) -> None: ...+++def register_memo_type(+ typ: type,+ key_fn: _KeyFn | None = None,+ *,+ state_fn: _StateFn | None = None,+ stable_type_id: str | None = None,+) -> None:+ """Register a memo key function, state function, and/or stable type ID for a type.++ Key-function and stable-type-ID resolutions are MRO-aware: the most specific+ registered base type wins. Each call replaces the full registration for+ ``typ``: omitting ``stable_type_id`` clears any previous registered stable+ type ID, and omitting ``key_fn`` or passing ``None`` clears any previous+ key/state functions."""- _memo_fns[typ] = _MemoFns(key_fn, state_fn)- _sync_plain_canonical_form_overridden()+ if not isinstance(typ, type):+ raise TypeError(+ f"register_memo_type() expects typ to be a type, got {type(typ).__name__}"+ )+ if key_fn is None:+ if state_fn is not None:+ raise TypeError(+ "register_memo_type() state_fn requires a memo key function"+ )+ if stable_type_id is None:+ raise TypeError("register_memo_type() requires a key_fn or stable_type_id")+ elif not callable(key_fn):+ raise TypeError(+ f"register_memo_type() key_fn must be callable, got {type(key_fn).__name__}"+ )+ if state_fn is not None and not callable(state_fn):+ raise TypeError(+ "register_memo_type() state_fn must be callable, "+ f"got {type(state_fn).__name__}"+ )+ if stable_type_id is not None and not isinstance(stable_type_id, str):+ raise TypeError(+ "register_memo_type() stable_type_id must be a str, "+ f"got {type(stable_type_id).__name__}"+ )++ _register_memo_type_registry(+ typ,+ _MemoTypeRegistry(+ key_fn=key_fn,+ state_fn=state_fn,+ stable_type_id=stable_type_id,+ ),+ )+++def register_memo_key_function(+ typ: type,+ key_fn: _KeyFn,+ *,+ state_fn: _StateFn | None = None,+) -> None:+ """Shortcut for ``register_memo_type(typ, key_fn, state_fn=state_fn)``."""+ register_memo_type(typ, key_fn, state_fn=state_fn)def register_not_memo_keyable(typ: type) -> None:@@ -228,15 +462,14 @@ def register_not_memo_keyable(typ: type) -> None:"This type maintains internal state that is incompatible with memoization.")- _memo_fns[typ] = _MemoFns(_raise_not_memo_keyable)- _sync_plain_canonical_form_overridden()+ _register_memo_type_registry(typ, _MemoTypeRegistry(key_fn=_raise_not_memo_keyable))-def unregister_memo_key_function(typ: type) -> None:- """Remove a previously registered memo key function (best-effort)."""+def unregister_memo_type(typ: type) -> None:+ """Remove registered memo configuration for a type."""- _memo_fns.pop(typ, None)- _sync_plain_canonical_form_overridden()+ if isinstance(typ, type):+ _unregister_memo_type_registry(typ)# The container types the native plain-data walker handles. A memo key function@@ -247,7 +480,10 @@ _PLAIN_CONTAINER_BASES = frozenset({dict, list, tuple, object})def _sync_plain_canonical_form_overridden() -> None:"""Tell the native plain-data walker whether it still applies."""core.set_plain_canonical_form_overridden(- not _memo_fns.keys().isdisjoint(_PLAIN_CONTAINER_BASES)+ any(+ _memo_type_registry[t].key_fn is not None+ for t in _PLAIN_CONTAINER_BASES & _memo_type_registry.keys()+ ))@@ -299,7 +535,11 @@ def _canonicalize(if isinstance(obj, (bytearray, memoryview)):return bytes(obj)- # 2) Hook / registry (apply once, then recurse on returned key fragment)+ # 2) Memo key dispatch. Raw class objects skip memo attributes but honor+ # explicit key registrations on their metaclass MRO.+ if isinstance(obj, type):+ return _canonicalize_class_object(obj, _seen, state_methods)+hook = getattr(obj, "__coco_memo_key__", None)if hook is not None and callable(hook):k = hook()@@ -313,25 +553,15 @@ def _canonicalize(state_methods.append(_make_state_fn_entry(state_hook, raw_fn))return (tag,- canonical_module_name(typ),- typ.__qualname__,+ *_type_identity_parts(typ),_canonicalize(k, _seen, state_methods),)for base in type(obj).__mro__:- memo = _memo_fns.get(base)- if memo is not None:- k = memo.key_fn(obj)- tag = "hook"- if memo.state_fn is not None:- tag = "shook"- bound = functools.partial(memo.state_fn, obj)- state_methods.append(_make_state_fn_entry(bound, memo.state_fn))- return (- tag,- canonical_module_name(base),- base.__qualname__,- _canonicalize(k, _seen, state_methods),+ memo = _memo_type_registry.get(base)+ if memo is not None and memo.key_fn is not None:+ return _canonicalize_registered_memo_key(+ obj, base, memo, _seen, state_methods)# 3) Cycle tracking@@ -468,18 +698,13 @@ def fingerprint_call(return core.fingerprint_simple_object(call_key_obj)-# Register memo key for class types.-register_memo_key_function(- type,- lambda cls: (canonical_module_name(cls), getattr(cls, "__qualname__", None)),-)--__all__ = ["NotMemoKeyable",+ "prev_type_id","register_memo_key_function",+ "register_memo_type","register_not_memo_keyable",- "unregister_memo_key_function",+ "unregister_memo_type","fingerprint_call","memo_fingerprint",]diff --git a/python/tests/core/test_function_memo.py b/python/tests/core/test_function_memo.pyindex 4e4abc07..2ac32f1d 100644--- a/python/tests/core/test_function_memo.py+++ b/python/tests/core/test_function_memo.py@@ -27,6 +27,43 @@ class SourceDataEntry:return (self.name, self.version)+@dataclass(frozen=True)+class _StableOldEntry:+ name: str+ version: int+ content: str++ __coco_memo_type_id__ = "test.FunctionMemoEntry/v1"+++@dataclass(frozen=True)+class _StableNewEntry:+ name: str+ version: int+ content: str++ __coco_memo_type_id__ = "test.FunctionMemoEntry/v1"+++@dataclass(frozen=True)+class _PreviousIdentityOldEntry:+ name: str+ version: int+ content: str+++@dataclass(frozen=True)+class _PreviousIdentityMovedEntry:+ name: str+ version: int+ content: str++ __coco_memo_type_id__ = coco.prev_type_id(+ _PreviousIdentityOldEntry.__module__,+ _PreviousIdentityOldEntry.__qualname__,+ )++@dataclassclass DictSourceDataEntry:name: str@@ -38,6 +75,8 @@ class DictSourceDataEntry:_plain_source_data: dict[str, SourceDataEntry] = {}+_stable_type_source_data: dict[str, object] = {}+_dict_source_data: dict[str, DictSourceDataEntry] = {}_metrics = Metrics()@@ -55,6 +94,89 @@ def _process_plain_source_data() -> None:coco.declare_target_state(GlobalDictTarget.target_state(key, transformed_value))[email protected](memo=True)+def _transform_stable_type_entry(entry: object) -> str:+ _metrics.increment("call.transform_stable_type_entry")+ return f"processed: {getattr(entry, 'content')}"+++def _process_stable_type_source_data() -> None:+ for key, value in _stable_type_source_data.items():+ transformed_value = _transform_stable_type_entry(value)+ coco.declare_target_state(GlobalDictTarget.target_state(key, transformed_value))+++def test_stable_type_id_reuses_memo_across_renamed_dataclass() -> None:+ GlobalDictTarget.store.clear()+ _stable_type_source_data.clear()+ _metrics.clear()++ app = coco.App(+ coco.AppConfig(+ name="test_stable_type_id_reuses_memo_across_renamed_dataclass",+ environment=coco_env,+ ),+ _process_stable_type_source_data,+ )++ _stable_type_source_data["A"] = _StableOldEntry(+ name="A", version=1, content="contentA1"+ )+ app.update_blocking()+ assert _metrics.collect() == {"call.transform_stable_type_entry": 1}+ assert GlobalDictTarget.store.data["A"].data == "processed: contentA1"++ _stable_type_source_data["A"] = _StableNewEntry(+ name="A", version=1, content="contentA1"+ )+ app.update_blocking()+ assert _metrics.collect() == {}+ assert GlobalDictTarget.store.data["A"].data == "processed: contentA1"++ _stable_type_source_data["A"] = _StableNewEntry(+ name="A", version=2, content="contentA2"+ )+ app.update_blocking()+ assert _metrics.collect() == {"call.transform_stable_type_entry": 1}+ assert GlobalDictTarget.store.data["A"].data == "processed: contentA2"+++def test_prev_type_id_reuses_existing_memo_after_dataclass_move() -> None:+ GlobalDictTarget.store.clear()+ _stable_type_source_data.clear()+ _metrics.clear()++ app = coco.App(+ coco.AppConfig(+ name="test_prev_type_id_reuses_existing_memo_after_dataclass_move",+ environment=coco_env,+ ),+ _process_stable_type_source_data,+ )++ _stable_type_source_data["A"] = _PreviousIdentityOldEntry(+ name="A", version=1, content="contentA1"+ )+ app.update_blocking()+ assert _metrics.collect() == {"call.transform_stable_type_entry": 1}+ assert GlobalDictTarget.store.data["A"].data == "processed: contentA1"++ _stable_type_source_data["A"] = _PreviousIdentityMovedEntry(+ name="A", version=1, content="contentA1"+ )+ app.update_blocking()+ assert _metrics.collect() == {}+ assert GlobalDictTarget.store.data["A"].data == "processed: contentA1"++ _stable_type_source_data["A"] = _PreviousIdentityMovedEntry(+ name="A", version=2, content="contentA2"+ )+ app.update_blocking()+ assert _metrics.collect() == {"call.transform_stable_type_entry": 1}+ assert GlobalDictTarget.store.data["A"].data == "processed: contentA2"++def test_memo_pure_function() -> None:GlobalDictTarget.store.clear()_plain_source_data.clear()diff --git a/python/tests/core/test_memo_state_validation.py b/python/tests/core/test_memo_state_validation.pyindex 089f76a3..aee484d3 100644--- a/python/tests/core/test_memo_state_validation.py+++ b/python/tests/core/test_memo_state_validation.py@@ -16,6 +16,7 @@ import pytestimport cocoindex as coco+from cocoindex._internal.memo_fingerprint import unregister_memo_typefrom tests import commonfrom tests.common.target_states import (DictDataWithPrev,@@ -962,3 +963,158 @@ def test_state_refresh_keeps_targets_and_nested_entries() -> None:"A": "outer: c1","A/inner": "inner: c1",}+++# ============================================================================+# Raw class-object metaclass memo methods are ignored (sync)+# ============================================================================++_class_object_source: dict[str, type] = {}+_class_object_prev_states: list[Any] = []+++class _ClassObjectMemoMeta(type):+ def __coco_memo_key__(cls) -> object:+ raise AssertionError("class objects must not call metaclass memo key")++ def __coco_memo_state__(cls, prev_state: Any) -> coco.MemoStateOutcome:+ _class_object_prev_states.append(prev_state)+ raise AssertionError("class objects must not call metaclass memo state")+++def _make_class_object(+ stable_key: str,+ state_value: int,+ content: str,+ stable_type_id: str | None = None,+) -> type:+ attrs: dict[str, object] = {+ "stable_key": stable_key,+ "state_value": state_value,+ "content": content,+ }+ if stable_type_id is not None:+ attrs["__coco_memo_type_id__"] = stable_type_id+ return _ClassObjectMemoMeta(+ f"ClassObject_{stable_key}_{state_value}_{content}",+ (),+ attrs,+ )++[email protected](memo=True)+def _transform_class_object(cls: type) -> str:+ _metrics.increment("call.transform_class_object")+ return f"class content: {getattr(cls, 'content')}"+++def _process_class_objects() -> None:+ for key, cls in _class_object_source.items():+ result = _transform_class_object(cls)+ coco.declare_target_state(GlobalDictTarget.target_state(key, result))+++def test_class_object_metaclass_memo_methods_are_ignored_sync() -> None:+ """Class objects use stable type IDs and never call metaclass memo methods."""+ GlobalDictTarget.store.clear()+ _class_object_source.clear()+ _class_object_prev_states.clear()+ _metrics.clear()++ app = coco.App(+ coco.AppConfig(+ name="test_class_object_metaclass_memo_methods_are_ignored_sync",+ environment=coco_env,+ ),+ _process_class_objects,+ )++ stable_type_id = "test.ClassObjectMemo/v1"+ cls = _make_class_object("stable", 1, "A", stable_type_id)++ # Run 1: the transform executes and no metaclass memo methods are called.+ _class_object_source["row"] = cls+ app.update_blocking()+ assert _metrics.collect() == {"call.transform_class_object": 1}+ assert _class_object_prev_states == []+ assert GlobalDictTarget.store.data == {+ "row": DictDataWithPrev(+ data="class content: A", prev=[], prev_may_be_missing=True+ )+ }++ # Run 2: a distinct class object with the same stable type ID is a cache hit.+ # Class schema/state changes are intentionally not part of the class-object+ # fingerprint; users who depend on them must include them with `memo_key=`.+ _class_object_source["row"] = _make_class_object("renamed", 2, "B", stable_type_id)+ app.update_blocking()+ assert _metrics.collect() == {}+ assert _class_object_prev_states == []+ assert GlobalDictTarget.store.data["row"].data == "class content: A"++ # Run 3: a distinct stable type ID changes the fingerprint, so the transform+ # re-executes and the previous target state is made available.+ _class_object_source["row"] = _make_class_object(+ "changed", 3, "C", "test.ClassObjectMemo/v2"+ )+ app.update_blocking()+ assert _metrics.collect() == {"call.transform_class_object": 1}+ assert _class_object_prev_states == []+ assert GlobalDictTarget.store.data == {+ "row": DictDataWithPrev(+ data="class content: C",+ prev=["class content: A"],+ prev_may_be_missing=False,+ )+ }+++def test_class_object_registered_metaclass_memo_state_sync() -> None:+ GlobalDictTarget.store.clear()+ _class_object_source.clear()+ _class_object_prev_states.clear()+ _metrics.clear()++ def class_object_key(cls: Any) -> object:+ return cls.stable_key++ def class_object_state(cls: Any, prev_state: Any) -> coco.MemoStateOutcome:+ return coco.MemoStateOutcome(+ state=cls.state_value,+ memo_valid=(+ not coco.is_non_existence(prev_state) and cls.state_value == prev_state+ ),+ )++ coco.register_memo_key_function(+ _ClassObjectMemoMeta,+ class_object_key,+ state_fn=class_object_state,+ )+ try:+ app = coco.App(+ coco.AppConfig(+ name="test_class_object_registered_metaclass_memo_state_sync",+ environment=coco_env,+ ),+ _process_class_objects,+ )++ _class_object_source["row"] = _make_class_object("row", 1, "A")+ app.update_blocking()+ assert _metrics.collect() == {"call.transform_class_object": 1}+ assert GlobalDictTarget.store.data["row"].data == "class content: A"++ _class_object_source["row"] = _make_class_object("row", 1, "B")+ app.update_blocking()+ assert _metrics.collect() == {}+ assert GlobalDictTarget.store.data["row"].data == "class content: A"++ _class_object_source["row"] = _make_class_object("row", 2, "C")+ app.update_blocking()+ assert _metrics.collect() == {"call.transform_class_object": 1}+ assert GlobalDictTarget.store.data["row"].data == "class content: C"+ assert _class_object_prev_states == []+ finally:+ unregister_memo_type(_ClassObjectMemoMeta)diff --git a/python/tests/core/test_value_fingerprint_tracking.py b/python/tests/core/test_value_fingerprint_tracking.pyindex fde99921..b9b97116 100644--- a/python/tests/core/test_value_fingerprint_tracking.py+++ b/python/tests/core/test_value_fingerprint_tracking.py@@ -10,7 +10,7 @@ import pytestimport cocoindex as cocofrom cocoindex._internal.memo_fingerprint import (register_memo_key_function,- unregister_memo_key_function,+ unregister_memo_type,)from cocoindex.connectorkits.fingerprint import fingerprint_object@@ -344,7 +344,7 @@ def test_memo_key_function_for_a_plain_type_keeps_reconcile_in_charge() -> None:assert _store.take_reconciles() == [_ReconcileCall("a", 1, False)]assert _store.data == {"a": (1, 2)}finally:- unregister_memo_key_function(tuple)+ unregister_memo_type(tuple)# Back to the default canonical form: the record no longer matches.app.update_blocking()diff --git a/python/tests/internal/test_memo_fingerprint.py b/python/tests/internal/test_memo_fingerprint.pyindex 38d8196b..3830345d 100644--- a/python/tests/internal/test_memo_fingerprint.py+++ b/python/tests/internal/test_memo_fingerprint.py@@ -3,10 +3,14 @@ import copyimport dataclassesimport enumimport math-from typing import Any+import pickle+import sys+from typing import Any, Callable, ClassVar, castimport pytest+# The two public names, imported the way users import them.+from cocoindex import prev_type_id, register_memo_typefrom cocoindex._internal import corefrom cocoindex._internal.function import _apply_memo_key, _normalize_memo_keyfrom cocoindex._internal.memo_fingerprint import (@@ -14,7 +18,8 @@ from cocoindex._internal.memo_fingerprint import (fingerprint_call,memo_fingerprint,register_memo_key_function,- unregister_memo_key_function,+ register_not_memo_keyable,+ unregister_memo_type,)from cocoindex._internal.typing import MemoStateOutcome@@ -95,7 +100,7 @@ def test_registry_overrides_default_behavior() -> None:assert fp_a == fp_irrelevant_changedassert fp_a != fp_bfinally:- unregister_memo_key_function(Y)+ unregister_memo_type(Y)def test_hook_and_registry_include_type_name_to_avoid_collisions() -> None:@@ -134,8 +139,611 @@ def test_hook_and_registry_include_type_name_to_avoid_collisions() -> None:_dummy_fn, (D(1),), {}, [])finally:- unregister_memo_key_function(C)- unregister_memo_key_function(D)+ unregister_memo_type(C)+ unregister_memo_type(D)+++# Stable type IDs: each case builds two values and states whether they+# fingerprint the same. Registrations made through `_Case.register` are removed+# after the case runs.++_OLD_MODULE = "old_package.models"+++class _Keyed:+ """Keyed by its value through ``__coco_memo_key__``."""++ def __init__(self, value: object, ignored: object = None) -> None:+ self.value = value+ self.ignored = ignored++ def __coco_memo_key__(self) -> object:+ return ("entry", self.value)+++class _Unkeyed:+ """No memo key of its own; a registered key function supplies one."""++ def __init__(self, value: object, ignored: object = None) -> None:+ self.value = value+ self.ignored = ignored+++def _value_key(entry: Any) -> object:+ # The key `_Keyed` returns, so a value keyed by a registered function and a+ # `_Keyed` value fingerprint the same exactly when their type identities do.+ return ("entry", entry.value)+++def _derive(base: type, name: str, module: str | None = None, **attrs: Any) -> Any:+ """Subclass *base*, keeping its metaclass, as if declared as *name* in *module*."""+ cls = type(base)(name, (base,), attrs)+ if module is not None:+ cls.__module__ = module+ return cls+++class _Case:+ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None:+ self.monkeypatch = monkeypatch+ self.registered: list[type] = []++ def register(+ self,+ typ: type,+ *args: Any,+ via: Callable[..., None] = register_memo_type,+ **kwargs: Any,+ ) -> None:+ via(typ, *args, **kwargs)+ self.registered.append(typ)+++_Build = Callable[[_Case], tuple[object, object]]+++def _declared_id_survives_module_move(case: _Case) -> tuple[object, object]:+ old = _derive(_Keyed, "Entry", _OLD_MODULE, __coco_memo_type_id__="test.Entry/v1")+ new = _derive(_Keyed, "Entry", "new_package", __coco_memo_type_id__="test.Entry/v1")+ return old(1), new(1)+++def _declared_id_versions_differ(case: _Case) -> tuple[object, object]:+ v1 = _derive(_Keyed, "Entry", __coco_memo_type_id__="test.Entry/v1")+ v2 = _derive(_Keyed, "Entry", __coco_memo_type_id__="test.Entry/v2")+ return v1(1), v2(1)+++def _pydantic_declared_id_survives_rename(case: _Case) -> tuple[object, object]:+ try:+ from pydantic import BaseModel+ except ImportError:+ pytest.skip("pydantic not installed")++ class Old(BaseModel):+ __coco_memo_type_id__: ClassVar[str] = "test.Model/v1"+ value: int++ class New(BaseModel):+ __coco_memo_type_id__: ClassVar[str] = "test.Model/v1"+ value: int++ return Old(value=1), New(value=1)+++def _declared_id_is_inherited(case: _Case) -> tuple[object, object]:+ base = _derive(_Keyed, "Base", __coco_memo_type_id__="test.Base/v1")+ return _derive(base, "Sub")(1), base(1)+++def _subclass_redeclares_id(case: _Case) -> tuple[object, object]:+ base = _derive(_Keyed, "Base", __coco_memo_type_id__="test.Base/v1")+ sub = _derive(base, "Sub", __coco_memo_type_id__="test.Sub/v1")+ return sub(1), base(1)+++def _inherited_declared_id_beats_own_registration(case: _Case) -> tuple[object, object]:+ base = _derive(_Keyed, "Base", __coco_memo_type_id__="test.Base/v1")+ sub = _derive(base, "Sub")+ case.register(sub, stable_type_id="test.Sub/v1")+ return sub(1), base(1)+++def _non_str_declared_id(declared: object) -> _Build:+ def build(case: _Case) -> tuple[object, object]:+ # Shadows the base's ID, and is then ignored like a missing one.+ base = _derive(_Keyed, "Base", __coco_memo_type_id__="test.Base/v1")+ entry = _derive(base, "Entry", __coco_memo_type_id__=declared)+ twin = _derive(_Keyed, "Twin")+ case.register(entry, stable_type_id="test.Registered/v1")+ case.register(twin, stable_type_id="test.Registered/v1")+ return entry(1), twin(1)++ return build+++def _metaclass_declared_id(class_objects: bool) -> _Build:+ def build(case: _Case) -> tuple[object, object]:+ class FamilyMeta(type):+ __coco_memo_type_id__ = "test.Family/v1"++ @dataclasses.dataclass+ class Row1(metaclass=FamilyMeta):+ x: int++ @dataclasses.dataclass+ class Row2(metaclass=FamilyMeta):+ x: int++ return (Row1, Row2) if class_objects else (Row1(x=1), Row2(x=1))++ return build+++def _old_and_moved(marker: str) -> tuple[Any, Any]:+ old = _derive(_Keyed, "SourceEntry", _OLD_MODULE)+ moved = _derive(_Keyed, "Moved", __coco_memo_type_id__=marker)+ return old, moved+++def _prev_type_id_matches_old_identity(case: _Case) -> tuple[object, object]:+ old, moved = _old_and_moved(prev_type_id(_OLD_MODULE, "SourceEntry"))+ return old(1), moved(1)+++def _prev_type_id_matches_old_class_object(case: _Case) -> tuple[object, object]:+ return _old_and_moved(prev_type_id(_OLD_MODULE, "SourceEntry"))+++def _prev_type_id_names_another_type(case: _Case) -> tuple[object, object]:+ old, moved = _old_and_moved(prev_type_id(_OLD_MODULE, "OtherEntry"))+ return old(1), moved(1)+++def _string_id_never_matches_automatic_identity(case: _Case) -> tuple[object, object]:+ old, moved = _old_and_moved(f"{_OLD_MODULE}.SourceEntry")+ return old(1), moved(1)+++def _prev_type_id_survives_pickling(case: _Case) -> tuple[object, object]:+ marker = pickle.loads(pickle.dumps(prev_type_id(_OLD_MODULE, "SourceEntry")))+ old, moved = _old_and_moved(marker)+ return old(1), moved(1)+++def _prev_type_id_names_main_by_script(case: _Case) -> tuple[object, object]:+ main = sys.modules["__main__"]+ case.monkeypatch.setattr(main, "__file__", "/tmp/main.py", raising=False)+ old = _derive(_Keyed, "SourceEntry", "__main__")+ moved = _derive(+ _Keyed, "Moved", __coco_memo_type_id__=prev_type_id("main", "SourceEntry")+ )+ return old(1), moved(1)+++def _prev_type_id_on_base_reaches_subclass(case: _Case) -> tuple[object, object]:+ old = _derive(_Keyed, "SourceBase", _OLD_MODULE)+ moved = _derive(+ _Keyed,+ "MovedBase",+ __coco_memo_type_id__=prev_type_id(_OLD_MODULE, "SourceBase"),+ )+ return _derive(moved, "MovedSub")(1), old(1)+++def _prev_type_id_for_registered_key_owner(case: _Case) -> tuple[object, object]:+ old = _derive(_Unkeyed, "SourceBase", _OLD_MODULE)+ moved = _derive(_Unkeyed, "MovedBase")+ case.register(old, _value_key)+ case.register(+ moved, _value_key, stable_type_id=prev_type_id(_OLD_MODULE, "SourceBase")+ )+ return _derive(old, "Child")(1), _derive(moved, "Child")(1)+++def _none_declared_id_shadows_key_owner_id(case: _Case) -> tuple[object, object]:+ # `None` on Child hides Base's declared ID, so the automatic fallback is+ # Base's module and qualified name, not its declared ID.+ base = _derive(_Unkeyed, "Base", _OLD_MODULE, __coco_memo_type_id__="test.Base/v1")+ case.register(base, _value_key)+ child = _derive(base, "Child", __coco_memo_type_id__=None)+ ref = _derive(+ _Keyed, "Ref", __coco_memo_type_id__=prev_type_id(_OLD_MODULE, "Base")+ )+ return child(1), ref(1)+++def _prev_type_id_for_registered_metaclass(case: _Case) -> tuple[object, object]:+ old = _derive(type, "SourceMeta", _OLD_MODULE)+ moved = _derive(type, "MovedMeta")+ case.register(old, lambda cls: "class")+ case.register(+ moved,+ lambda cls: "class",+ stable_type_id=prev_type_id(_OLD_MODULE, "SourceMeta"),+ )+ return old("Entry", (), {}), moved("Entry", (), {})+++def _registered_id_without_key_fn(case: _Case) -> tuple[object, object]:+ old, new = _derive(_Keyed, "Old"), _derive(_Keyed, "New")+ case.register(old, stable_type_id="test.Entry/v1")+ case.register(new, state_fn=None, stable_type_id="test.Entry/v1")+ return old(1), new(1)+++def _registered_id_reaches_subclass(class_objects: bool) -> _Build:+ def build(case: _Case) -> tuple[object, object]:+ parent = _derive(_Keyed, "Parent")+ child = _derive(parent, "Child")+ case.register(parent, stable_type_id="test.Parent/v1")+ return (child, parent) if class_objects else (child(1), parent(1))++ return build+++def _subclass_registration_overrides_base_id(case: _Case) -> tuple[object, object]:+ parent = _derive(_Keyed, "Parent")+ child = _derive(parent, "Child")+ case.register(parent, stable_type_id="test.Parent/v1")+ case.register(child, stable_type_id="test.Child/v1")+ return child(1), parent(1)+++def _registered_key_owner_id_reaches_subclass(case: _Case) -> tuple[object, object]:+ base = _derive(_Unkeyed, "Base")+ case.register(base, _value_key, stable_type_id="test.Base/v1")+ ref = _derive(_Keyed, "Ref", __coco_memo_type_id__="test.Base/v1")+ return _derive(base, "Sub")(1, "ignored"), ref(1)+++def _subclass_id_beats_registered_key_owner_id(declared: bool) -> _Build:+ def build(case: _Case) -> tuple[object, object]:+ # The base's key function still applies; only the identity changes.+ base = _derive(_Unkeyed, "Base")+ case.register(base, _value_key, stable_type_id="test.Base/v1")+ if declared:+ sub = _derive(base, "Sub", __coco_memo_type_id__="test.Sub/v1")+ else:+ sub = _derive(base, "Sub")+ case.register(sub, stable_type_id="test.Sub/v1")+ ref = _derive(_Keyed, "Ref", __coco_memo_type_id__="test.Sub/v1")+ return sub(1, "ignored"), ref(1)++ return build+++def _declared_id_beats_key_owner_registration(case: _Case) -> tuple[object, object]:+ base = _derive(_Unkeyed, "Base", __coco_memo_type_id__="test.Declared/v1")+ case.register(base, _value_key, stable_type_id="test.Registered/v1")+ ref = _derive(_Keyed, "Ref", __coco_memo_type_id__="test.Declared/v1")+ return _derive(base, "Sub")(1), ref(1)+++def _own_memo_key_beats_registration(case: _Case) -> tuple[object, object]:+ def must_not_run(*args: object) -> object:+ raise AssertionError("the type's own memo key wins over its registration")++ entry = _derive(_Keyed, "Entry", __coco_memo_type_id__="test.Declared/v1")+ case.register(+ entry, must_not_run, state_fn=must_not_run, stable_type_id="test.Registered/v1"+ )+ twin = _derive(_Keyed, "Twin", __coco_memo_type_id__="test.Declared/v1")+ return entry(1), twin(1)+++def _class_object_ignores_own_memo_key(case: _Case) -> tuple[object, object]:+ def must_not_run(*args: object) -> object:+ raise AssertionError("class objects never call __coco_memo_key__")++ attrs = {"__coco_memo_type_id__": "test.Class/v1"}+ old = _derive(object, "Old", __coco_memo_key__=staticmethod(must_not_run), **attrs)+ new = _derive(object, "New", __coco_memo_key__=classmethod(must_not_run), **attrs)+ return old, new+++def _registered_id_applies_to_class_objects(case: _Case) -> tuple[object, object]:+ old, new = _derive(_Unkeyed, "Old"), _derive(_Unkeyed, "New")+ case.register(old, stable_type_id="test.Class/v1")+ case.register(new, stable_type_id="test.Class/v1")+ return old, new+++def _class_object_key_registered_on(metaclass: bool) -> _Build:+ def build(case: _Case) -> tuple[object, object]:+ # A class keyed through its metaclass, or through `type` further up the+ # metaclass's MRO, takes the stable type ID registered with the key function.+ meta = _derive(type, "Meta")+ case.register(+ meta if metaclass else type,+ lambda cls: ("entry", 1),+ stable_type_id="test.Key/v1",+ )+ ref = _derive(_Keyed, "Ref", __coco_memo_type_id__="test.Key/v1")+ return meta("Entry", (), {}), ref(1)++ return build+++def _class_object_ignores_own_id_under_key_owner(declared: bool) -> _Build:+ def build(case: _Case) -> tuple[object, object]:+ # A metaclass key function with its own ID; the classes' own, differing+ # declared IDs or registrations do not apply to the class values.+ meta = _derive(type, "Meta")+ case.register(meta, lambda cls: "same", stable_type_id="test.Meta/v1")+ base = meta("Base", (_Unkeyed,), {})+ ids = ("test.Own/v1", "test.Other/v1")+ if declared:+ return (+ _derive(base, "One", __coco_memo_type_id__=ids[0]),+ _derive(base, "Two", __coco_memo_type_id__=ids[1]),+ )+ one, two = _derive(base, "One"), _derive(base, "Two")+ case.register(one, stable_type_id=ids[0])+ case.register(two, stable_type_id=ids[1])+ return one, two++ return build+++def _class_objects_ignore_object_key_fn(case: _Case) -> tuple[object, object]:+ case.register(object, lambda obj: "same", stable_type_id="test.Object/v1")+ return _derive(_Unkeyed, "Entry"), _derive(_Unkeyed, "Other")+++def _class_object_distinct_from_its_instance(+ case: _Case,+) -> tuple[object, object]:+ # The class takes the metaclass identity while the instance takes the+ # class identity, so the same payload and state do not collide.+ meta = _derive(type, "Meta")+ base = meta("Base", (_Unkeyed,), {})+ entry = _derive(+ base,+ "Entry",+ __coco_memo_type_id__="test.Entry/v1",+ __coco_memo_key__=lambda self: ("same", "payload"),+ __coco_memo_state__=lambda self, prev: None,+ )+ case.register(+ meta,+ lambda cls: ("same", "payload"),+ state_fn=lambda cls, prev: None,+ )+ return entry, entry(1)+++def _reregistering_drops_state_fn(case: _Case) -> tuple[object, object]:+ entry, twin = _derive(_Unkeyed, "Entry"), _derive(_Unkeyed, "Twin")+ case.register(+ entry, _value_key, state_fn=lambda e, prev: prev, stable_type_id="test.Entry/v1"+ )+ case.register(entry, _value_key, stable_type_id="test.Entry/v1")+ case.register(twin, _value_key, stable_type_id="test.Entry/v1")+ return entry(1), twin(1)+++def _reregistering_drops_stable_id(via: Callable[..., None]) -> _Build:+ def build(case: _Case) -> tuple[object, object]:+ entry, twin = _derive(_Unkeyed, "Entry"), _derive(_Unkeyed, "Twin")+ case.register(entry, _value_key, stable_type_id="test.Entry/v1")+ case.register(entry, _value_key, via=via)+ case.register(twin, _value_key, stable_type_id="test.Entry/v1")+ return entry(1), twin(1)++ return build+++def _reregistering_drops_key_fn(case: _Case) -> tuple[object, object]:+ entry = dataclasses.make_dataclass("Entry", ["value", "ignored"])+ case.register(entry, _value_key)+ case.register(entry, stable_type_id="test.Entry/v1")+ return entry(1, "a"), entry(1, "b")+++def _not_memo_keyable_drops_stable_id(case: _Case) -> tuple[object, object]:+ entry, twin = _derive(_Unkeyed, "Entry"), _derive(_Unkeyed, "Twin")+ case.register(entry, stable_type_id="test.Entry/v1")+ case.register(entry, via=register_not_memo_keyable)+ case.register(twin, stable_type_id="test.Entry/v1")+ return entry, twin+++def _registration_after_first_fingerprint(case: _Case) -> tuple[object, object]:+ # The first fingerprint resolves Entry's identity before any registration.+ entry, twin = _derive(_Keyed, "Entry"), _derive(_Keyed, "Twin")+ memo_fingerprint(entry(1))+ case.register(entry, stable_type_id="test.Entry/v1")+ case.register(twin, stable_type_id="test.Entry/v1")+ return entry(1), twin(1)+++def _unregistration_after_first_fingerprint(case: _Case) -> tuple[object, object]:+ entry, twin = _derive(_Keyed, "Entry"), _derive(_Keyed, "Twin")+ case.register(entry, stable_type_id="test.Entry/v1")+ case.register(twin, stable_type_id="test.Entry/v1")+ memo_fingerprint(entry(1))+ unregister_memo_type(entry)+ return entry(1), twin(1)+++def _memo_key_leads_back_to_parent(registered: bool) -> _Build:+ def build(case: _Case) -> tuple[object, object]:+ def parent_key(node: Any) -> object:+ return node.value++ if registered:+ node = _derive(_Unkeyed, "Node")+ case.register(node, parent_key)+ else:+ node = _derive(_Unkeyed, "Node", __coco_memo_key__=parent_key)++ def graph() -> list[object]:+ parent: list[object] = []+ parent.append(node(parent))+ return parent++ return graph(), graph()++ return build+++ ("build", "same"),+ [+ # Declared IDs+ pytest.param(_declared_id_survives_module_move, True, id="declared-moved"),+ pytest.param(_declared_id_versions_differ, False, id="declared-versions"),+ pytest.param(+ _pydantic_declared_id_survives_rename, True, id="declared-pydantic"+ ),+ pytest.param(_declared_id_is_inherited, True, id="declared-inherited"),+ pytest.param(_subclass_redeclares_id, False, id="declared-overridden"),+ pytest.param(+ _inherited_declared_id_beats_own_registration,+ True,+ id="declared-beats-registered",+ ),+ pytest.param(_non_str_declared_id(None), True, id="declared-none"),+ pytest.param(_non_str_declared_id(12345), True, id="declared-non-str"),+ pytest.param(_metaclass_declared_id(False), False, id="metaclass-instances"),+ pytest.param(_metaclass_declared_id(True), False, id="metaclass-classes"),+ # prev_type_id+ pytest.param(_prev_type_id_matches_old_identity, True, id="prev-instance"),+ pytest.param(_prev_type_id_matches_old_class_object, True, id="prev-class"),+ pytest.param(_prev_type_id_names_another_type, False, id="prev-other-type"),+ pytest.param(+ _string_id_never_matches_automatic_identity, False, id="string-id-tagged"+ ),+ pytest.param(_prev_type_id_survives_pickling, True, id="prev-pickled"),+ pytest.param(_prev_type_id_names_main_by_script, True, id="prev-main"),+ pytest.param(_prev_type_id_on_base_reaches_subclass, True, id="prev-inherited"),+ pytest.param(_prev_type_id_for_registered_key_owner, True, id="prev-key-owner"),+ pytest.param(+ _none_declared_id_shadows_key_owner_id,+ True,+ id="none-declared-shadows-key-owner-id",+ ),+ pytest.param(_prev_type_id_for_registered_metaclass, True, id="prev-metaclass"),+ # Registered IDs+ pytest.param(_registered_id_without_key_fn, True, id="registered-id-only"),+ pytest.param(+ _registered_id_reaches_subclass(False), True, id="registered-inherited"+ ),+ pytest.param(+ _registered_id_reaches_subclass(True), True, id="registered-inherited-class"+ ),+ pytest.param(+ _subclass_registration_overrides_base_id, False, id="registered-overridden"+ ),+ pytest.param(+ _registered_key_owner_id_reaches_subclass, True, id="key-owner-id-inherited"+ ),+ pytest.param(+ _subclass_id_beats_registered_key_owner_id(True),+ True,+ id="key-owner-id-overridden-by-declared",+ ),+ pytest.param(+ _subclass_id_beats_registered_key_owner_id(False),+ True,+ id="key-owner-id-overridden-by-registered",+ ),+ pytest.param(+ _declared_id_beats_key_owner_registration,+ True,+ id="key-owner-declared-beats-registered",+ ),+ pytest.param(_own_memo_key_beats_registration, True, id="own-memo-key-wins"),+ # Class objects+ pytest.param(+ _class_object_ignores_own_memo_key, True, id="class-own-key-unused"+ ),+ pytest.param(+ _registered_id_applies_to_class_objects, True, id="class-registered-id"+ ),+ pytest.param(+ _class_object_key_registered_on(True), True, id="class-key-metaclass"+ ),+ pytest.param(_class_object_key_registered_on(False), True, id="class-key-type"),+ pytest.param(+ _class_object_ignores_own_id_under_key_owner(True),+ True,+ id="class-own-declared-id-differs",+ ),+ pytest.param(+ _class_object_ignores_own_id_under_key_owner(False),+ True,+ id="class-own-registered-id-differs",+ ),+ pytest.param(+ _class_object_distinct_from_its_instance,+ False,+ id="class-object-vs-instance",+ ),+ pytest.param(_class_objects_ignore_object_key_fn, False, id="class-object-key"),+ # Every registration replaces the type's whole configuration+ pytest.param(_reregistering_drops_state_fn, True, id="replace-state-fn"),+ pytest.param(+ _reregistering_drops_stable_id(register_memo_type), False, id="replace-id"+ ),+ pytest.param(+ _reregistering_drops_stable_id(register_memo_key_function),+ False,+ id="replace-id-via-key-function-shortcut",+ ),+ pytest.param(_reregistering_drops_key_fn, False, id="replace-key-fn"),+ pytest.param(+ _not_memo_keyable_drops_stable_id, False, id="replace-id-via-not-keyable"+ ),+ # Registry changes apply to types already fingerprinted+ pytest.param(+ _registration_after_first_fingerprint, True, id="register-after-use"+ ),+ pytest.param(+ _unregistration_after_first_fingerprint, False, id="unregister-after-use"+ ),+ # A memo key fragment shares the walk of the value holding it+ pytest.param(_memo_key_leads_back_to_parent(False), True, id="cycle-own-key"),+ pytest.param(_memo_key_leads_back_to_parent(True), True, id="cycle-registered"),+ ],+)+def test_type_identity(+ build: _Build, same: bool, monkeypatch: pytest.MonkeyPatch+) -> None:+ case = _Case(monkeypatch)+ try:+ a, b = build(case)+ assert (memo_fingerprint(a) == memo_fingerprint(b)) is same+ finally:+ for typ in case.registered:+ unregister_memo_type(typ)+++ ("typ", "args", "kwargs", "match"),+ [+ (object(), (), {"stable_type_id": "test.Entry/v1"}, "expects typ to be a type"),+ (_Unkeyed, (), {}, "requires a key_fn or stable_type_id"),+ (_Unkeyed, (object(),), {}, "key_fn must be callable"),+ (_Unkeyed, (_value_key,), {"state_fn": object()}, "state_fn must be callable"),+ (+ _Unkeyed,+ (),+ {"state_fn": _value_key},+ "state_fn requires a memo key function",+ ),+ (_Unkeyed, (), {"stable_type_id": 123}, "stable_type_id must be a str"),+ ],+)+def test_register_memo_type_rejects_invalid_calls(+ typ: Any, args: tuple[Any, ...], kwargs: dict[str, Any], match: str+) -> None:+ try:+ with pytest.raises(TypeError, match=match):+ cast(Any, register_memo_type)(typ, *args, **kwargs)+ finally:+ unregister_memo_type(typ)def test_cycles_are_supported_and_deterministic() -> None:@@ -632,7 +1240,7 @@ def test_state_methods_collected_from_registry() -> None:assert isinstance(methods[0], StateFnEntry)assert callable(methods[0].call)finally:- unregister_memo_key_function(Registered)+ unregister_memo_type(Registered)def test_multiple_state_methods_collected_in_order() -> None:@@ -962,6 +1570,20 @@ def test_memo_fingerprint_of_plain_data_is_stable() -> None:)+def test_memo_fingerprint_of_class_objects_is_stable() -> None:+ # Values measured on main, where a class object is keyed by a temporary+ # (module, qualname) tuple; the cycle after it checks back-reference ordinals.+ schema = type("Schema", (), {"__module__": "app.models"})+ cycle: list[object] = []+ cycle.append(cycle)+ assert memo_fingerprint(schema).as_bytes().hex() == (+ "f4682ab705e4b07c4906721398444971"+ )+ assert memo_fingerprint([schema, cycle]).as_bytes().hex() == (+ "a6716187b9dbbbcdb9a9db2a1b988de5"+ )++def test_memo_fingerprint_honors_registry_for_plain_container_types() -> None:register_memo_key_function(list, lambda obj: len(obj))try:@@ -969,5 +1591,5 @@ def test_memo_fingerprint_honors_registry_for_plain_container_types() -> None:assert fp == memo_fingerprint({"a": [3, 4]})assert fp == _canonical_form_fingerprint({"a": [1, 2]})finally:- unregister_memo_key_function(list)+ unregister_memo_type(list)assert memo_fingerprint({"a": [1, 2]}) != fpdiff --git a/rust/py/src/memo_fingerprint.rs b/rust/py/src/memo_fingerprint.rsindex 020ffaa0..a02cd2fa 100644--- a/rust/py/src/memo_fingerprint.rs+++ b/rust/py/src/memo_fingerprint.rs@@ -283,7 +283,7 @@ fn write_plain(/// Whether a memo key function is registered for a plain container type or a/// base of one, replacing the default canonical form the native walker-/// reproduces. Mirrors the Python registry (`_memo_fns` in+/// reproduces. Mirrors the Python registry (`_memo_type_registry` in/// `memo_fingerprint.py`), which updates it on every change.static PLAIN_CANONICAL_FORM_OVERRIDDEN: AtomicBool = AtomicBool::new(false);