diff --git a/ccflow/evaluators/common.py b/ccflow/evaluators/common.py index 2e54f8e..2e6844a 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 types import MappingProxyType, UnionType +from typing import Annotated, Any, Union, 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 compute_cache_token +from ..utils.tokenize import compute_cache_token, compute_data_token from .reporting import ReportingEvaluator, _descriptor __all__ = [ @@ -294,6 +294,83 @@ 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 _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: + """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 ( + "*" not in serialized + and name not in serialized + and not info.exclude + and (exclude_if is None or not exclude_if(value)) + 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 + # 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. @@ -321,16 +398,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), + _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=[flow_obj.model_dump(mode="python")], + 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 bd52889..29b4969 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 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,215 @@ 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.""" + + 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): + 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 holder.value.calls == 1, "the second reference reuses the first one's digest" + compute_data_token(Shared(a=holder, b=holder)) + 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: + 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))) + + +TestNestedModelDigests.Pair.model_rebuild() + + +class TestCacheKeyNestedModels: + """``cache_key()`` keys a model by its dump, digesting each nested ccflow model once.""" + + @_needs_polymorphic_serialization + def test_a_shared_model_is_dumped_once(self): + from ccflow import Flow + + 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 holder.value.calls == 1 + cache_key(ModelEvaluationContext(model=model, context=NullContext())) + 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): + 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_a_changed_registry_entry_changes_the_key(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__")) + + @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 + + @field_serializer("child") + 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] + + 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 + + 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=wrap(Child(secret=secret))) + + assert cache_key(make(1)) != cache_key(make(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..9f7968c 100644 --- a/ccflow/utils/tokenize.py +++ b/ccflow/utils/tokenize.py @@ -52,6 +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 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) + # Tracks functions currently being hashed to detect circular closure references. _hashing_functions: contextvars.ContextVar[set | None] = contextvars.ContextVar("_ccflow_hashing_functions", default=None) @@ -331,7 +335,13 @@ 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). + + 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: + return digests[id(obj)][1] def build(): type_path = f"{type(obj).__module__}.{type(obj).__qualname__}" @@ -343,7 +353,13 @@ 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) + 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: + digests[id(obj)] = (obj, token) + return token def _register_numpy() -> None: @@ -387,21 +403,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: 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.