From bc49613a9138252f4feae859d0a44423c3bfd887 Mon Sep 17 00:00:00 2001 From: Pascal Tomecek <40371786+ptomecek@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:46:43 -0500 Subject: [PATCH 1/3] [feature] Hash shared nested models once in cache keys and data tokens cache_key() tokenized model_dump(), which copies every shared nested model, so a config graph that references the same models many times produced a dump of several MB and took seconds to key. cache_key() now digests a model's dump with each field that holds only ccflow models replaced by those models' digests, computed once per key. This applies on pydantic>=2.13, where ccflow models serialize as their runtime type; other fields, and older pydantic versions, use the dump as before. compute_data_token() also hashes each nested model once per call, by digest. Every cache key and every data token of a model changes once. Signed-off-by: Pascal Tomecek <40371786+ptomecek@users.noreply.github.com> --- ccflow/evaluators/common.py | 9 +- ccflow/tests/utils/test_tokenize.py | 155 +++++++++++++++++++++++++++- ccflow/utils/tokenize.py | 126 +++++++++++++++++++--- 3 files changed, 273 insertions(+), 17 deletions(-) diff --git a/ccflow/evaluators/common.py b/ccflow/evaluators/common.py index 2e54f8e..f093183 100644 --- a/ccflow/evaluators/common.py +++ b/ccflow/evaluators/common.py @@ -18,7 +18,7 @@ WrapperModel, ) from ..utils.reporting import FormatConfig, LoggingPolicy -from ..utils.tokenize import compute_cache_token +from ..utils.tokenize import _model_dump_digest, compute_cache_token from .reporting import ReportingEvaluator, _descriptor __all__ = [ @@ -321,16 +321,17 @@ def cache_key(flow_obj: ModelEvaluationContext | ContextBase | CallableModel, *, if isinstance(flow_obj, ModelEvaluationContext): flow_obj, fn, non_transparent = _flatten_cache_key_context(flow_obj) + memo = {} return compute_cache_token( data_values=[ - {**flow_obj.model_dump(mode="python"), "fn": fn}, - *(evaluator.model_dump(mode="python") for evaluator in non_transparent), + (_model_dump_digest(flow_obj, memo, exclude=frozenset({"fn"})), fn), + *(_model_dump_digest(evaluator, memo) for evaluator in non_transparent), ], behavior_classes=[type(flow_obj.model), *(type(evaluator) for evaluator in non_transparent)], ).encode("utf-8") elif isinstance(flow_obj, (ContextBase, CallableModel)): return compute_cache_token( - data_values=[flow_obj.model_dump(mode="python")], + data_values=[_model_dump_digest(flow_obj, {})], behavior_classes=[type(flow_obj)], ).encode("utf-8") else: diff --git a/ccflow/tests/utils/test_tokenize.py b/ccflow/tests/utils/test_tokenize.py index bd52889..24beae0 100644 --- a/ccflow/tests/utils/test_tokenize.py +++ b/ccflow/tests/utils/test_tokenize.py @@ -14,8 +14,9 @@ import numpy as np import pandas as pd import pytest -from pydantic import BaseModel as _PlainPydantic +from pydantic import BaseModel as _PlainPydantic, Field +from ccflow.base import _USE_RUNTIME_POLYMORPHIC_SERIALIZATION, BaseModel as _CcflowModel from ccflow.callable import CallableModel, ContextBase, EvaluatorBase, ModelEvaluationContext from ccflow.context import NullContext from ccflow.evaluators.common import cache_key @@ -761,6 +762,158 @@ class PlainPydantic(_PlainPydantic): assert normalize_token(PlainPydantic(x=5)) != normalize_token(PlainPydantic(x=6)) +class TestNestedModelDigests: + """Nested models are tokenized by digest, once per computation however often they are referenced.""" + + class Leaf(_PlainPydantic): + x: int = 1 + + class Pair(_PlainPydantic): + a: "TestNestedModelDigests.Leaf" + b: "TestNestedModelDigests.Leaf" + + def test_a_shared_model_is_normalized_once_per_computation(self): + calls = [] + + class Counted: + pass + + @normalize_token.register(Counted) + def _count(obj): + calls.append(obj) + return "counted" + + class Holder(_PlainPydantic, arbitrary_types_allowed=True): + value: Counted + + class Shared(_PlainPydantic): + a: Holder + b: Holder + + holder = Holder(value=Counted()) + compute_data_token(Shared(a=holder, b=holder)) + assert len(calls) == 1, "the second reference reuses the first one's digest" + compute_data_token(Shared(a=holder, b=holder)) + assert len(calls) == 2, "digests are not kept between computations" + + def test_a_temporary_model_freed_mid_computation_does_not_lend_its_digest(self): + class Wrapped: + def __init__(self, x): + self.x = x + + # Each call builds a throwaway model that is freed on return, so the next one can reuse its id. + @normalize_token.register(Wrapped) + def _wrapped(obj): + return normalize_token(self.Leaf(x=obj.x)) + + assert compute_data_token([Wrapped(1), Wrapped(2)]) != compute_data_token([Wrapped(1), Wrapped(1)]) + + def test_a_nested_change_changes_the_token_and_equal_data_gives_equal_tokens(self): + assert compute_data_token(self.Pair(a=self.Leaf(x=1), b=self.Leaf(x=1))) == compute_data_token(self.Pair(a=self.Leaf(x=1), b=self.Leaf(x=1))) + assert compute_data_token(self.Pair(a=self.Leaf(x=1), b=self.Leaf(x=1))) != compute_data_token(self.Pair(a=self.Leaf(x=1), b=self.Leaf(x=2))) + + def test_models_in_a_cycle_tokenize_the_same_in_any_order(self): + class Node(_PlainPydantic): + child: object = None + + a, b = Node(), Node() + a.child, b.child = b, a + assert compute_data_token({"a": a, "b": b}) == compute_data_token({"b": b, "a": a}) + + +TestNestedModelDigests.Pair.model_rebuild() + + +class TestCacheKeyNestedModels: + """``cache_key()`` keys a model by its dump, digesting each nested ccflow model once.""" + + @pytest.mark.skipif(not _USE_RUNTIME_POLYMORPHIC_SERIALIZATION, reason="nested models are digested separately on pydantic>=2.13") + def test_a_shared_model_is_dumped_once(self): + from ccflow import Flow + + calls = [] + + class Counted: + pass + + @normalize_token.register(Counted) + def _count(obj): + calls.append(obj) + return "counted" + + class Holder(_CcflowModel, arbitrary_types_allowed=True): + value: Counted + + class Model(CallableModel): + a: Holder + b: Holder + + @Flow.call + def __call__(self, context: NullContext) -> GenericResult: + return GenericResult(value=0) + + holder = Holder(value=Counted()) + model = Model(a=holder, b=holder) + cache_key(model) + assert len(calls) == 1 + cache_key(ModelEvaluationContext(model=model, context=NullContext())) + assert len(calls) == 2 + + def test_shared_and_equal_separate_models_give_the_same_key(self): + class Leaf(_CcflowModel): + x: int = 1 + + class Parent(ContextBase): + a: Leaf + b: list[Leaf] + + leaf = Leaf() + assert cache_key(Parent(a=leaf, b=[leaf])) == cache_key(Parent(a=Leaf(), b=[Leaf()])) + assert cache_key(Parent(a=leaf, b=[leaf])) != cache_key(Parent(a=leaf, b=[Leaf(x=2)])) + + def test_registry_entries(self): + from ccflow import ModelRegistry + + class Leaf(_CcflowModel): + x: int + + class Parent(ContextBase): + registry: ModelRegistry + + first = Parent(registry=ModelRegistry(name="r", models={"e": Leaf(x=1)})) + second = Parent(registry=ModelRegistry(name="r", models={"e": Leaf(x=2)})) + assert cache_key(first) != cache_key(second) + + def test_the_resolved_fn_replaces_the_stored_one(self): + from ccflow import Flow + from ccflow.callable import TransparentModelEvaluationContext + from ccflow.evaluators import LoggingEvaluator + + class Model(CallableModel): + @Flow.call + def __call__(self, context: NullContext) -> GenericResult: + return GenericResult(value=0) + + model = Model() + inner = ModelEvaluationContext(model=model, context=NullContext(), fn="__call__") + wrapped = TransparentModelEvaluationContext(model=LoggingEvaluator(), context=inner, fn="__deps__") + assert cache_key(wrapped) == cache_key(ModelEvaluationContext(model=model, context=NullContext(), fn="__deps__")) + + def test_an_annotated_serializer_keeps_the_field_in_the_dump(self): + from typing import Annotated, List # noqa: UP035 + + from pydantic import PlainSerializer + + class Child(_CcflowModel): + secret: int = Field(exclude=True) + + class Parent(ContextBase): + # typing.List: before pydantic 2.13, ccflow wraps a builtin ``list[...]`` annotation in SerializeAsAny. + children: List[Annotated[Child, PlainSerializer(lambda child: child.secret)]] # noqa: UP006 + + assert cache_key(Parent(children=[Child(secret=1)])) != cache_key(Parent(children=[Child(secret=2)])) + + class TestNormalizeTokenNumpyPandas: def test_numpy_ndarray(self): arr = np.array([1, 2, 3], dtype=np.int64) diff --git a/ccflow/utils/tokenize.py b/ccflow/utils/tokenize.py index ca82f24..53a36ef 100644 --- a/ccflow/utils/tokenize.py +++ b/ccflow/utils/tokenize.py @@ -24,11 +24,13 @@ from decimal import Decimal from functools import partial, singledispatch from pathlib import PurePath -from types import CodeType, MappingProxyType, MethodType, MethodWrapperType, ModuleType -from typing import Any +from types import CodeType, MappingProxyType, MethodType, MethodWrapperType, ModuleType, UnionType +from typing import Annotated, Any, Union, get_args, get_origin from uuid import UUID -from pydantic import BaseModel as _PydanticBaseModel +from pydantic import BaseModel as _PydanticBaseModel, InstanceOf, SerializeAsAny + +from ..base import _USE_RUNTIME_POLYMORPHIC_SERIALIZATION, BaseModel as _CcflowBaseModel __all__ = ( "compute_behavior_token", @@ -52,6 +54,17 @@ def _sha256_hexdigest(*parts: bytes | str) -> str: # ContextVar (rather than threading.local) so the visited set auto-isolates across asyncio tasks. _visited: contextvars.ContextVar[set | None] = contextvars.ContextVar("_ccflow_normalize_visited", default=None) +# ``id(model) -> (model, token)`` for the pydantic models already normalized in the current top-level computation, so +# a model referenced many times (e.g. one registry node shared by several others) is hashed once. Each entry holds its +# model so the id cannot be reused by another object (e.g. a temporary model built by a handler) before the +# computation ends. ``compute_data_token()`` sets a fresh dict and resets it with its ContextVar token, so a nested +# call inside a handler gets its own memo and leaves the outer one intact. +_model_digests: contextvars.ContextVar[dict | None] = contextvars.ContextVar("_ccflow_model_digests", default=None) + +# Number of cycle markers returned so far. A model whose normalization returned one depends on where the traversal +# entered the cycle, so its digest is not memoized. +_cycle_markers: contextvars.ContextVar[int] = contextvars.ContextVar("_ccflow_cycle_markers", default=0) + # Tracks functions currently being hashed to detect circular closure references. _hashing_functions: contextvars.ContextVar[set | None] = contextvars.ContextVar("_ccflow_hashing_functions", default=None) @@ -64,6 +77,7 @@ def _with_cycle_check(obj: Any, build: Callable[[], Any]) -> Any: visited = set() token = _visited.set(visited) elif id(obj) in visited: + _cycle_markers.set(_cycle_markers.get() + 1) return ("__cycle__", type(obj).__name__) visited.add(id(obj)) try: @@ -331,7 +345,15 @@ def _normalize_type(obj): @normalize_token.register(_PydanticBaseModel) def _normalize_pydantic_basemodel(obj): - """Hash a pydantic model by its non-excluded fields (and any ``extra='allow'`` extras).""" + """Hash a pydantic model by its non-excluded fields (and any ``extra='allow'`` extras). + + Returns ``("pydantic", type_path, digest)``, where ``digest`` is the SHA-256 of the model's canonical form, so a + nested model adds a fixed-size entry to its parent's token. Within one ``tokenize()`` or ``compute_data_token()`` + call, each model object is normalized once. + """ + digests = _model_digests.get() + if digests is not None and id(obj) in digests: + return digests[id(obj)][1] def build(): type_path = f"{type(obj).__module__}.{type(obj).__qualname__}" @@ -343,7 +365,14 @@ def build(): extras_canonical = tuple(sorted(((k, normalize_token(v)) for k, v in extras.items()), key=repr)) return ("pydantic", type_path, fields, extras_canonical) - return _with_cycle_check(obj, build) + markers = _cycle_markers.get() + canonical = _with_cycle_check(obj, build) + if canonical[0] == "__cycle__": + return canonical + token = ("pydantic", canonical[1], _sha256_hexdigest(repr(canonical))) + if digests is not None and _cycle_markers.get() == markers: + digests[id(obj)] = (obj, token) + return token def _register_numpy() -> None: @@ -387,21 +416,17 @@ def _normalize_np_scalar(obj): def tokenize(*args: Any, **kwargs: Any) -> str: """Return a deterministic SHA-256 hex digest of the given args/kwargs (variadic to match ``dask.base.tokenize``).""" - payload = (args, kwargs) if kwargs else args - visited_token = _visited.set(set()) - try: - return _sha256_hexdigest(repr(normalize_token(payload))) - finally: - _visited.reset(visited_token) + return compute_data_token((args, kwargs) if kwargs else args) def compute_data_token(value: Any) -> str: """Compute a deterministic data token for a single value.""" - visited_token = _visited.set(set()) + visited_token, digests_token = _visited.set(set()), _model_digests.set({}) try: return _sha256_hexdigest(repr(normalize_token(value))) finally: _visited.reset(visited_token) + _model_digests.reset(digests_token) def compute_cache_token(*, data_values: Iterable[Any] = (), behavior_classes: Iterable[type] = ()) -> str: @@ -420,6 +445,83 @@ def compute_cache_token(*, data_values: Iterable[Any] = (), behavior_classes: It return compute_data_token(tuple(tokens)) +def _holds_only_ccflow_models(value: Any) -> bool: + """Return whether ``value`` is a ccflow model, or a list, tuple or str-keyed dict of such values and ``None`` that + holds at least one model.""" + if isinstance(value, _CcflowBaseModel): + return True + if type(value) is dict and all(type(key) is str for key in value): + value = list(value.values()) + elif type(value) not in (list, tuple): + return False + return any(item is not None for item in value) and all(item is None or _holds_only_ccflow_models(item) for item in value) + + +def _is_plain_annotation(annotation: Any) -> bool: + """Return whether ``annotation`` is built only from model classes, ``Any``, ``None``, ``str``, lists, tuples, dicts + and unions, with no ``Annotated`` metadata other than ``SerializeAsAny`` and ``InstanceOf`` (which only changes + validation).""" + if annotation in (Any, Ellipsis, type(None), str): + return True + origin, args = get_origin(annotation), get_args(annotation) + if origin is None: + return isinstance(annotation, type) and issubclass(annotation, _PydanticBaseModel) + if origin is Annotated: + return all(isinstance(m, (SerializeAsAny, InstanceOf)) for m in args[1:]) and _is_plain_annotation(args[0]) + return origin in (list, tuple, dict, Union, UnionType) and all(_is_plain_annotation(arg) for arg in args) + + +def _digest_tree(value: Any, memo: dict) -> Any: + if isinstance(value, _PydanticBaseModel): + return _model_dump_digest(value, memo) + if type(value) is dict: + return {key: _digest_tree(item, memo) for key, item in value.items()} + if type(value) in (list, tuple): + return type(value)(_digest_tree(item, memo) for item in value) + return value + + +def _model_dump_digest(model: _PydanticBaseModel, memo: dict, exclude: frozenset[str] = frozenset()) -> str: + """Return a digest of ``model.model_dump(mode="python")`` that dumps each nested ccflow model once. + + A field that holds only ccflow models, with a plain annotation and no serializer or exclusion of its own, is + left out of the dump and replaced by its models' digests. On pydantic>=2.13 a ccflow model serializes as its + runtime type, so its own dump is the one its parent would contain. Other fields are dumped as usual. + + ``memo`` maps ``id(model)`` to ``(model, digest)`` for one key; it holds each model so its id cannot be reused, + and maps a model still in progress to ``(model, None)``, so a cycle raises as ``model_dump()`` does. ``exclude`` + names top-level fields to leave out. + """ + entry = memo.get(id(model)) + if entry is not None: + if entry[1] is None: + raise ValueError(f"Circular reference detected for {type(model).__qualname__}") + return entry[1] + memo[id(model)] = (model, None) + cls = type(model) + split = set() + # Before pydantic 2.13 a field can serialize a ccflow model by its declared type, so it stays in the dump. + if _USE_RUNTIME_POLYMORPHIC_SERIALIZATION and isinstance(model, _CcflowBaseModel) and not cls.__pydantic_decorators__.model_serializers: + serialized = {name for d in cls.__pydantic_decorators__.field_serializers.values() for name in d.info.fields} + split = { + name + for name, info in cls.model_fields.items() + if name not in exclude + and name not in serialized + and "*" not in serialized + and not info.exclude + and getattr(info, "exclude_if", None) is None # pydantic>=2.11 + and all(isinstance(m, (SerializeAsAny, InstanceOf)) for m in info.metadata) + and _is_plain_annotation(info.annotation) + and _holds_only_ccflow_models(getattr(model, name, None)) + } + # The compiled serializer, as a parent's dump would use for this model, rather than any model_dump() override. + residual = cls.__pydantic_serializer__.to_python(model, mode="python", exclude=(split | exclude) or None) + digest = compute_data_token((residual, {name: _digest_tree(getattr(model, name), memo) for name in sorted(split)})) + memo[id(model)] = (model, digest) + return digest + + # Methods that are never behavior-relevant (pydantic/python internals) _SKIPPED_METHODS = frozenset( { From 9164c9240ff32a0f83604173442a01ce240b3cff Mon Sep 17 00:00:00 2001 From: Pascal Tomecek <40371786+ptomecek@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:41:28 -0500 Subject: [PATCH 2/3] [feature] Digest @Flow.model inputs separately and keep cache-key helpers in evaluators Split fields marked SkipValidation, and fields whose exclude_if is false for their current value, so shared dependencies of @Flow.model nodes are serialized once per key. Move the cache-key digest helpers next to cache_key(), test that fields with a field serializer or an Annotated serializer stay in the dump, and describe how cache keys use the compiled serializer. Signed-off-by: Pascal Tomecek <40371786+ptomecek@users.noreply.github.com> --- ccflow/evaluators/common.py | 77 +++++++++++++++-- ccflow/tests/utils/test_tokenize.py | 114 +++++++++++++++---------- ccflow/utils/tokenize.py | 104 ++-------------------- docs/wiki/reference/Built-in-Models.md | 2 +- 4 files changed, 149 insertions(+), 148 deletions(-) diff --git a/ccflow/evaluators/common.py b/ccflow/evaluators/common.py index f093183..9d15942 100644 --- a/ccflow/evaluators/common.py +++ b/ccflow/evaluators/common.py @@ -1,9 +1,9 @@ import logging from collections.abc import Callable from types import MappingProxyType -from typing import Any +from typing import Annotated, Any, get_args, get_origin -from pydantic import Field, PrivateAttr +from pydantic import BaseModel as PydanticBaseModel, Field, InstanceOf, PrivateAttr, SerializeAsAny, SkipValidation from typing_extensions import override from ..base import BaseModel, make_lazy_result @@ -18,7 +18,7 @@ WrapperModel, ) from ..utils.reporting import FormatConfig, LoggingPolicy -from ..utils.tokenize import _model_dump_digest, compute_cache_token +from ..utils.tokenize import compute_cache_token, compute_data_token from .reporting import ReportingEvaluator, _descriptor __all__ = [ @@ -294,6 +294,71 @@ def _effective_evaluation_key( ).encode("utf-8") +# Set on pydantic>=2.13, where a nested ccflow model serializes as its runtime type. +_POLYMORPHIC_SERIALIZATION = BaseModel.model_config.get("polymorphic_serialization", False) + +# ``InstanceOf`` and ``SkipValidation`` only affect validation. +_PLAIN_MARKERS = (SerializeAsAny, InstanceOf, SkipValidation) + + +def _has_serializer(annotation: Any, metadata: tuple = ()) -> bool: + """Return whether ``metadata``, or ``Annotated`` metadata at any depth of ``annotation``, is not a plain marker.""" + if get_origin(annotation) is Annotated: + annotation, *more = get_args(annotation) + metadata = (*metadata, *more) + return any(not isinstance(m, _PLAIN_MARKERS) for m in metadata) or any(_has_serializer(arg) for arg in get_args(annotation)) + + +def _digest_tree(value: Any, memo: dict) -> Any: + """Return ``value`` with each ccflow model replaced by its digest, or ``None`` unless it holds only ccflow models. + + ``value`` qualifies if it is a ccflow model, or nested lists, tuples and str-keyed dicts of them and ``None`` that + hold at least one model. + """ + if isinstance(value, BaseModel): + return _dump_digest(value, memo) + if type(value) is dict and all(type(key) is str for key in value): + items = list(value.values()) + elif type(value) in (list, tuple): + items = list(value) + else: + return None + digests = [None if item is None else _digest_tree(item, memo) for item in items] + if all(d is None for d in digests) or any(d is None and item is not None for d, item in zip(digests, items)): + return None + return dict(zip(value, digests)) if type(value) is dict else type(value)(digests) + + +def _dump_digest(model: PydanticBaseModel, memo: dict) -> str: + """Return a digest of ``model``'s python-mode dump in which each nested ccflow model is dumped once per ``memo``.""" + # memo: id(model) -> (model, digest). Holding the model keeps its id from being reused by another object. + entry = memo.get(id(model)) + if entry is not None: + return entry[1] + cls = type(model) + split = {} + # A field holding only nested ccflow models, with no serialization or exclusion of its own, dumps as those models' + # own dumps, so it can be replaced by their digests. + if _POLYMORPHIC_SERIALIZATION and isinstance(model, BaseModel) and not cls.__pydantic_decorators__.model_serializers: + serialized = {name for d in cls.__pydantic_decorators__.field_serializers.values() for name in d.info.fields} + for name, info in cls.model_fields.items(): + value = getattr(model, name, None) + exclude_if = getattr(info, "exclude_if", None) # pydantic>=2.11 + if ( + name not in serialized + and not info.exclude + and (exclude_if is None or not exclude_if(value)) + and not _has_serializer(info.annotation, tuple(info.metadata)) + and (tree := _digest_tree(value, memo)) is not None + ): + split[name] = tree + # The compiled serializer, as a parent's dump would use, rather than any model_dump() override. + residual = cls.__pydantic_serializer__.to_python(model, mode="python", exclude=set(split) or None) + digest = compute_data_token((residual, split)) + memo[id(model)] = (model, digest) + return digest + + def cache_key(flow_obj: ModelEvaluationContext | ContextBase | CallableModel, *, effective: bool = False) -> bytes: """Returns a key suitable for caching and dependency graph deduplication. @@ -324,14 +389,14 @@ def cache_key(flow_obj: ModelEvaluationContext | ContextBase | CallableModel, *, memo = {} return compute_cache_token( data_values=[ - (_model_dump_digest(flow_obj, memo, exclude=frozenset({"fn"})), fn), - *(_model_dump_digest(evaluator, memo) for evaluator in non_transparent), + _dump_digest(flow_obj.model_copy(update={"fn": fn}), memo), + *(_dump_digest(evaluator, memo) for evaluator in non_transparent), ], behavior_classes=[type(flow_obj.model), *(type(evaluator) for evaluator in non_transparent)], ).encode("utf-8") elif isinstance(flow_obj, (ContextBase, CallableModel)): return compute_cache_token( - data_values=[_model_dump_digest(flow_obj, {})], + data_values=[_dump_digest(flow_obj, {})], behavior_classes=[type(flow_obj)], ).encode("utf-8") else: diff --git a/ccflow/tests/utils/test_tokenize.py b/ccflow/tests/utils/test_tokenize.py index 24beae0..459872c 100644 --- a/ccflow/tests/utils/test_tokenize.py +++ b/ccflow/tests/utils/test_tokenize.py @@ -16,7 +16,7 @@ import pytest from pydantic import BaseModel as _PlainPydantic, Field -from ccflow.base import _USE_RUNTIME_POLYMORPHIC_SERIALIZATION, BaseModel as _CcflowModel +from ccflow.base import BaseModel as _CcflowModel from ccflow.callable import CallableModel, ContextBase, EvaluatorBase, ModelEvaluationContext from ccflow.context import NullContext from ccflow.evaluators.common import cache_key @@ -762,6 +762,23 @@ class PlainPydantic(_PlainPydantic): assert normalize_token(PlainPydantic(x=5)) != normalize_token(PlainPydantic(x=6)) +class _Counted: + """Counts how often ``normalize_token`` normalizes it.""" + + calls = 0 + + +@normalize_token.register(_Counted) +def _normalize_counted(obj): + obj.calls += 1 + return "counted" + + +_needs_polymorphic_serialization = pytest.mark.skipif( + not _CcflowModel.model_config.get("polymorphic_serialization"), reason="nested models are digested separately only on pydantic>=2.13" +) + + class TestNestedModelDigests: """Nested models are tokenized by digest, once per computation however often they are referenced.""" @@ -773,28 +790,18 @@ class Pair(_PlainPydantic): b: "TestNestedModelDigests.Leaf" def test_a_shared_model_is_normalized_once_per_computation(self): - calls = [] - - class Counted: - pass - - @normalize_token.register(Counted) - def _count(obj): - calls.append(obj) - return "counted" - class Holder(_PlainPydantic, arbitrary_types_allowed=True): - value: Counted + value: _Counted class Shared(_PlainPydantic): a: Holder b: Holder - holder = Holder(value=Counted()) + holder = Holder(value=_Counted()) compute_data_token(Shared(a=holder, b=holder)) - assert len(calls) == 1, "the second reference reuses the first one's digest" + assert holder.value.calls == 1, "the second reference reuses the first one's digest" compute_data_token(Shared(a=holder, b=holder)) - assert len(calls) == 2, "digests are not kept between computations" + assert holder.value.calls == 2, "digests are not kept between computations" def test_a_temporary_model_freed_mid_computation_does_not_lend_its_digest(self): class Wrapped: @@ -812,14 +819,6 @@ def test_a_nested_change_changes_the_token_and_equal_data_gives_equal_tokens(sel assert compute_data_token(self.Pair(a=self.Leaf(x=1), b=self.Leaf(x=1))) == compute_data_token(self.Pair(a=self.Leaf(x=1), b=self.Leaf(x=1))) assert compute_data_token(self.Pair(a=self.Leaf(x=1), b=self.Leaf(x=1))) != compute_data_token(self.Pair(a=self.Leaf(x=1), b=self.Leaf(x=2))) - def test_models_in_a_cycle_tokenize_the_same_in_any_order(self): - class Node(_PlainPydantic): - child: object = None - - a, b = Node(), Node() - a.child, b.child = b, a - assert compute_data_token({"a": a, "b": b}) == compute_data_token({"b": b, "a": a}) - TestNestedModelDigests.Pair.model_rebuild() @@ -827,22 +826,12 @@ class Node(_PlainPydantic): class TestCacheKeyNestedModels: """``cache_key()`` keys a model by its dump, digesting each nested ccflow model once.""" - @pytest.mark.skipif(not _USE_RUNTIME_POLYMORPHIC_SERIALIZATION, reason="nested models are digested separately on pydantic>=2.13") + @_needs_polymorphic_serialization def test_a_shared_model_is_dumped_once(self): from ccflow import Flow - calls = [] - - class Counted: - pass - - @normalize_token.register(Counted) - def _count(obj): - calls.append(obj) - return "counted" - class Holder(_CcflowModel, arbitrary_types_allowed=True): - value: Counted + value: _Counted class Model(CallableModel): a: Holder @@ -852,12 +841,31 @@ class Model(CallableModel): def __call__(self, context: NullContext) -> GenericResult: return GenericResult(value=0) - holder = Holder(value=Counted()) + holder = Holder(value=_Counted()) model = Model(a=holder, b=holder) cache_key(model) - assert len(calls) == 1 + assert holder.value.calls == 1 cache_key(ModelEvaluationContext(model=model, context=NullContext())) - assert len(calls) == 2 + assert holder.value.calls == 2 + + @_needs_polymorphic_serialization + def test_a_model_shared_by_flow_model_inputs_is_dumped_once(self): + from ccflow import Flow + + class Leaf(CallableModel, arbitrary_types_allowed=True): + value: _Counted + + @Flow.call + def __call__(self, context: NullContext) -> GenericResult: + return GenericResult(value=0) + + @Flow.model + def combine(a: GenericResult, b: GenericResult) -> GenericResult: + return GenericResult(value=a.value + b.value) + + leaf = Leaf(value=_Counted()) + cache_key(combine(a=leaf, b=leaf)) + assert leaf.value.calls == 1 def test_shared_and_equal_separate_models_give_the_same_key(self): class Leaf(_CcflowModel): @@ -871,7 +879,7 @@ class Parent(ContextBase): assert cache_key(Parent(a=leaf, b=[leaf])) == cache_key(Parent(a=Leaf(), b=[Leaf()])) assert cache_key(Parent(a=leaf, b=[leaf])) != cache_key(Parent(a=leaf, b=[Leaf(x=2)])) - def test_registry_entries(self): + def test_a_changed_registry_entry_changes_the_key(self): from ccflow import ModelRegistry class Leaf(_CcflowModel): @@ -899,19 +907,37 @@ def __call__(self, context: NullContext) -> GenericResult: wrapped = TransparentModelEvaluationContext(model=LoggingEvaluator(), context=inner, fn="__deps__") assert cache_key(wrapped) == cache_key(ModelEvaluationContext(model=model, context=NullContext(), fn="__deps__")) - def test_an_annotated_serializer_keeps_the_field_in_the_dump(self): + @pytest.mark.parametrize("shape", ["field_serializer", "annotated", "annotated_items"]) + def test_a_field_with_a_serializer_stays_in_the_dump(self, shape): from typing import Annotated, List # noqa: UP035 - from pydantic import PlainSerializer + from pydantic import PlainSerializer, field_serializer class Child(_CcflowModel): secret: int = Field(exclude=True) - class Parent(ContextBase): + by_secret = PlainSerializer(lambda child: child.secret) + + class ByFieldSerializer(ContextBase): + child: Child + + @field_serializer("child") + def _expose(self, child): + return child.secret + + class ByAnnotated(ContextBase): + child: Annotated[Child, by_secret] + + class ByAnnotatedItems(ContextBase): # typing.List: before pydantic 2.13, ccflow wraps a builtin ``list[...]`` annotation in SerializeAsAny. - children: List[Annotated[Child, PlainSerializer(lambda child: child.secret)]] # noqa: UP006 + child: List[Annotated[Child, by_secret]] # noqa: UP006 + + parent = {"field_serializer": ByFieldSerializer, "annotated": ByAnnotated, "annotated_items": ByAnnotatedItems}[shape] + + def make(secret): + return parent(child=[Child(secret=secret)] if shape == "annotated_items" else Child(secret=secret)) - assert cache_key(Parent(children=[Child(secret=1)])) != cache_key(Parent(children=[Child(secret=2)])) + assert cache_key(make(1)) != cache_key(make(2)) class TestNormalizeTokenNumpyPandas: diff --git a/ccflow/utils/tokenize.py b/ccflow/utils/tokenize.py index 53a36ef..9f7968c 100644 --- a/ccflow/utils/tokenize.py +++ b/ccflow/utils/tokenize.py @@ -24,13 +24,11 @@ from decimal import Decimal from functools import partial, singledispatch from pathlib import PurePath -from types import CodeType, MappingProxyType, MethodType, MethodWrapperType, ModuleType, UnionType -from typing import Annotated, Any, Union, get_args, get_origin +from types import CodeType, MappingProxyType, MethodType, MethodWrapperType, ModuleType +from typing import Any from uuid import UUID -from pydantic import BaseModel as _PydanticBaseModel, InstanceOf, SerializeAsAny - -from ..base import _USE_RUNTIME_POLYMORPHIC_SERIALIZATION, BaseModel as _CcflowBaseModel +from pydantic import BaseModel as _PydanticBaseModel __all__ = ( "compute_behavior_token", @@ -54,17 +52,10 @@ def _sha256_hexdigest(*parts: bytes | str) -> str: # ContextVar (rather than threading.local) so the visited set auto-isolates across asyncio tasks. _visited: contextvars.ContextVar[set | None] = contextvars.ContextVar("_ccflow_normalize_visited", default=None) -# ``id(model) -> (model, token)`` for the pydantic models already normalized in the current top-level computation, so -# a model referenced many times (e.g. one registry node shared by several others) is hashed once. Each entry holds its -# model so the id cannot be reused by another object (e.g. a temporary model built by a handler) before the -# computation ends. ``compute_data_token()`` sets a fresh dict and resets it with its ContextVar token, so a nested -# call inside a handler gets its own memo and leaves the outer one intact. +# ``id(model) -> (model, token)`` for the models normalized in the current ``compute_data_token()`` call. Holding the +# model keeps its id from being reused by another object before the call ends. _model_digests: contextvars.ContextVar[dict | None] = contextvars.ContextVar("_ccflow_model_digests", default=None) -# Number of cycle markers returned so far. A model whose normalization returned one depends on where the traversal -# entered the cycle, so its digest is not memoized. -_cycle_markers: contextvars.ContextVar[int] = contextvars.ContextVar("_ccflow_cycle_markers", default=0) - # Tracks functions currently being hashed to detect circular closure references. _hashing_functions: contextvars.ContextVar[set | None] = contextvars.ContextVar("_ccflow_hashing_functions", default=None) @@ -77,7 +68,6 @@ def _with_cycle_check(obj: Any, build: Callable[[], Any]) -> Any: visited = set() token = _visited.set(visited) elif id(obj) in visited: - _cycle_markers.set(_cycle_markers.get() + 1) return ("__cycle__", type(obj).__name__) visited.add(id(obj)) try: @@ -347,9 +337,7 @@ def _normalize_type(obj): def _normalize_pydantic_basemodel(obj): """Hash a pydantic model by its non-excluded fields (and any ``extra='allow'`` extras). - Returns ``("pydantic", type_path, digest)``, where ``digest`` is the SHA-256 of the model's canonical form, so a - nested model adds a fixed-size entry to its parent's token. Within one ``tokenize()`` or ``compute_data_token()`` - call, each model object is normalized once. + The model is represented by a digest of its canonical form, computed once per ``compute_data_token()`` call. """ digests = _model_digests.get() if digests is not None and id(obj) in digests: @@ -365,12 +353,11 @@ def build(): extras_canonical = tuple(sorted(((k, normalize_token(v)) for k, v in extras.items()), key=repr)) return ("pydantic", type_path, fields, extras_canonical) - markers = _cycle_markers.get() canonical = _with_cycle_check(obj, build) if canonical[0] == "__cycle__": return canonical token = ("pydantic", canonical[1], _sha256_hexdigest(repr(canonical))) - if digests is not None and _cycle_markers.get() == markers: + if digests is not None: digests[id(obj)] = (obj, token) return token @@ -445,83 +432,6 @@ def compute_cache_token(*, data_values: Iterable[Any] = (), behavior_classes: It return compute_data_token(tuple(tokens)) -def _holds_only_ccflow_models(value: Any) -> bool: - """Return whether ``value`` is a ccflow model, or a list, tuple or str-keyed dict of such values and ``None`` that - holds at least one model.""" - if isinstance(value, _CcflowBaseModel): - return True - if type(value) is dict and all(type(key) is str for key in value): - value = list(value.values()) - elif type(value) not in (list, tuple): - return False - return any(item is not None for item in value) and all(item is None or _holds_only_ccflow_models(item) for item in value) - - -def _is_plain_annotation(annotation: Any) -> bool: - """Return whether ``annotation`` is built only from model classes, ``Any``, ``None``, ``str``, lists, tuples, dicts - and unions, with no ``Annotated`` metadata other than ``SerializeAsAny`` and ``InstanceOf`` (which only changes - validation).""" - if annotation in (Any, Ellipsis, type(None), str): - return True - origin, args = get_origin(annotation), get_args(annotation) - if origin is None: - return isinstance(annotation, type) and issubclass(annotation, _PydanticBaseModel) - if origin is Annotated: - return all(isinstance(m, (SerializeAsAny, InstanceOf)) for m in args[1:]) and _is_plain_annotation(args[0]) - return origin in (list, tuple, dict, Union, UnionType) and all(_is_plain_annotation(arg) for arg in args) - - -def _digest_tree(value: Any, memo: dict) -> Any: - if isinstance(value, _PydanticBaseModel): - return _model_dump_digest(value, memo) - if type(value) is dict: - return {key: _digest_tree(item, memo) for key, item in value.items()} - if type(value) in (list, tuple): - return type(value)(_digest_tree(item, memo) for item in value) - return value - - -def _model_dump_digest(model: _PydanticBaseModel, memo: dict, exclude: frozenset[str] = frozenset()) -> str: - """Return a digest of ``model.model_dump(mode="python")`` that dumps each nested ccflow model once. - - A field that holds only ccflow models, with a plain annotation and no serializer or exclusion of its own, is - left out of the dump and replaced by its models' digests. On pydantic>=2.13 a ccflow model serializes as its - runtime type, so its own dump is the one its parent would contain. Other fields are dumped as usual. - - ``memo`` maps ``id(model)`` to ``(model, digest)`` for one key; it holds each model so its id cannot be reused, - and maps a model still in progress to ``(model, None)``, so a cycle raises as ``model_dump()`` does. ``exclude`` - names top-level fields to leave out. - """ - entry = memo.get(id(model)) - if entry is not None: - if entry[1] is None: - raise ValueError(f"Circular reference detected for {type(model).__qualname__}") - return entry[1] - memo[id(model)] = (model, None) - cls = type(model) - split = set() - # Before pydantic 2.13 a field can serialize a ccflow model by its declared type, so it stays in the dump. - if _USE_RUNTIME_POLYMORPHIC_SERIALIZATION and isinstance(model, _CcflowBaseModel) and not cls.__pydantic_decorators__.model_serializers: - serialized = {name for d in cls.__pydantic_decorators__.field_serializers.values() for name in d.info.fields} - split = { - name - for name, info in cls.model_fields.items() - if name not in exclude - and name not in serialized - and "*" not in serialized - and not info.exclude - and getattr(info, "exclude_if", None) is None # pydantic>=2.11 - and all(isinstance(m, (SerializeAsAny, InstanceOf)) for m in info.metadata) - and _is_plain_annotation(info.annotation) - and _holds_only_ccflow_models(getattr(model, name, None)) - } - # The compiled serializer, as a parent's dump would use for this model, rather than any model_dump() override. - residual = cls.__pydantic_serializer__.to_python(model, mode="python", exclude=(split | exclude) or None) - digest = compute_data_token((residual, {name: _digest_tree(getattr(model, name), memo) for name in sorted(split)})) - memo[id(model)] = (model, digest) - return digest - - # Methods that are never behavior-relevant (pydantic/python internals) _SKIPPED_METHODS = frozenset( { diff --git a/docs/wiki/reference/Built-in-Models.md b/docs/wiki/reference/Built-in-Models.md index 092b623..7693763 100644 --- a/docs/wiki/reference/Built-in-Models.md +++ b/docs/wiki/reference/Built-in-Models.md @@ -78,7 +78,7 @@ Evaluators control *how* a `CallableModel` runs. Set one through `FlowOptions` ( `MemoryCacheEvaluator` uses `ccflow.evaluators.cache_key()`, which delegates to `ccflow.utils.compute_cache_token()`. A key combines a **data token** (for the serialized model/context payload) and a **behavior token** (for each callable/evaluator class that can affect the result). -- For a direct `CallableModel` call, the key depends on `model.model_dump(mode="python")` and `compute_behavior_token(type(model))`. +- For a direct `CallableModel` call, the key depends on the model's python-mode serialization (from pydantic's compiled serializer, so a `model_dump()` override is not used) and `compute_behavior_token(type(model))`. On pydantic>=2.13, each nested ccflow model is serialized once per key and represented by its digest, however many fields refer to it. - For a `ModelEvaluationContext`, the structural key depends on the context payload plus the function name (`__call__` vs `__deps__`), the behavior token of the model class, and the data/behavior tokens of any **non-transparent** evaluators in the chain. Transparent evaluators (those whose `is_transparent` returns `True`) are skipped, so wrapping a model in logging or timing does not change its cache identity. From c63fa2ece983cf34e40056b794e7cb2e7a656be3 Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:32:39 -0500 Subject: [PATCH 3/3] Keep fields with hidden serializers in cache-key dumps A field was replaced by its nested models' digests unless a serializer was visible on its annotation. A field_serializer("*"), a TypeAliasType wrapping an Annotated serializer, or a TypedDict member serializer went undetected, so two models differing only in what that serializer exposed got the same cache key. Now a field is replaced only when its annotation is built from ccflow model classes, Any, None and builtin scalars inside lists, tuples, dicts and unions, and no field_serializer("*") is defined. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --- ccflow/evaluators/common.py | 32 +++++++++++++++++-------- ccflow/tests/utils/test_tokenize.py | 37 ++++++++++++++++++++++++++--- 2 files changed, 56 insertions(+), 13 deletions(-) diff --git a/ccflow/evaluators/common.py b/ccflow/evaluators/common.py index 9d15942..2e6844a 100644 --- a/ccflow/evaluators/common.py +++ b/ccflow/evaluators/common.py @@ -1,7 +1,7 @@ import logging from collections.abc import Callable -from types import MappingProxyType -from typing import Annotated, Any, get_args, get_origin +from types import MappingProxyType, UnionType +from typing import Annotated, Any, Union, get_args, get_origin from pydantic import BaseModel as PydanticBaseModel, Field, InstanceOf, PrivateAttr, SerializeAsAny, SkipValidation from typing_extensions import override @@ -301,12 +301,22 @@ def _effective_evaluation_key( _PLAIN_MARKERS = (SerializeAsAny, InstanceOf, SkipValidation) -def _has_serializer(annotation: Any, metadata: tuple = ()) -> bool: - """Return whether ``metadata``, or ``Annotated`` metadata at any depth of ``annotation``, is not a plain marker.""" - if get_origin(annotation) is Annotated: - annotation, *more = get_args(annotation) - metadata = (*metadata, *more) - return any(not isinstance(m, _PLAIN_MARKERS) for m in metadata) or any(_has_serializer(arg) for arg in get_args(annotation)) +def _is_plain(annotation: Any) -> bool: + """Return whether a field annotated ``annotation`` serializes a nested ccflow model as the model's own dump. + + Only ccflow model classes, ``Any``, ``None`` and builtin scalars qualify, combined by lists, tuples, dicts and unions, + with no ``Annotated`` metadata other than plain markers. Anything else, such as a type alias or a ``TypedDict``, may + carry a serializer, so it does not qualify. + """ + origin = get_origin(annotation) + if origin is Annotated: + inner, *metadata = get_args(annotation) + return all(isinstance(m, _PLAIN_MARKERS) for m in metadata) and _is_plain(inner) + if origin is not None: + return origin in (list, tuple, dict, Union, UnionType) and all(_is_plain(arg) for arg in get_args(annotation)) + if annotation in (Any, Ellipsis, type(None), str, int, float, bool): + return True + return isinstance(annotation, type) and issubclass(annotation, BaseModel) def _digest_tree(value: Any, memo: dict) -> Any: @@ -345,10 +355,12 @@ def _dump_digest(model: PydanticBaseModel, memo: dict) -> str: value = getattr(model, name, None) exclude_if = getattr(info, "exclude_if", None) # pydantic>=2.11 if ( - name not in serialized + "*" not in serialized + and name not in serialized and not info.exclude and (exclude_if is None or not exclude_if(value)) - and not _has_serializer(info.annotation, tuple(info.metadata)) + and all(isinstance(m, _PLAIN_MARKERS) for m in info.metadata) + and _is_plain(info.annotation) and (tree := _digest_tree(value, memo)) is not None ): split[name] = tree diff --git a/ccflow/tests/utils/test_tokenize.py b/ccflow/tests/utils/test_tokenize.py index 459872c..29b4969 100644 --- a/ccflow/tests/utils/test_tokenize.py +++ b/ccflow/tests/utils/test_tokenize.py @@ -907,16 +907,20 @@ def __call__(self, context: NullContext) -> GenericResult: wrapped = TransparentModelEvaluationContext(model=LoggingEvaluator(), context=inner, fn="__deps__") assert cache_key(wrapped) == cache_key(ModelEvaluationContext(model=model, context=NullContext(), fn="__deps__")) - @pytest.mark.parametrize("shape", ["field_serializer", "annotated", "annotated_items"]) + @pytest.mark.parametrize( + "shape", ["field_serializer", "wildcard_field_serializer", "annotated", "annotated_items", "type_alias", "type_alias_items", "typed_dict"] + ) def test_a_field_with_a_serializer_stays_in_the_dump(self, shape): from typing import Annotated, List # noqa: UP035 from pydantic import PlainSerializer, field_serializer + from typing_extensions import TypeAliasType, TypedDict class Child(_CcflowModel): secret: int = Field(exclude=True) by_secret = PlainSerializer(lambda child: child.secret) + ChildBySecret = TypeAliasType("ChildBySecret", Annotated[Child, by_secret]) class ByFieldSerializer(ContextBase): child: Child @@ -925,6 +929,13 @@ class ByFieldSerializer(ContextBase): def _expose(self, child): return child.secret + class ByWildcardFieldSerializer(ContextBase): + child: Child + + @field_serializer("*") + def _expose(self, value): + return value.secret if isinstance(value, Child) else value + class ByAnnotated(ContextBase): child: Annotated[Child, by_secret] @@ -932,10 +943,30 @@ class ByAnnotatedItems(ContextBase): # typing.List: before pydantic 2.13, ccflow wraps a builtin ``list[...]`` annotation in SerializeAsAny. child: List[Annotated[Child, by_secret]] # noqa: UP006 - parent = {"field_serializer": ByFieldSerializer, "annotated": ByAnnotated, "annotated_items": ByAnnotatedItems}[shape] + class ByTypeAlias(ContextBase): + child: ChildBySecret + + class ByTypeAliasItems(ContextBase): + child: List[ChildBySecret] # noqa: UP006 + + class Members(TypedDict): + child: Annotated[Child, by_secret] + + class ByTypedDict(ContextBase): + child: Members + + parent, wrap = { + "field_serializer": (ByFieldSerializer, lambda child: child), + "wildcard_field_serializer": (ByWildcardFieldSerializer, lambda child: child), + "annotated": (ByAnnotated, lambda child: child), + "annotated_items": (ByAnnotatedItems, lambda child: [child]), + "type_alias": (ByTypeAlias, lambda child: child), + "type_alias_items": (ByTypeAliasItems, lambda child: [child]), + "typed_dict": (ByTypedDict, lambda child: {"child": child}), + }[shape] def make(secret): - return parent(child=[Child(secret=secret)] if shape == "annotated_items" else Child(secret=secret)) + return parent(child=wrap(Child(secret=secret))) assert cache_key(make(1)) != cache_key(make(2))