Memoization keys & states
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.
CocoIndex detects logic, input, and context changes to decide whether it can reuse a memo. It fingerprints function arguments, deps values, and context values with detect_change=True through the same pipeline. Most types work automatically. You can customize fingerprinting and validation with:
- 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.
- Stable type IDs — how to keep a type’s memo namespace stable across refactors.
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=. - You control the type and every use should share the same key → define
__coco_memo_key__. - You don’t control the type and every use should share the same key → register a key function.
- A matching key still needs a freshness check, such as mtime or ETag → use a memo state.
- A class may move or be renamed while keeping the same memo namespace → use a stable type ID.
- A value must never participate in memoization → inherit from
NotMemoKeyable.
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()), beforeuse_context()reads them. depsvalues — once, when the@coco.fn(..., deps=...)or@coco.fn.as_async(..., deps=...)decorator is applied.coco.LogicDepvalues — once, when theLogicDepis 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.
How data fingerprinting works
For each data value, CocoIndex derives a canonical form with this precedence:
- If the object implements
__coco_memo_key__(), CocoIndex uses its return value. This applies to class instances, not class objects (type). - Otherwise, if a memo key function is registered for the object’s type, CocoIndex uses it.
- Otherwise, CocoIndex uses its built-in canonicalization.
The following types are handled automatically (no custom key needed):
- Primitives:
None,bool,int,float,str,bytes,bytearray,memoryview - 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 a stable type ID when configured, otherwise by module and qualified name - Other picklable objects: used as a fallback via
pickle
The canonical forms are combined into a deterministic fingerprint. If the fingerprint matches a cached entry, the cached result is reused — unless memo states indicate it’s stale (see Memo state validation below).
Customizing the memoization key
Define __coco_memo_key__ (when you control the type)
Implement a method on your class that returns a stable, deterministic value:
class MyType:
def __coco_memo_key__(self) -> object:
# Return small primitives / tuples.
return (...)Return something that uniquely identifies the semantic content your function depends on:
- Good: small tuples of primitives, e.g.
(stable_id, version) - Bad: memory addresses, unstable UUIDs, open file handles,
datetime.now(), or large raw payloads
Example — DB row:
class UserRow:
def __init__(self, user_id: int, updated_at: int) -> None:
self.user_id = user_id
self.updated_at = updated_at
def __coco_memo_key__(self) -> object:
return ("users", self.user_id, self.updated_at)The method is used whenever a UserRow is fingerprinted as a function argument, deps value, or change-detected context value. For example:
import cocoindex as coco
@coco.fn(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 key function:
from pathlib import Path
from cocoindex import register_memo_type
def path_key(p: Path) -> object:
p = p.resolve()
st = p.stat()
return (str(p), st.st_mtime_ns, st.st_size)
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):
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: intDeclare 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():
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:
- Declared stable type ID (
__coco_memo_type_id__, own or inherited). - Registered stable type ID (most specific registration across the type’s MRO via
register_memo_type()). - Automatic fallback (the canonical
module.QualNameof the type or, for a value handled by a registered key function, of the type the function is registered on).
- Declared stable type ID (
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.
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.
Override at the call site with memo_key=
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).
@coco.fn(
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}"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 memo key function, or default canonicalization).
It works for every parameter kind:
- Positional / keyword parameters — referenced by name.
self— methods can passmemo_key={"self": lambda self: self.prefix}to memoize on selected instance state instead of the whole instance. Changes to other attributes on the same instance won’t invalidate the memo.*args— name the varargs parameter; the callable receives the full tuple and must return a tuple.Noneexcludes all variadic positional arguments.**kwargs— name the varkw parameter; the callable receives a dict and must return a dict.Noneexcludes all variadic keyword arguments.
memo_key is validated at decoration time: unknown parameter names raise ValueError, and values that are neither callable nor None raise TypeError.
Memo state validation
Sometimes fingerprint matching alone isn’t enough to decide whether a cached result is valid. For example:
- Multi-level validation: for files, check the modified time first (cheap), and only read the file for a content fingerprint when the time doesn’t match.
- 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-Sinceon the next run.
Memo state validation addresses these by letting you attach a state function to your objects. 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.
How it works
CocoIndex calls each state function with the state from the previous invocation:
- Initial state capture:
prev_stateiscoco.NON_EXISTENCE. Usecoco.is_non_existence(prev_state)to detect this. - Validation after a later fingerprint match:
prev_stateis whatever the state function returned previously.
Your state function returns a coco.MemoStateOutcome(state=..., memo_valid=...):
state— the current state value. CocoIndex stores it for the next run.memo_valid(bool, defaults toFalse) — whether the cached result is still valid.
This decouples “has the state changed?” from “can we reuse the memo?”:
MemoStateOutcome(state=new_state)→ cache is invalid (default). Function re-executes, new state is stored. On the first run (no previous cache), simply return the initial state without settingmemo_valid.MemoStateOutcome(state=same_state, memo_valid=True)→ nothing changed, cached result reused, no state update needed.MemoStateOutcome(state=new_state, memo_valid=True)→ state changed but cached result is still valid (e.g. mtime changed but content hash unchanged). The new state is persisted so the next run uses the updated state.
Define __coco_memo_state__ (when you control the type)
Annotate the prev_state parameter with its expected type (matching what you return in MemoStateOutcome(state=...)) so CocoIndex can properly reconstruct stored state values. See Serialization for details on supported types.
Add a __coco_memo_state__ method alongside __coco_memo_key__.
import os
import hashlib
from pathlib import Path
import cocoindex as coco
class LocalFile:
def __init__(self, path: Path) -> None:
self.path = path
def __coco_memo_key__(self) -> object:
# 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:
st = os.stat(self.path)
new_mtime = st.st_mtime_ns
if coco.is_non_existence(prev_state):
# First run — compute initial state (memo_valid defaults to False,
# which is fine since there's no previous cache to reuse)
content_hash = hashlib.sha256(self.path.read_bytes()).hexdigest()
return coco.MemoStateOutcome(state=(new_mtime, content_hash))
prev_mtime, prev_hash = prev_state
if new_mtime == prev_mtime:
# mtime unchanged — definitely reusable, no content read needed
return coco.MemoStateOutcome(state=prev_state, memo_valid=True)
# mtime changed — read content and check hash
content_hash = hashlib.sha256(self.path.read_bytes()).hexdigest()
return coco.MemoStateOutcome(
state=(new_mtime, content_hash), memo_valid=content_hash == prev_hash
)Without state validation, you’d include mtime and size directly in the memo key:
def __coco_memo_key__(self):
st = os.stat(self.path)
return (str(self.path.resolve()), st.st_mtime_ns, st.st_size)This works for simple cases. State validation becomes useful when you need multi-level checks (e.g. check mtime first, then content hash only if it differs), async operations, or stored metadata like ETags. With the MemoStateOutcome return, you can update the state (e.g. new mtime) without invalidating the cache when the content hasn’t actually changed.
Register a state function (when you don’t control the 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:
from pathlib import Path
import cocoindex as coco
def path_key(p: Path) -> object:
return str(p.resolve())
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_state
return coco.MemoStateOutcome(state=new_state, memo_valid=memo_valid)
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.
State that depends on what the function did
By default the state stored after a re-run is the one the state function returned when it rejected the cached result, before the function ran. That fits a state read from the outside, such as a file’s modification time.
Some states are only known once the function has run, for example the set of things it read. Return recollect_after_run=True and CocoIndex calls the state function a second time after the function body, with NON_EXISTENCE as on a first run, and stores that state:
class Tracked:
def __init__(self, key: str) -> None:
self.key = key
self.observed: list[tuple[str, int]] = [] # filled by the function
def __coco_memo_key__(self) -> object:
return self.key
def __coco_memo_state__(
self, prev_state: list[tuple[str, int]] | coco.NonExistenceType
) -> coco.MemoStateOutcome:
if coco.is_non_existence(prev_state):
# After the function ran: report what it read.
return coco.MemoStateOutcome(state=list(self.observed))
valid = all(current_version(name) == version for name, version in prev_state)
return coco.MemoStateOutcome(
state=prev_state, memo_valid=valid, recollect_after_run=True
)The flag is only read when the cached result is not reused. It applies to memoized functions; a memoized component that returns it raises an error.
When the state is the set of things the function read that are not among its arguments, record each read with coco.use_data_dep (experimental) instead: it works for components too, and validates each read on its own.
Async state methods
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(). Ifbuilder.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.
import cocoindex as coco
class S3Object:
def __init__(self, bucket: str, key: str) -> None:
self.bucket = bucket
self.key = key
def __coco_memo_key__(self) -> object:
return (self.bucket, self.key)
async def __coco_memo_state__(self, prev_state: str | coco.NonExistenceType) -> coco.MemoStateOutcome:
etag = await self._head_object()
memo_valid = not coco.is_non_existence(prev_state) and etag == prev_state
return coco.MemoStateOutcome(state=etag, memo_valid=memo_valid)
async def _head_object(self) -> str:
... # boto3 / aioboto3 HEAD callPreventing memoization
Some types maintain internal state that makes memoization semantically incorrect. For example, a generator that tracks call counts would produce wrong results if memoized.
Inherit from NotMemoKeyable (when you control the type)
import cocoindex as coco
class MyStatefulGenerator(coco.NotMemoKeyable):
def __init__(self) -> None:
self._counter = 0
def next_value(self) -> int:
self._counter += 1
return self._counterRegister as not memo-keyable (when you don’t control the type)
import cocoindex as coco
from some_library import StatefulGenerator
coco.register_not_memo_keyable(StatefulGenerator)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
id(obj), pointer addresses, or random values. - 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
MemoStateOutcome(state=new_state, memo_valid=True)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. - Mark stateful types as
NotMemoKeyable: prevent subtle bugs from incorrect memoization of types with side effects.
- 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.