Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 85 additions & 7 deletions ccflow/evaluators/common.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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__ = [
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand Down
212 changes: 211 additions & 1 deletion ccflow/tests/utils/test_tokenize.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading