Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
"""Tests for logic change detection: memoized results are invalidated when function code changes."""
import copy
import gc
import pathlib
import sys
from types import ModuleType
from collections.abc import Iterator
from typing import Any
import pytest
import cocoindex as coco
from cocoindex._internal import core
from cocoindex._internal.function import AsyncFunction, SyncFunction
from tests import common
from tests.common.environment import get_env_db_path
from tests.common.target_states import GlobalDictTarget, Metrics
from tests.common.module_utils import load_module_as, unload_module_functions
coco_env = common.create_test_env(__file__)
_TEST_DIR = pathlib.Path(__file__).parent
_V1_PATH = str(_TEST_DIR / "mod_logic_v1.py")
_V2_PATH = str(_TEST_DIR / "mod_logic_v2.py")
_VER1_PATH = str(_TEST_DIR / "mod_logic_ver1.py")
_VER2_PATH = str(_TEST_DIR / "mod_logic_ver2.py")
_DEPS_V1_PATH = str(_TEST_DIR / "mod_logic_deps_v1.py")
_DEPS_V2_PATH = str(_TEST_DIR / "mod_logic_deps_v2.py")
_DEPS_CHAIN_V1_PATH = str(_TEST_DIR / "mod_logic_deps_chain_v1.py")
_DEPS_CHAIN_V2_PATH = str(_TEST_DIR / "mod_logic_deps_chain_v2.py")
_SELF_V1_PATH = str(_TEST_DIR / "mod_logic_self_v1.py")
_SELF_V2_PATH = str(_TEST_DIR / "mod_logic_self_v2.py")
_SELF_V3_PATH = str(_TEST_DIR / "mod_logic_self_v3.py")
_NONE_V1_PATH = str(_TEST_DIR / "mod_logic_none_v1.py")
_NONE_V2_PATH = str(_TEST_DIR / "mod_logic_none_v2.py")
_CHAIN_V1_PATH = str(_TEST_DIR / "mod_logic_chain_v1.py")
_CHAIN_V2_PATH = str(_TEST_DIR / "mod_logic_chain_v2.py")
_CHAIN_V3_PATH = str(_TEST_DIR / "mod_logic_chain_v3.py")
_METHOD_V1_PATH = str(_TEST_DIR / "mod_logic_method_v1.py")
_METHOD_V2_PATH = str(_TEST_DIR / "mod_logic_method_v2.py")
_FAKE_MODULE = "tests.core._dynamic_logic_change_module"
def _load_module(
module_path: str,
metrics: Metrics,
current_module: list[Any],
old_module: ModuleType | None = None,
) -> ModuleType:
"""Load a module version, unregistering the old module's fingerprints first."""
if old_module is not None:
unload_module_functions(old_module)
current_module.clear()
mod = load_module_as(module_path, _FAKE_MODULE)
mod.set_metrics(metrics)
current_module.append(mod)
return mod
@pytest.fixture(autouse=True)
def _cleanup_dynamic_module() -> Iterator[None]:
"""Ensure the fake module and its logic fingerprints are cleaned up after each test."""
gc.collect() # Collect stale SyncFunction objects from prior tests so their __del__ runs now.
yield
mod = sys.modules.get(_FAKE_MODULE)
if mod is not None:
unload_module_functions(mod)
del sys.modules[_FAKE_MODULE]
# ============================================================================
# Memoized function cache invalidated on logic change
# ============================================================================
def test_fn_memo_invalidated_on_logic_change() -> None:
"""A memoized function's cached result is invalidated when its code changes."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.transform_memo("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_fn_memo_invalidated_on_logic_change", environment=coco_env
),
app_main,
)
# v1: first run β function executes
mod = _load_module(_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"transform_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "v1: value1"
# v1: second run β memo hit
app.update_blocking()
assert metrics.collect() == {}
# v2: logic changed β memo invalidated, function re-executes
mod = _load_module(_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"transform_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "v2: value1"
# v2: second run β memo hit again
app.update_blocking()
assert metrics.collect() == {}
# ============================================================================
# Component memo invalidated on logic change
# ============================================================================
def test_component_memo_invalidated_on_logic_change() -> None:
"""A memoized component's memo is invalidated when its code changes."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
async def app_main() -> None:
mod = current_module[0]
await coco.mount(
coco.component_subpath("A"), mod.declare_entry_memo, "A", "value1"
)
app = coco.App(
coco.AppConfig(
name="test_component_memo_invalidated_on_logic_change", environment=coco_env
),
app_main,
)
# v1: first run β component executes
mod = _load_module(_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"declare_entry_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "v1: value1"
# v1: second run β component memo hit
app.update_blocking()
assert metrics.collect() == {}
# v2: logic changed β component memo invalidated
mod = _load_module(_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"declare_entry_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "v2: value1"
# v2: second run β component memo hit again
app.update_blocking()
assert metrics.collect() == {}
# ============================================================================
# Redefining a function with identical code keeps its memo β e.g. a notebook
# cell or `importlib.reload` re-running a `@coco.fn` definition. The new object
# registers the same logic fingerprint before the old object is dropped, so
# dropping the old one must not unregister it from under the new one.
# ============================================================================
def _define_sync_memo_fn(metrics: Metrics) -> SyncFunction[[str], None]:
@coco.fn(memo=True)
def sync_memo_fn(key: str) -> None:
metrics.increment(f"sync_memo_fn({key})")
return sync_memo_fn
def _define_async_memo_fn(metrics: Metrics) -> AsyncFunction[[str], None]:
@coco.fn(memo=True)
async def async_memo_fn(key: str) -> None:
metrics.increment(f"async_memo_fn({key})")
return async_memo_fn
def test_memo_hit_survives_redefining_fn_with_identical_code() -> None:
"""Rebinding a memoized function's name to an identical redefinition keeps
both its function memo and its component memo."""
metrics = Metrics()
sync_memo_fn = _define_sync_memo_fn(metrics)
async_memo_fn = _define_async_memo_fn(metrics)
@coco.fn
async def app_main() -> None:
sync_memo_fn("call")
await async_memo_fn("call")
await coco.use_mount(coco.component_subpath("sync"), sync_memo_fn, "mount")
await coco.use_mount(coco.component_subpath("async"), async_memo_fn, "mount")
app = coco.App(
coco.AppConfig(
name="test_memo_hit_survives_redefining_fn_with_identical_code",
environment=coco_env,
),
app_main,
)
app.update_blocking()
assert metrics.collect() == {
"sync_memo_fn(call)": 1,
"async_memo_fn(call)": 1,
"sync_memo_fn(mount)": 1,
"async_memo_fn(mount)": 1,
}
app.update_blocking()
assert metrics.collect() == {}
# Each call below registers the new object's fingerprint before the
# rebinding drops the old object; collect so the old object's finalizer
# has run before the next update.
sync_memo_fn = _define_sync_memo_fn(metrics)
async_memo_fn = _define_async_memo_fn(metrics)
gc.collect()
app.update_blocking()
assert metrics.collect() == {}
# ============================================================================
# Copying a function keeps its memo: dropping a copy must not release the logic
# fingerprint registration held by the original.
# ============================================================================
def test_memo_hit_survives_dropping_copies_of_fn() -> None:
"""Dropping a `copy.copy` or `copy.deepcopy` of a memoized function keeps
both its function memo and its component memo."""
metrics = Metrics()
sync_memo_fn = _define_sync_memo_fn(metrics)
async_memo_fn = _define_async_memo_fn(metrics)
@coco.fn
async def app_main() -> None:
sync_memo_fn("call")
await async_memo_fn("call")
await coco.use_mount(coco.component_subpath("sync"), sync_memo_fn, "mount")
await coco.use_mount(coco.component_subpath("async"), async_memo_fn, "mount")
app = coco.App(
coco.AppConfig(
name="test_memo_hit_survives_dropping_copies_of_fn",
environment=coco_env,
),
app_main,
)
app.update_blocking()
assert metrics.collect() == {
"sync_memo_fn(call)": 1,
"async_memo_fn(call)": 1,
"sync_memo_fn(mount)": 1,
"async_memo_fn(mount)": 1,
}
app.update_blocking()
assert metrics.collect() == {}
copies = [
copy.copy(sync_memo_fn),
copy.deepcopy(sync_memo_fn),
copy.copy(async_memo_fn),
copy.deepcopy(async_memo_fn),
]
del copies
gc.collect()
app.update_blocking()
assert metrics.collect() == {}
# ============================================================================
# Transitive β foo (memoized fn) calls bar, bar changes
# ============================================================================
def test_transitive_fn_memo_bar_memo_changes() -> None:
"""foo (memo) calls bar (memo). bar's code changes β foo's memo invalidated."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.foo_calls_bar_memo("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_transitive_fn_memo_bar_memo_changes", environment=coco_env
),
app_main,
)
# v1: first run β both foo and bar execute
mod = _load_module(_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"foo_calls_bar_memo": 1, "bar_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
# v1: second run β foo memo hit (bar not called either)
app.update_blocking()
assert metrics.collect() == {}
# v2: bar's logic changed β foo's memo invalidated transitively
mod = _load_module(_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"foo_calls_bar_memo": 1, "bar_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v2: value1"
# v2: second run β memo hit again
app.update_blocking()
assert metrics.collect() == {}
def test_transitive_fn_memo_bar_plain_changes() -> None:
"""foo (memo) calls bar (non-memo). bar's code changes β foo's memo invalidated."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.foo_calls_bar_plain("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_transitive_fn_memo_bar_plain_changes", environment=coco_env
),
app_main,
)
# v1: first run β both foo and bar execute
mod = _load_module(_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"foo_calls_bar_plain": 1, "bar_plain": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
# v1: second run β foo memo hit (bar not called since foo is cached)
app.update_blocking()
assert metrics.collect() == {}
# v2: bar's logic changed β foo's memo invalidated transitively
mod = _load_module(_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"foo_calls_bar_plain": 1, "bar_plain": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v2: value1"
# v2: second run β memo hit again
app.update_blocking()
assert metrics.collect() == {}
# ============================================================================
# Transitive β foo (component) calls/mounts bar, bar changes
# ============================================================================
def test_transitive_component_calls_bar_memo() -> None:
"""foo (component) calls bar (memo fn). bar changes β bar's fn memo invalidated."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
async def app_main() -> None:
mod = current_module[0]
await coco.mount(
coco.component_subpath("A"), mod.foo_comp_calls_bar_memo, "A", "value1"
)
app = coco.App(
coco.AppConfig(
name="test_transitive_component_calls_bar_memo", environment=coco_env
),
app_main,
)
# v1: first run β foo runs, bar_memo executes
mod = _load_module(_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"foo_comp_calls_bar_memo": 1, "bar_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
# v1: second run β foo re-runs (non-memo component), bar_memo cached
app.update_blocking()
assert metrics.collect() == {"foo_comp_calls_bar_memo": 1}
# v2: bar's logic changed β bar's fn memo invalidated
mod = _load_module(_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"foo_comp_calls_bar_memo": 1, "bar_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v2: value1"
# v2: second run β bar_memo cached again
app.update_blocking()
assert metrics.collect() == {"foo_comp_calls_bar_memo": 1}
def test_transitive_component_mounts_bar_comp_plain() -> None:
"""foo (component) mounts bar (non-memo component). bar changes β bar re-runs with new code."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
async def app_main() -> None:
mod = current_module[0]
await coco.mount(
coco.component_subpath("A"),
mod.foo_comp_mounts_bar_comp_plain,
"A",
"value1",
)
app = coco.App(
coco.AppConfig(
name="test_transitive_component_mounts_bar_comp_plain", environment=coco_env
),
app_main,
)
# v1: first run β foo and bar both execute
mod = _load_module(_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {
"foo_comp_mounts_bar_comp_plain": 1,
"bar_comp_plain": 1,
}
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
# v1: second run β both non-memo, both re-run
app.update_blocking()
assert metrics.collect() == {
"foo_comp_mounts_bar_comp_plain": 1,
"bar_comp_plain": 1,
}
# v2: bar's code changed β bar produces new output
mod = _load_module(_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {
"foo_comp_mounts_bar_comp_plain": 1,
"bar_comp_plain": 1,
}
assert GlobalDictTarget.store.data["A"].data == "bar_v2: value1"
def test_transitive_component_mounts_bar_comp_memo() -> None:
"""foo (component) mounts bar (memo component). bar changes β bar's component memo invalidated."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
async def app_main() -> None:
mod = current_module[0]
await coco.mount(
coco.component_subpath("A"),
mod.foo_comp_mounts_bar_comp_memo,
"A",
"value1",
)
app = coco.App(
coco.AppConfig(
name="test_transitive_component_mounts_bar_comp_memo", environment=coco_env
),
app_main,
)
# v1: first run β foo runs, bar_comp_memo executes
mod = _load_module(_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {
"foo_comp_mounts_bar_comp_memo": 1,
"bar_comp_memo": 1,
}
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
# v1: second run β foo re-runs (non-memo), bar_comp_memo cached (memo component)
app.update_blocking()
assert metrics.collect() == {"foo_comp_mounts_bar_comp_memo": 1}
# v2: bar's code changed β bar's component memo invalidated
mod = _load_module(_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {
"foo_comp_mounts_bar_comp_memo": 1,
"bar_comp_memo": 1,
}
assert GlobalDictTarget.store.data["A"].data == "bar_v2: value1"
# v2: second run β bar_comp_memo cached again
app.update_blocking()
assert metrics.collect() == {"foo_comp_mounts_bar_comp_memo": 1}
# ============================================================================
# Memoized parent across the mount boundary β child's change must invalidate
# the parent (its persisted logic_deps must include the mounted subtree).
#
# The memoized parent is defined here at module level (never reloaded), so its
# own logic fingerprint stays stably registered across the v1->v2 transition.
# This isolates the case "only the mounted child's code changed" β unlike the
# tests above where the parent is a plain (non-memoized) component that always
# re-runs and relies on the *child's* own memo to catch the change.
# ============================================================================
_mount_parent_metrics: list[Any] = []
_mount_parent_child: list[Any] = []
@coco.fn(memo=True)
async def _memo_parent_mounts_child(key: str, value: str) -> None:
_mount_parent_metrics[0].increment("memo_parent")
await coco.mount(coco.component_subpath(key), _mount_parent_child[0], key, value)
def test_memo_parent_invalidated_when_mounted_child_changes() -> None:
"""A memoized parent that mounts a child must invalidate when only the
child's code changes β regression for the dropped mount-boundary deps."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
_mount_parent_metrics.clear()
_mount_parent_metrics.append(metrics)
@coco.fn
async def app_main() -> None:
await coco.mount(
coco.component_subpath("A"), _memo_parent_mounts_child, "A", "value1"
)
app = coco.App(
coco.AppConfig(
name="test_memo_parent_invalidated_when_mounted_child_changes",
environment=coco_env,
),
app_main,
)
# v1: first run β memoized parent and child both execute
mod = _load_module(_V1_PATH, metrics, current_module)
_mount_parent_child.clear()
_mount_parent_child.append(mod.bar_comp_plain)
app.update_blocking()
assert metrics.collect() == {"memo_parent": 1, "bar_comp_plain": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
# v1: second run β parent memo hit, nothing runs
app.update_blocking()
assert metrics.collect() == {}
# v2: ONLY the mounted child's body changed. The memoized parent's stored
# logic_deps must include the child's fingerprint, so the parent invalidates,
# re-runs, and re-mounts the child β refreshing the output.
mod = _load_module(_V2_PATH, metrics, current_module, old_module=mod)
_mount_parent_child.clear()
_mount_parent_child.append(mod.bar_comp_plain)
app.update_blocking()
assert metrics.collect() == {"memo_parent": 1, "bar_comp_plain": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v2: value1"
# v2: second run β parent memo hit again
app.update_blocking()
assert metrics.collect() == {}
# ============================================================================
# Cache-hit propagation across the mount boundary β a memoized child that is a
# cache *hit* (while its parent rebuilds for an unrelated reason) must still
# report its dependency set to the rebuilt parent. Otherwise the parent's
# refreshed memo loses the child's subtree, and a later change to the child
# would wrongly leave the parent a memo hit.
# ============================================================================
_cachehit_metrics: list[Any] = []
_cachehit_child: list[Any] = []
_cachehit_value: list[str] = []
@coco.fn(memo=True)
async def _memo_parent_mounts_memo_child(key: str, value: str) -> None:
# `value` is part of this memo'd parent's key, so changing it forces a
# rebuild β but the child below is always mounted with FIXED args, so it
# stays a cache hit across that rebuild.
_cachehit_metrics[0].increment("cachehit_parent")
await coco.mount(coco.component_subpath("C"), _cachehit_child[0], "C", "fixed")
def test_memo_child_cache_hit_still_propagates_deps_to_rebuilt_parent() -> None:
"""When a memoized parent rebuilds (unrelated reason) and its memo child is
a cache hit, the child's deps must still flow into the parent's refreshed
memo β so a later change to the child invalidates the parent."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
_cachehit_metrics.clear()
_cachehit_metrics.append(metrics)
_cachehit_value.clear()
_cachehit_value.append("x1")
@coco.fn
async def app_main() -> None:
await coco.mount(
coco.component_subpath("P"),
_memo_parent_mounts_memo_child,
"P",
_cachehit_value[0],
)
app = coco.App(
coco.AppConfig(
name="test_memo_child_cache_hit_still_propagates_deps_to_rebuilt_parent",
environment=coco_env,
),
app_main,
)
# Run 1 (child v1, value x1): parent + child both build.
mod = _load_module(_V1_PATH, metrics, current_module)
_cachehit_child.clear()
_cachehit_child.append(mod.bar_comp_memo)
app.update_blocking()
assert metrics.collect() == {"cachehit_parent": 1, "bar_comp_memo": 1}
assert GlobalDictTarget.store.data["C"].data == "bar_v1: fixed"
# Run 2 (child still v1, value x2): parent's key changed β parent rebuilds;
# child is unchanged β cache HIT. The child must still propagate its deps to
# the rebuilt parent (the `reused` outcome path).
_cachehit_value[0] = "x2"
app.update_blocking()
assert metrics.collect() == {"cachehit_parent": 1} # child cached, didn't run
# Run 3 (child v2, value x2): only the child's code changed. Parent's key
# matches run 2, but its stored deps must include the child's (v1) fp, so the
# parent invalidates, rebuilds, and re-mounts the now-changed child.
mod = _load_module(_V2_PATH, metrics, current_module, old_module=mod)
_cachehit_child.clear()
_cachehit_child.append(mod.bar_comp_memo)
app.update_blocking()
assert metrics.collect() == {"cachehit_parent": 1, "bar_comp_memo": 1}
assert GlobalDictTarget.store.data["C"].data == "bar_v2: fixed"
# ============================================================================
# Explicit version bump invalidates memo (identical function body)
# ============================================================================
def test_fn_memo_invalidated_on_version_bump() -> None:
"""Bumping the version= parameter invalidates memo even when the function body is identical."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.transform_memo_ver("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_fn_memo_invalidated_on_version_bump", environment=coco_env
),
app_main,
)
# version=1: first run β function executes
mod = _load_module(_VER1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"transform_memo_ver": 1}
assert GlobalDictTarget.store.data["A"].data == "ver: value1"
# version=1: second run β memo hit
app.update_blocking()
assert metrics.collect() == {}
# version=2: identical body but version bumped β memo invalidated
mod = _load_module(_VER2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"transform_memo_ver": 1}
assert GlobalDictTarget.store.data["A"].data == "ver: value1"
# version=2: second run β memo hit again
app.update_blocking()
assert metrics.collect() == {}
# ============================================================================
# "self" memoized function β NOT invalidated when child changes,
# IS invalidated when own code changes
# ============================================================================
def test_self_mode_not_invalidated_when_child_changes() -> None:
"""A logic_tracking='self' memo fn is NOT invalidated when its child function changes."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.foo_self("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_self_mode_not_invalidated_when_child_changes",
environment=coco_env,
),
app_main,
)
# v1: first run β foo_self and bar execute
mod = _load_module(_SELF_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"foo_self": 1, "bar": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
# v1: second run β memo hit
app.update_blocking()
assert metrics.collect() == {}
# v2: bar changed but foo_self unchanged β memo NOT invalidated (self mode)
mod = _load_module(_SELF_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {}
# Still has v1 output since memo was reused
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
def test_self_mode_invalidated_when_own_code_changes() -> None:
"""A logic_tracking='self' memo fn IS invalidated when its own code changes."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.foo_self("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_self_mode_invalidated_when_own_code_changes",
environment=coco_env,
),
app_main,
)
# v1: first run β foo_self and bar execute
mod = _load_module(_SELF_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"foo_self": 1, "bar": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
# v1: second run β memo hit
app.update_blocking()
assert metrics.collect() == {}
# v3: foo_self itself changed β memo invalidated
mod = _load_module(_SELF_V3_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"foo_self": 1, "bar": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
# v3: second run β memo hit again
app.update_blocking()
assert metrics.collect() == {}
# ============================================================================
# None memoized function β NOT invalidated on any function logic change
# ============================================================================
def test_none_mode_not_invalidated_on_any_logic_change() -> None:
"""A logic_tracking=None memo fn is NOT invalidated when any function code changes."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.foo_none("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_none_mode_not_invalidated_on_any_logic_change",
environment=coco_env,
),
app_main,
)
# v1: first run β foo_none and bar execute
mod = _load_module(_NONE_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"foo_none": 1, "bar": 1}
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
# v1: second run β memo hit
app.update_blocking()
assert metrics.collect() == {}
# v2: both foo_none and bar changed β memo NOT invalidated (None mode)
mod = _load_module(_NONE_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {}
# Still has v1 output since memo was reused
assert GlobalDictTarget.store.data["A"].data == "bar_v1: value1"
# ============================================================================
# None function still detects change on context key deps
# ============================================================================
_CHANGE_DETECTED_KEY_J3 = coco.ContextKey[str](
"_test_logic_tracking_none_ctx_j3", detect_change=True
)
def _create_env_with_ctx(db_name: str, value: str) -> coco.Environment:
"""Create an Environment with a change-detected context value."""
ctx = coco.ContextProvider()
ctx.provide(_CHANGE_DETECTED_KEY_J3, value)
settings = coco.Settings.from_env(db_path=get_env_db_path(db_name))
return coco.Environment(settings, context_provider=ctx)
def test_none_mode_still_detects_change_on_context_key_deps() -> None:
"""A logic_tracking=None memo fn is still invalidated when a change-detected context value changes."""
GlobalDictTarget.store.clear()
metrics = Metrics()
db_name = "test_none_mode_ctx_deps"
@coco.fn(memo=True, logic_tracking=None)
def process(name: str, content: str) -> None:
val = coco.use_context(_CHANGE_DETECTED_KEY_J3)
metrics.increment("process")
coco.declare_target_state(
GlobalDictTarget.target_state(name, f"{val}:{content}")
)
@coco.fn
async def app_main() -> None:
await coco.mount(coco.component_subpath("A"), process, "A", "data")
# Phase 1: value="v1" β executes then memo hit
env1 = _create_env_with_ctx(db_name, "v1")
app1 = coco.App(coco.AppConfig(name=db_name, environment=env1), app_main)
app1.update_blocking()
assert metrics.collect() == {"process": 1}
assert GlobalDictTarget.store.data["A"].data == "v1:data"
app1.update_blocking()
assert metrics.collect() == {}
del app1, env1
gc.collect()
# Phase 2: value="v2" β change-detected key changed, memo invalidated despite None mode
env2 = _create_env_with_ctx(db_name, "v2")
app2 = coco.App(coco.AppConfig(name=db_name, environment=env2), app_main)
app2.update_blocking()
assert metrics.collect() == {"process": 1}
assert GlobalDictTarget.store.data["A"].data == "v2:data"
app2.update_blocking()
assert metrics.collect() == {}
# ============================================================================
# Transitive β foo("full") β bar("self") β baz
# foo invalidated when bar changes, NOT when baz changes
# ============================================================================
def test_transitive_full_self_plain_bar_changes() -> None:
"""foo(full) β bar(self) β baz. bar changes β foo invalidated."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.foo_full("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_transitive_full_self_plain_bar_changes",
environment=coco_env,
),
app_main,
)
# v1: first run β all three execute
mod = _load_module(_CHAIN_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"foo_full": 1, "bar_self": 1, "baz": 1}
assert GlobalDictTarget.store.data["A"].data == "baz_v1: value1"
# v1: second run β foo memo hit (bar memo also hit inside)
app.update_blocking()
assert metrics.collect() == {}
# v2: bar_self changed β foo invalidated (full propagates bar's fp)
mod = _load_module(_CHAIN_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"foo_full": 1, "bar_self": 1, "baz": 1}
assert GlobalDictTarget.store.data["A"].data == "baz_v1: value1"
# v2: second run β memo hit again
app.update_blocking()
assert metrics.collect() == {}
def test_transitive_full_self_plain_baz_changes() -> None:
"""foo(full) β bar(self) β baz. baz changes β foo NOT invalidated."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.foo_full("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_transitive_full_self_plain_baz_changes",
environment=coco_env,
),
app_main,
)
# v1: first run β all three execute
mod = _load_module(_CHAIN_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"foo_full": 1, "bar_self": 1, "baz": 1}
assert GlobalDictTarget.store.data["A"].data == "baz_v1: value1"
# v1: second run β foo memo hit
app.update_blocking()
assert metrics.collect() == {}
# v3: baz changed but bar_self is "self" mode β baz's fp not propagated past bar
# foo NOT invalidated
mod = _load_module(_CHAIN_V3_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {}
# Still has v1 output since foo memo was reused
assert GlobalDictTarget.store.data["A"].data == "baz_v1: value1"
# ============================================================================
# Bound method β fn memo invalidated on logic change
# ============================================================================
def test_bound_method_fn_memo_invalidated_on_logic_change() -> None:
"""A @coco.fn(memo=True) bound method's cached result is invalidated when code changes."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.processor.transform_memo("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_bound_method_fn_memo_logic_change", environment=coco_env
),
app_main,
)
# v1: first run β method executes
mod = _load_module(_METHOD_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"transform_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "v1: value1"
# v1: second run β memo hit
app.update_blocking()
assert metrics.collect() == {}
# v2: logic changed β memo invalidated, method re-executes
mod = _load_module(_METHOD_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"transform_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "v2: value1"
# v2: second run β memo hit again
app.update_blocking()
assert metrics.collect() == {}
# ============================================================================
# Bound method β component memo invalidated on logic change
# ============================================================================
def test_bound_method_component_memo_invalidated_on_logic_change() -> None:
"""A @coco.fn(memo=True) bound method's component memo is invalidated when code changes."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
async def app_main() -> None:
mod = current_module[0]
await coco.mount(
coco.component_subpath("A"), mod.processor.declare_entry_memo, "A", "value1"
)
app = coco.App(
coco.AppConfig(
name="test_bound_method_component_memo_logic_change", environment=coco_env
),
app_main,
)
# v1: first run β component executes
mod = _load_module(_METHOD_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"declare_entry_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "v1: value1"
# v1: second run β component memo hit
app.update_blocking()
assert metrics.collect() == {}
# v2: logic changed β component memo invalidated
mod = _load_module(_METHOD_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"declare_entry_memo": 1}
assert GlobalDictTarget.store.data["A"].data == "v2: value1"
# v2: second run β component memo hit again
app.update_blocking()
assert metrics.collect() == {}
# ============================================================================
# `deps=` parameter β external value declared as a logic dependency
# ============================================================================
def test_fn_memo_invalidated_on_deps_change() -> None:
"""Changing the value passed to ``deps=`` invalidates the memo even when
the function body is identical, mirroring how ``version=`` behaves."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.transform_memo_deps("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_fn_memo_invalidated_on_deps_change", environment=coco_env
),
app_main,
)
# deps_v1: first run β function executes
mod = _load_module(_DEPS_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"transform_memo_deps": 1}
assert GlobalDictTarget.store.data["A"].data == "deps: value1"
# deps_v1: second run β memo hit
app.update_blocking()
assert metrics.collect() == {}
# deps_v2: identical body but deps value changed β memo invalidated
mod = _load_module(_DEPS_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"transform_memo_deps": 1}
assert GlobalDictTarget.store.data["A"].data == "deps: value1"
# deps_v2: second run β memo hit again
app.update_blocking()
assert metrics.collect() == {}
def test_transitive_deps_change_propagates_through_full() -> None:
"""A child function whose only change is its ``deps=`` value should
invalidate a memoized ``logic_tracking="full"`` parent the same way a
child code change does."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.foo_full("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_transitive_deps_change_propagates_through_full",
environment=coco_env,
),
app_main,
)
# v1: first run β both foo_full and bar execute
mod = _load_module(_DEPS_CHAIN_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"foo_full": 1, "bar": 1}
assert GlobalDictTarget.store.data["A"].data == "bar: value1"
# v1: second run β memo hit at foo_full, bar not called
app.update_blocking()
assert metrics.collect() == {}
# v2: bar's deps changed (body identical) β full propagation invalidates foo_full
mod = _load_module(_DEPS_CHAIN_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {"foo_full": 1, "bar": 1}
assert GlobalDictTarget.store.data["A"].data == "bar: value1"
# v2: second run β memo hit again
app.update_blocking()
assert metrics.collect() == {}
def test_transitive_deps_change_blocked_by_self() -> None:
"""A ``logic_tracking="self"`` parent should NOT be invalidated when a
child function's ``deps=`` changes β ``"self"`` blocks transitive logic
propagation, deps changes included."""
GlobalDictTarget.store.clear()
metrics = Metrics()
current_module: list[Any] = []
@coco.fn
def app_main() -> None:
mod = current_module[0]
result = mod.foo_self("A", "value1")
coco.declare_target_state(GlobalDictTarget.target_state("A", result))
app = coco.App(
coco.AppConfig(
name="test_transitive_deps_change_blocked_by_self",
environment=coco_env,
),
app_main,
)
# v1: first run β both foo_self and bar execute
mod = _load_module(_DEPS_CHAIN_V1_PATH, metrics, current_module)
app.update_blocking()
assert metrics.collect() == {"foo_self": 1, "bar": 1}
assert GlobalDictTarget.store.data["A"].data == "bar: value1"
# v1: second run β memo hit at foo_self
app.update_blocking()
assert metrics.collect() == {}
# v2: bar's deps changed but foo_self is in "self" mode β memo NOT invalidated.
# foo_self keeps returning the cached value, so bar is never called either.
mod = _load_module(_DEPS_CHAIN_V2_PATH, metrics, current_module, old_module=mod)
app.update_blocking()
assert metrics.collect() == {}
assert GlobalDictTarget.store.data["A"].data == "bar: value1"
def test_deps_fingerprint_contract() -> None:
"""Focused unit-level checks on the deps fingerprint contract.
Probes the per-function ``_logic_fp`` directly (bypassing the full
end-to-end app path) to verify that equal deps produce equal fingerprints,
different deps differ, ``__coco_memo_key__()`` is honored, and ``deps``
composes correctly with ``version``.
"""
def my_fn(x: str) -> str:
return x + " done"
# Build several SyncFunction wrappers around the same callable so the
# only varying input is the deps value.
no_deps = SyncFunction(my_fn, memo=True)
deps_a1 = SyncFunction(my_fn, memo=True, deps="prompt-A")
deps_a2 = SyncFunction(my_fn, memo=True, deps="prompt-A")
deps_b = SyncFunction(my_fn, memo=True, deps="prompt-B")
deps_explicit_none = SyncFunction(my_fn, memo=True, deps=None)
try:
assert deps_a1._logic_fp == deps_a2._logic_fp, (
"equal deps must produce equal logic fingerprints"
)
assert deps_a1._logic_fp != deps_b._logic_fp, (
"different deps must produce different logic fingerprints"
)
assert no_deps._logic_fp != deps_a1._logic_fp, (
"absence of deps must differ from a deps value"
)
assert no_deps._logic_fp == deps_explicit_none._logic_fp, (
"deps=None is equivalent to no deps"
)
# Multi-value deps via dict.
deps_dict_1 = SyncFunction(
my_fn,
memo=True,
deps={"prompt": "P", "model": "M"},
)
deps_dict_2 = SyncFunction(
my_fn,
memo=True,
deps={"model": "M", "prompt": "P"}, # same content, different order
)
deps_dict_3 = SyncFunction(
my_fn,
memo=True,
deps={"prompt": "P", "model": "M2"},
)
try:
assert deps_dict_1._logic_fp == deps_dict_2._logic_fp, (
"dict deps must be order-independent"
)
assert deps_dict_1._logic_fp != deps_dict_3._logic_fp, (
"changing any value in dict deps must invalidate the fingerprint"
)
finally:
del deps_dict_1, deps_dict_2, deps_dict_3
gc.collect()
# __coco_memo_key__ contract: the transient field must not affect the fp.
class WithKey:
def __init__(self, n: int, transient: str) -> None:
self.n = n
self.transient = transient
def __coco_memo_key__(self) -> object:
return ("with_key", self.n)
same_a = SyncFunction(my_fn, memo=True, deps=WithKey(42, "noise-a"))
same_b = SyncFunction(my_fn, memo=True, deps=WithKey(42, "noise-b"))
diff = SyncFunction(my_fn, memo=True, deps=WithKey(43, "noise-a"))
try:
assert same_a._logic_fp == same_b._logic_fp, (
"__coco_memo_key__ should ignore transient fields"
)
assert same_a._logic_fp != diff._logic_fp, (
"changing the keyed field must invalidate the fingerprint"
)
finally:
del same_a, same_b, diff
gc.collect()
# version= and deps= are independent contributors: both feed into the
# same _logic_fp, and changing either should change it while holding
# the other fixed.
v1_dA = SyncFunction(my_fn, memo=True, version=1, deps="A")
v1_dA_b = SyncFunction(my_fn, memo=True, version=1, deps="A")
v1_dB = SyncFunction(my_fn, memo=True, version=1, deps="B")
v2_dA = SyncFunction(my_fn, memo=True, version=2, deps="A")
v2_dB = SyncFunction(my_fn, memo=True, version=2, deps="B")
try:
assert v1_dA._logic_fp == v1_dA_b._logic_fp, (
"same version + same deps must produce the same fingerprint"
)
assert v1_dA._logic_fp != v1_dB._logic_fp, (
"same version + different deps must differ"
)
assert v1_dA._logic_fp != v2_dA._logic_fp, (
"different version + same deps must differ"
)
assert v1_dA._logic_fp != v2_dB._logic_fp, (
"different version + different deps must differ"
)
# No collisions across the four distinct cells of the 2x2 matrix.
assert (
len(
{v1_dA._logic_fp, v1_dB._logic_fp, v2_dA._logic_fp, v2_dB._logic_fp}
)
== 4
)
finally:
del v1_dA, v1_dA_b, v1_dB, v2_dA, v2_dB
gc.collect()
finally:
del no_deps, deps_a1, deps_a2, deps_b, deps_explicit_none
gc.collect()
def test_deps_rejected_with_logic_tracking_none() -> None:
"""Passing ``deps=`` with ``logic_tracking=None`` is contradictory β the
function opts out of logic tracking entirely, so deps would be silently
dropped. Catch it at decoration time instead."""
with pytest.raises(ValueError, match="deps="):
@coco.fn(memo=True, deps="ignored", logic_tracking=None)
def _f(x: str) -> str:
return x
with pytest.raises(ValueError, match="deps="):
@coco.fn.as_async(memo=True, deps="ignored", logic_tracking=None)
async def _g(x: str) -> str:
return x
# ---------------------------------------------------------------------------
# Fn-memo HIT must still report the fn's own logic fp to the caller β on both
# the sync and async call paths. Regression: the sync path used to create its
# FnCallContext only on a miss, so a caller's memo entry rebuilt during a run
# where the inner fn hit lost the dep, and a later code change to the inner fn
# went undetected. (The async path always created the ctx before the probe.)
# ---------------------------------------------------------------------------
_hit_dep_runs: list[str] = []
_hit_dep_n: dict[str, int] = {"n": 1}
@coco.fn(memo=True)
def _hit_dep_leaf_sync() -> int:
_hit_dep_runs.append("leaf")
return 1
@coco.fn(memo=True)
async def _hit_dep_mid(n: int) -> int:
_hit_dep_runs.append(f"mid{n}")
return _hit_dep_leaf_sync() + n
async def _hit_dep_main() -> None:
await coco.use_mount(coco.component_subpath("mid"), _hit_dep_mid, _hit_dep_n["n"])
def test_sync_fn_hit_still_reports_logic_dep_to_rebuilt_caller() -> None:
_hit_dep_runs.clear()
_hit_dep_n["n"] = 1
app: coco.App[[], None] = coco.App(
coco.AppConfig(name="test_sync_fn_hit_logic_dep", environment=coco_env),
_hit_dep_main,
)
# Run 1: everything executes.
app.update_blocking()
assert _hit_dep_runs == ["mid1", "leaf"]
# Run 2: mid's memo key changes -> mid re-executes, leaf HITS. Mid's
# rebuilt entry must still record leaf's logic fp.
_hit_dep_runs.clear()
_hit_dep_n["n"] = 2
app.update_blocking()
assert _hit_dep_runs == ["mid2"]
# Run 3: simulate leaf's code changing β its old fp leaves the registry.
leaf_fp = _hit_dep_leaf_sync._logic_fp # type: ignore[attr-defined]
assert leaf_fp is not None
core.unregister_logic_fingerprint(leaf_fp)
try:
_hit_dep_runs.clear()
app.update_blocking()
assert _hit_dep_runs == [
"mid2",
"leaf",
], f"leaf logic change not detected after hit-rebuild: {_hit_dep_runs}"
finally:
core.register_logic_fingerprint(leaf_fp)
# ---------------------------------------------------------------------------
# Fn-memo HIT must also re-offer what its entry recorded *beneath* the fn's own
# fp β the callees it tracked under "full" β to a rebuilt caller. Regression:
# the hit path carried the fn's own fp (above) and its target-provider deps,
# but not the entry's transitive logic deps, so a caller re-stored while the
# inner fn hit lost them, and a later change to a grand-callee went undetected
# (the inner fn's own entry would miss, but a caller that hits never reaches it).
# ---------------------------------------------------------------------------
_hit_tr_runs: list[str] = []
_hit_tr_n: dict[str, int] = {"n": 1}
@coco.fn
def _hit_tr_baz() -> int:
_hit_tr_runs.append("baz")
return 1
@coco.fn(memo=True)
def _hit_tr_leaf_sync() -> int:
_hit_tr_runs.append("leaf")
return _hit_tr_baz()
@coco.fn(memo=True)
async def _hit_tr_leaf_async() -> int:
_hit_tr_runs.append("leaf")
return _hit_tr_baz()
@coco.fn(memo=True)
async def _hit_tr_mid_sync_leaf(n: int) -> int:
_hit_tr_runs.append(f"mid{n}")
return _hit_tr_leaf_sync() + n
@coco.fn(memo=True)
async def _hit_tr_mid_async_leaf(n: int) -> int:
_hit_tr_runs.append(f"mid{n}")
return await _hit_tr_leaf_async() + n
async def _hit_tr_main_sync_leaf() -> None:
await coco.use_mount(
coco.component_subpath("mid"), _hit_tr_mid_sync_leaf, _hit_tr_n["n"]
)
async def _hit_tr_main_async_leaf() -> None:
await coco.use_mount(
coco.component_subpath("mid"), _hit_tr_mid_async_leaf, _hit_tr_n["n"]
)
@pytest.mark.parametrize(
("name", "main"),
[("sync", _hit_tr_main_sync_leaf), ("async", _hit_tr_main_async_leaf)],
)
def test_fn_hit_still_reports_transitive_logic_deps_to_rebuilt_caller(
name: str, main: Any
) -> None:
_hit_tr_runs.clear()
_hit_tr_n["n"] = 1
app: coco.App[[], None] = coco.App(
coco.AppConfig(
name=f"test_fn_hit_transitive_logic_deps_{name}", environment=coco_env
),
main,
)
# Run 1: everything executes; leaf's entry records baz, mid's records both.
app.update_blocking()
assert _hit_tr_runs == ["mid1", "leaf", "baz"]
# Run 2: mid's memo key changes -> mid re-executes, leaf HITS. Mid's
# rebuilt entry must still record baz, which only leaf's entry knew.
_hit_tr_runs.clear()
_hit_tr_n["n"] = 2
app.update_blocking()
assert _hit_tr_runs == ["mid2"]
# Run 3: simulate baz's code changing β its fp leaves the registry. Mid
# must miss (not only leaf, which mid would never reach on a hit).
baz_fp = _hit_tr_baz._logic_fp # type: ignore[attr-defined]
assert baz_fp is not None
core.unregister_logic_fingerprint(baz_fp)
try:
_hit_tr_runs.clear()
app.update_blocking()
assert _hit_tr_runs == ["mid2", "leaf", "baz"], (
f"grand-callee logic change not detected after hit-rebuild: {_hit_tr_runs}"
)
finally:
core.register_logic_fingerprint(baz_fp)