Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

fix(core): validate each data-dependency record once per operation (#2850)

Jiangzhou3706a6dcee4e
diff --git a/docs/src/content/docs/programming_guide/function.mdx b/docs/src/content/docs/programming_guide/function.mdx
index 9d3e6434..acc26d85 100644
--- a/docs/src/content/docs/programming_guide/function.mdx
+++ b/docs/src/content/docs/programming_guide/function.mdx
@@ -579,6 +579,7 @@ The rules for an entry that recorded data dependencies:
- The entry is reused only when its arguments, logic and context match **and** every record validates. A record whose kind is no longer registered, or whose stored key or state no longer deserializes, is a logged miss; a validator's <Lang only="python">exception propagates</Lang><Lang only="rust">error propagates</Lang>. A changed-but-valid state is refreshed without a run. On a miss the body's new records replace the stored set.
- A record rides up through every enclosing function frame regardless of `logic_tracking`, into every enclosing memoized function's entry and the component's entry, where it stops. Records are **not** copied into ancestor components' entries. A component reports one bit upward instead, and its parent's entry lists the children that reported it: **a component is skipped only if its own entry validates and every descendant that recorded data dependencies validates too**, which the parent's probe checks from those descendants' own stored entries, by path, without mounting them. A changed-but-valid descendant record is refreshed in place. The probe stops, and the body re-runs, at a listed descendant with no entry (a non-memoized one, whose records are dropped, or one whose last run observed a key in two states), a record that no longer decodes, a kind no longer registered, or a validator answering invalid. Closed descendants are carried over by the reuse unvalidated, as they always were. A component that records nothing is unaffected.
- Because a parent's probe may validate a record while the component that recorded it is not mounted, a validator runs with no component context and must depend on its key and stored state alone.
+- A record is validated at most once per update. Every later probe in the same update that holds the same stored record (a memoized function beneath a component whose body re-runs, each level above an open component, a sibling that read the same file) takes the first answer without calling the validator. A source that changes after that answer is seen by the next update. A preview validates on its own.
- <Lang only="python">`use_data_dep` raises outside a component context, and when the current frame has already closed. The check covers the current frame only: a `@coco.fn` reader started as a task that outlives the decorated function which started it keeps its own open frame, so its records merge into an already-joined frame and are lost, as its logic deps are today. Await readers inside the function that started them.</Lang><Lang only="rust">`ctx.use_data_dep` returns an error outside a pipeline context, and when the function that owns the current frame has already returned (a spawned task recording after it). Await readers inside the function that started them.</Lang>
#### Callbacks: `logic_propagated_to_callers`
diff --git a/examples/cocoindex_agents/DESIGN.md b/examples/cocoindex_agents/DESIGN.md
index 76c21aad..48d1cd77 100644
--- a/examples/cocoindex_agents/DESIGN.md
+++ b/examples/cocoindex_agents/DESIGN.md
@@ -1328,7 +1328,7 @@ workers skipped) pins that the trace changed nothing memoized.
|---|---|---|---|
| Progress survives failure | solved by `use_mount` per turn | βœ… | partial fn-memo flush on failure (S–M; pure entries only) |
| Skip unchanged **open** sessions | shipped: `coco.DataDep` + `use_data_dep` + `cannot_skip`; adopted 2026-11-04 (*Open vs closed*) | βœ… | β€” |
-| Skip the **parent** of an open session | shipped: transitive validation by path (engine PR #2671, 2026-11-04); one validation per record per run (engine PR #2836, 2026-11-21: the root's records were validated twice when its body re-ran, a search and a request per page each time, Β§3 *Sources: the web*); no change on this side | βœ… | β€” |
+| Skip the **parent** of an open session | shipped: transitive validation by path (engine PR #2671, 2026-11-04); one validation per record per run (engine PR #2836, 2026-11-21: the root's records were validated twice when its body re-ran, a search and a request per page each time, Β§3 *Sources: the web*); a record shared by several probes of one run (a component and the memoized function beneath it, each level above an open session, sibling sessions) validated once per run (engine PR #2850, 2026-11-26); no change on this side | βœ… | β€” |
| Memo probe ("would this hit?") | deferred | β€” | S |
| A component hit keeps its `use_state` values | engine behaviour | βœ… | β€” |
diff --git a/python/cocoindex/_internal/core.pyi b/python/cocoindex/_internal/core.pyi
index daa6f2a8..8fdefc45 100644
--- a/python/cocoindex/_internal/core.pyi
+++ b/python/cocoindex/_internal/core.pyi
@@ -106,6 +106,8 @@ class ComponentProcessorContext:
def stable_path(self) -> StablePath: ...
@property
def live(self) -> bool: ...
+ @property
+ def data_dep_verdicts(self) -> DataDepVerdicts: ...
def join_fn_call(self, child_fn_ctx: FnCallContext) -> None: ...
def initial_context_memo_states(
self,
@@ -145,6 +147,33 @@ class FnCallContext:
class StoredValue:
def get(self, deserialize_fn: Callable[[bytes], T], /) -> T: ...
+class DataDepVerdict:
+ """What a validator answered for one record identity."""
+
+ @property
+ def memo_valid(self) -> bool: ...
+ @property
+ def new_state(self) -> StoredValue | None:
+ """The validator's changed state; `None` when it equals the stored one."""
+ ...
+
+class DataDepVerdicts:
+ """The data-dependency verdicts of one operation, by record identity."""
+
+ def get(
+ self, kind_fp: Fingerprint, key_fp: Fingerprint, state_fp: Fingerprint, /
+ ) -> DataDepVerdict | None: ...
+ def record(
+ self,
+ kind_fp: Fingerprint,
+ key_fp: Fingerprint,
+ state_fp: Fingerprint,
+ memo_valid: bool,
+ state_changed: bool,
+ state: Any,
+ /,
+ ) -> DataDepVerdict: ...
+
# --- FnCallMemoGuard ---
class FnCallMemoGuard:
@property
@@ -160,7 +189,10 @@ class FnCallMemoGuard:
@property
def cached_data_deps(
self,
- ) -> list[tuple[Fingerprint, Fingerprint, StoredValue, StoredValue]] | None: ...
+ ) -> (
+ list[tuple[Fingerprint, Fingerprint, Fingerprint, StoredValue, StoredValue]]
+ | None
+ ): ...
def update_memo_states(
self,
memo_states: list[Any] | None = None,
@@ -466,7 +498,13 @@ def init_runtime(
non_existence: Any,
target_state_codec: ModuleType,
validate_data_deps_fn: Callable[
- [str, list[tuple[Fingerprint, Fingerprint, StoredValue, StoredValue]]],
+ [
+ DataDepVerdicts,
+ str,
+ list[
+ tuple[Fingerprint, Fingerprint, Fingerprint, StoredValue, StoredValue]
+ ],
+ ],
Awaitable[tuple[list[tuple[Fingerprint, Fingerprint, Any, Any]], bool, bool]],
],
) -> None: ...
diff --git a/python/cocoindex/_internal/data_dep.py b/python/cocoindex/_internal/data_dep.py
index fe04ad25..c99cdf01 100644
--- a/python/cocoindex/_internal/data_dep.py
+++ b/python/cocoindex/_internal/data_dep.py
@@ -16,7 +16,10 @@ one bit upward instead (see the engine's ``ComponentRunOutcome``), and the
parent's entry lists the children that reported it. A memoized ancestor's
probe then validates those descendants' records from their own entries
(``validate_stored_data_deps`` below) and reuses the ancestor when they all
-hold. Spec: cocoindex-specs ``data_deps/spec.md``.
+hold. Each stored record is validated at most once per operation: the
+engine keeps the operation's verdicts by record identity
+(``core.DataDepVerdicts``), and every probe consults them before calling a
+validator. Spec: cocoindex-specs ``data_deps/spec.md``.
"""
from __future__ import annotations
@@ -78,6 +81,12 @@ class DataDep:
the stored key and state, as a state function's ``prev_state`` annotation
does.
+ A stored record is validated at most once per operation (one
+ ``App.update``): every later probe in the same operation that holds the
+ same kind, key and stored state takes the first answer without calling
+ ``validate``. A source that changes after that answer is seen by the next
+ operation.
+
**Construct at module import, never inside a component.** A memo entry is
validated against the kinds registered at that moment, so a kind
constructed inside a component registers too late for the entries that
@@ -219,15 +228,20 @@ def use_data_dep(kind: DataDep, /, *, key: object, state: object) -> None:
# ---------------------------------------------------------------------------
# A stored record as the engine hands it to a probe:
-# (kind_fp, key_fp, key, state), key and state as `StoredValue`s.
+# (kind_fp, key_fp, state_fp, key, state), key and state as `StoredValue`s. The
+# three fingerprints are the record's identity in the operation's verdicts.
StoredDataDep = tuple[
- core.Fingerprint, core.Fingerprint, core.StoredValue, core.StoredValue
+ core.Fingerprint,
+ core.Fingerprint,
+ core.Fingerprint,
+ core.StoredValue,
+ core.StoredValue,
]
# A record handed back after validation: (kind_fp, key_fp, key, state). The
# key is the original `StoredValue`; the state is the original `StoredValue`
-# when unchanged, or the validator's new state object otherwise. The engine
-# keeps stored bytes and fingerprints as they are and serializes only a new
-# state, so a refreshed record equals a fresh record of the same observation.
+# when unchanged, or the new state otherwise. The engine keeps stored bytes and
+# fingerprints as they are and serializes only a new state object, so a
+# refreshed record equals a fresh record of the same observation.
RefreshedDataDep = tuple[core.Fingerprint, core.Fingerprint, Any, Any]
@@ -235,6 +249,7 @@ class _DecodedDataDep(NamedTuple):
kind: DataDep
kind_fp: core.Fingerprint
key_fp: core.Fingerprint
+ state_fp: core.Fingerprint
key_stored: core.StoredValue
state_stored: core.StoredValue
key: Any
@@ -257,7 +272,7 @@ def decode_stored_data_deps(
re-runs and re-records.
"""
decoded: list[_DecodedDataDep] = []
- for kind_fp, key_fp, key_stored, state_stored in stored:
+ for kind_fp, key_fp, state_fp, key_stored, state_stored in stored:
kind = _registry.get(kind_fp)
if kind is None:
logger.warning(
@@ -280,66 +295,105 @@ def decode_stored_data_deps(
)
return None
decoded.append(
- _DecodedDataDep(kind, kind_fp, key_fp, key_stored, state_stored, key, state)
+ _DecodedDataDep(
+ kind, kind_fp, key_fp, state_fp, key_stored, state_stored, key, state
+ )
)
return decoded
-def _call_validators(decoded: Sequence[_DecodedDataDep]) -> list[Any]:
- return [rec.kind._validate(rec.key, rec.state) for rec in decoded]
+class _PendingValidation(NamedTuple):
+ """The validate phase split by the operation's verdicts (see
+ ``core.DataDepVerdicts``), one entry per record in both lists: the verdict
+ the operation already holds, or ``None``; and where that is ``None``, the
+ validator's result (or awaitable), ``None`` otherwise."""
+
+ known: list[core.DataDepVerdict | None]
+ outcomes: list[Any]
+
+
+def _call_validators(
+ decoded: Sequence[_DecodedDataDep], verdicts: core.DataDepVerdicts
+) -> _PendingValidation:
+ """Call the validator of each record this operation has not validated
+ yet; a record validated earlier in the operation takes that verdict."""
+ known = [verdicts.get(rec.kind_fp, rec.key_fp, rec.state_fp) for rec in decoded]
+ outcomes = [
+ rec.kind._validate(rec.key, rec.state) if verdict is None else None
+ for rec, verdict in zip(decoded, known)
+ ]
+ return _PendingValidation(known, outcomes)
def _fold_outcomes(
- decoded: Sequence[_DecodedDataDep], outcomes: Sequence[Any]
+ decoded: Sequence[_DecodedDataDep],
+ verdicts: core.DataDepVerdicts,
+ pending: _PendingValidation,
) -> DataDepValidation:
+ """Combine known verdicts and fresh outcomes, recording each fresh outcome
+ in the operation's verdicts. A probe acts on the verdict ``record``
+ returns: its own, or the one a concurrent probe recorded first."""
refreshed: list[RefreshedDataDep] = []
can_reuse = True
states_changed = False
- for rec, outcome in zip(decoded, outcomes):
- if not isinstance(outcome, MemoStateOutcome):
- raise TypeError(
- f"{rec.kind!r}.validate must return coco.MemoStateOutcome, got "
- f"{outcome!r}"
+ for rec, verdict, outcome in zip(decoded, pending.known, pending.outcomes):
+ if verdict is None:
+ if not isinstance(outcome, MemoStateOutcome):
+ raise TypeError(
+ f"{rec.kind!r}.validate must return coco.MemoStateOutcome, "
+ f"got {outcome!r}"
+ )
+ verdict = verdicts.record(
+ rec.kind_fp,
+ rec.key_fp,
+ rec.state_fp,
+ outcome.memo_valid,
+ outcome.state != rec.state,
+ outcome.state,
)
- if not outcome.memo_valid:
+ if not verdict.memo_valid:
can_reuse = False
- if outcome.state != rec.state:
+ new_state = verdict.new_state
+ if new_state is not None:
states_changed = True
- state_out: Any = outcome.state
- else:
- state_out = rec.state_stored
+ state_out = new_state if new_state is not None else rec.state_stored
refreshed.append((rec.kind_fp, rec.key_fp, rec.key_stored, state_out))
return DataDepValidation(refreshed, can_reuse, states_changed)
def validate_data_deps_sync(
- decoded: Sequence[_DecodedDataDep], *, running_loop_error_msg: str
+ decoded: Sequence[_DecodedDataDep],
+ verdicts: core.DataDepVerdicts,
+ *,
+ running_loop_error_msg: str,
) -> DataDepValidation:
- """Validate phase, sync: call every validator; a validator's exception
- propagates. Awaitables are resolved as memo state functions' are."""
- outcomes = _call_validators(decoded)
+ """Validate phase, sync: call the validator of every record the operation
+ has not validated yet; a validator's exception propagates. Awaitables are
+ resolved as memo state functions' are."""
+ pending = _call_validators(decoded, verdicts)
outcomes = resolve_awaitables_sync(
- outcomes, running_loop_error_msg=running_loop_error_msg
+ pending.outcomes, running_loop_error_msg=running_loop_error_msg
)
- return _fold_outcomes(decoded, outcomes)
+ return _fold_outcomes(decoded, verdicts, pending._replace(outcomes=outcomes))
async def validate_data_deps_async(
- decoded: Sequence[_DecodedDataDep],
+ decoded: Sequence[_DecodedDataDep], verdicts: core.DataDepVerdicts
) -> DataDepValidation:
- """Validate phase, async: validators run concurrently; an exception
- propagates."""
- outcomes = _call_validators(decoded)
+ """Validate phase, async: the validators of the records the operation has
+ not validated yet run concurrently; an exception propagates."""
+ pending = _call_validators(decoded, verdicts)
+ outcomes = pending.outcomes
awaitable_indices = [i for i, o in enumerate(outcomes) if isinstance(o, Awaitable)]
if awaitable_indices:
resolved = await asyncio.gather(*(outcomes[i] for i in awaitable_indices))
for i, value in zip(awaitable_indices, resolved):
outcomes[i] = value
- return _fold_outcomes(decoded, outcomes)
+ return _fold_outcomes(decoded, verdicts, pending)
async def validate_stored_data_deps(
- path: str, stored: list[StoredDataDep]
+ verdicts: core.DataDepVerdicts, path: str, stored: list[StoredDataDep]
) -> tuple[list[RefreshedDataDep], bool, bool]:
"""The engine's processor-free entry (``EngineProfile::validate_data_deps``).
@@ -348,10 +402,11 @@ async def validate_stored_data_deps(
there is no processor, no state handler and no component context for the
row at ``path``, only its records. Same two phases as a component's own
probe: decode (a failure is a logged miss, no validator called), then the
- validators, whose exceptions propagate. Registered at ``init_runtime``.
+ validators, whose exceptions propagate, against the operation's
+ ``verdicts``. Registered at ``init_runtime``.
"""
decoded = decode_stored_data_deps(stored, where=f"component {path}")
if decoded is None:
return [], False, False
- validation = await validate_data_deps_async(decoded)
+ validation = await validate_data_deps_async(decoded, verdicts)
return validation.refreshed, validation.can_reuse, validation.states_changed
diff --git a/python/cocoindex/_internal/function.py b/python/cocoindex/_internal/function.py
index cb0ef9e6..1403a938 100644
--- a/python/cocoindex/_internal/function.py
+++ b/python/cocoindex/_internal/function.py
@@ -429,9 +429,13 @@ def _data_deps_decode_failed() -> DataDepValidation:
def _probe_data_deps_sync(
- guard: core.FnCallMemoGuard, *, where: str
+ guard: core.FnCallMemoGuard,
+ processor_ctx: core.ComponentProcessorContext,
+ *,
+ where: str,
) -> DataDepValidation | None:
- """Decode and validate a hit entry's stored data dependencies.
+ """Decode and validate a hit entry's stored data dependencies, against the
+ verdicts of ``processor_ctx``'s operation.
``None`` when the entry recorded none. A decode failure (kind gone, stored
key or state no longer deserializes) is a logged miss and calls no
@@ -444,12 +448,17 @@ def _probe_data_deps_sync(
if decoded is None:
return _data_deps_decode_failed()
return validate_data_deps_sync(
- decoded, running_loop_error_msg=_SYNC_RUNNING_LOOP_ERROR_MSG
+ decoded,
+ processor_ctx.data_dep_verdicts,
+ running_loop_error_msg=_SYNC_RUNNING_LOOP_ERROR_MSG,
)
async def _probe_data_deps_async(
- guard: core.FnCallMemoGuard, *, where: str
+ guard: core.FnCallMemoGuard,
+ processor_ctx: core.ComponentProcessorContext,
+ *,
+ where: str,
) -> DataDepValidation | None:
"""Async variant of :func:`_probe_data_deps_sync`."""
stored = guard.cached_data_deps
@@ -458,23 +467,25 @@ async def _probe_data_deps_async(
decoded = decode_stored_data_deps(stored, where=where)
if decoded is None:
return _data_deps_decode_failed()
- return await validate_data_deps_async(decoded)
+ return await validate_data_deps_async(decoded, processor_ctx.data_dep_verdicts)
async def _validate_component_data_deps(
validated: StateMethodsResult,
data_deps_stored: list[StoredDataDep] | None,
+ comp_ctx: core.ComponentProcessorContext,
*,
where: str,
) -> StateMethodsResult:
"""Fold a component entry's stored data dependencies into the state
- validation result: decode phase, then validators (see ``data_dep``)."""
+ validation result: decode phase, then validators, against the verdicts of
+ ``comp_ctx``'s operation (see ``data_dep``)."""
if not data_deps_stored:
return validated
decoded = decode_stored_data_deps(data_deps_stored, where=where)
if decoded is None:
return validated._replace(can_reuse=False)
- dd = await validate_data_deps_async(decoded)
+ dd = await validate_data_deps_async(decoded, comp_ctx.data_dep_verdicts)
return validated._replace(
can_reuse=validated.can_reuse and dd.can_reuse,
states_changed=validated.states_changed or dd.states_changed,
@@ -564,6 +575,7 @@ def _make_component_state_handling(
return await _validate_component_data_deps(
validated,
data_deps_stored,
+ comp_ctx,
where=f"component {path.to_string()}",
)
# Cache miss: look up the eager initial states for the context fps
@@ -1074,7 +1086,9 @@ class SyncFunction(Function[P, R_co]):
# validated only when the states still allow a reuse.
data_deps = (
_probe_data_deps_sync(
- guard, where=_data_dep_where(self._fn)
+ guard,
+ parent_ctx._core_processor_ctx,
+ where=_data_dep_where(self._fn),
)
if use_cache
else None
@@ -1623,7 +1637,9 @@ class AsyncFunction(Function[P, R_co]):
# validated only when the states still allow a reuse.
data_deps = (
await _probe_data_deps_async(
- guard, where=_data_dep_where(self._any_fn)
+ guard,
+ parent_ctx._core_processor_ctx,
+ where=_data_dep_where(self._any_fn),
)
if use_cache
else None
diff --git a/python/tests/core/test_data_dep.py b/python/tests/core/test_data_dep.py
index c1016bd2..0567c7ad 100644
--- a/python/tests/core/test_data_dep.py
+++ b/python/tests/core/test_data_dep.py
@@ -342,6 +342,158 @@ def test_a_hit_re_offers_its_records_to_a_caller_stored_later() -> None:
assert _data() == {name: "outer:A2"}
+# ---------------------------------------------------------------------------
+# One validation per record per operation
+# ---------------------------------------------------------------------------
+
+_fn_read_path: dict[str, pathlib.Path] = {}
+_own_read_path: dict[str, pathlib.Path] = {}
+# Run by the component's body between its own read and the function call, to
+# change a source after the component's probe validated it.
+_between_probes: dict[str, Any] = {}
+
+
+def _fn_reading(name: str) -> str:
+ _metrics.increment("run.fn")
+ return _read(_fn_read_path[name]).decode()
+
+
+def _component_reading(name: str) -> None:
+ _metrics.increment("run.component")
+ own = _read(_own_read_path[name]).decode()
+ between = _between_probes.pop(name, None)
+ if between is not None:
+ between()
+ coco.declare_target_state(
+ GlobalDictTarget.target_state(name, own + _fn_reading(name))
+ )
+
+
+async def _component_reading_main(name: str) -> None:
+ await coco.use_mount(coco.component_subpath(name), _component_reading, name)
+
+
+def test_a_record_validated_at_a_component_is_not_validated_again_beneath_it() -> None:
+ """The function's read rides into the component's entry too. When the
+ component's own read invalidates it, the body re-runs and the function's
+ probe takes the verdict the component's probe got for the shared record
+ instead of calling the validator again."""
+ _reset()
+ _between_probes.clear()
+ with tempfile.TemporaryDirectory() as d:
+ a = pathlib.Path(d) / "a.txt"
+ b = pathlib.Path(d) / "b.txt"
+ _write(a, "A1")
+ _write(b, "B1")
+ _fn_read_path["n"] = a
+ _own_read_path["n"] = b
+ app = _app("test_dd_once_per_op", _component_reading_main, "n")
+ app.update_blocking()
+ assert _metrics.collect() == {"run.component": 1, "run.fn": 1}
+
+ # b changed: a is validated once, at the component's probe.
+ _write(b, "B2")
+ app.update_blocking()
+ assert _metrics.collect() == {
+ "run.component": 1,
+ "validate.file": 2,
+ "validate.file.digest": 1,
+ }
+ assert _data() == {"n": "B2A1"}
+
+ # a moved while staying valid and b changed: the function's probe
+ # takes a's changed-but-valid verdict and refreshes its entry with it.
+ _touch(a)
+ _write(b, "B3")
+ app.update_blocking()
+ assert _metrics.collect() == {
+ "run.component": 1,
+ "validate.file": 2,
+ "validate.file.digest": 2,
+ }
+ assert _data() == {"n": "B3A1"}
+
+ # Both entries hold a's refreshed state: the next probe takes the
+ # fast path for it. Each operation validates afresh.
+ app.update_blocking()
+ assert _metrics.collect() == {"validate.file": 2}
+
+
+def test_a_change_between_two_probes_is_seen_by_the_next_operation() -> None:
+ """An operation acts on the first verdict for a record: a source that
+ changes after the component's probe validated it does not make the
+ function's probe in the same operation miss. The next operation validates
+ the stored record afresh and re-runs both."""
+ _reset()
+ _between_probes.clear()
+ with tempfile.TemporaryDirectory() as d:
+ a = pathlib.Path(d) / "a.txt"
+ b = pathlib.Path(d) / "b.txt"
+ _write(a, "A1")
+ _write(b, "B1")
+ _fn_read_path["n"] = a
+ _own_read_path["n"] = b
+ app = _app("test_dd_change_between", _component_reading_main, "n")
+ app.update_blocking()
+ _metrics.clear()
+
+ _write(b, "B2")
+ _between_probes["n"] = lambda: _write(a, "A2")
+ app.update_blocking()
+ assert _metrics.collect() == {
+ "run.component": 1,
+ "validate.file": 2,
+ "validate.file.digest": 1,
+ }
+ assert _data() == {"n": "B2A1"}
+
+ app.update_blocking()
+ assert _metrics.collect() == {
+ "run.component": 1,
+ "run.fn": 1,
+ "validate.file": 2,
+ "validate.file.digest": 1,
+ }
+ assert _data() == {"n": "B2A2"}
+
+ app.update_blocking()
+ assert _metrics.collect() == {"validate.file": 2}
+
+
+def test_a_record_shared_by_sibling_components_is_validated_once() -> None:
+ """Two components that read one file, mounted one after the other, hold
+ the same record: the second probe takes the first one's verdict."""
+ _reset()
+ with tempfile.TemporaryDirectory() as d:
+ a = pathlib.Path(d) / "a.txt"
+ _write(a, "A1")
+ _reads["s1"] = [a]
+ _reads["s2"] = [a]
+ app = _app("test_dd_shared_siblings", _sessions_main, ["s1", "s2"])
+ app.update_blocking()
+ _metrics.clear()
+
+ app.update_blocking()
+ assert _metrics.collect() == {"validate.file": 1}
+
+ _touch(a)
+ app.update_blocking()
+ assert _metrics.collect() == {"validate.file": 1, "validate.file.digest": 1}
+
+ _write(a, "A2")
+ app.update_blocking()
+ assert _metrics.collect() == {
+ "run.s1": 1,
+ "run.s2": 1,
+ "validate.file": 1,
+ "validate.file.digest": 1,
+ }
+ assert _data() == {"s1": "A2", "s2": "A2"}
+
+
# ---------------------------------------------------------------------------
# Snapshots and coarse memo keys
# ---------------------------------------------------------------------------
@@ -492,10 +644,11 @@ def test_a_memoized_ancestor_is_reused_while_its_open_descendants_reads_validate
app.update_blocking()
assert _metrics.collect() == {"validate.file": 1}
- # Edited: the read is invalid at the grandparent's probe, then at the
- # parent's, then at the open child's own; each level re-runs its body.
- # This run records nothing, so the ancestors store unflagged memos and
- # the next run reuses the grandparent without validating anything.
+ # Edited: the read is invalid at the grandparent's probe; each level
+ # re-runs its body, and the parent's probe and the open child's own
+ # take that verdict without validating again. This run records
+ # nothing, so the ancestors store unflagged memos and the next run
+ # reuses the grandparent without validating anything.
_reads["open"] = []
_write(a, "A2")
app.update_blocking()
@@ -503,8 +656,8 @@ def test_a_memoized_ancestor_is_reused_while_its_open_descendants_reads_validate
"run.gp": 1,
"run.p": 1,
"run.open": 1,
- "validate.file": 3,
- "validate.file.digest": 3,
+ "validate.file": 1,
+ "validate.file.digest": 1,
}
app.update_blocking()
assert _metrics.collect() == {}
diff --git a/rust/core/src/engine/component.rs b/rust/core/src/engine/component.rs
index 10436289..a6b857b0 100644
--- a/rust/core/src/engine/component.rs
+++ b/rust/core/src/engine/component.rs
@@ -2223,6 +2223,7 @@ mod tests {
/// The test profile registers no kinds, so no record validates.
fn validate_data_deps(
_host_runtime_ctx: &(),
+ _verdicts: Arc<crate::engine::context::DataDepVerdicts>,
_path: &StablePath,
records: Vec<crate::engine::context::DataDepRecord>,
) -> crate::prelude::Result<
diff --git a/rust/core/src/engine/context.rs b/rust/core/src/engine/context.rs
index 907f400b..8919f9f6 100644
--- a/rust/core/src/engine/context.rs
+++ b/rust/core/src/engine/context.rs
@@ -341,6 +341,87 @@ pub(crate) fn decode_data_deps(entries: Vec<db_schema::DataDepEntry<'_>>) -> Vec
.collect()
}
+/// A stored data-dependency record as one validation sees it: its kind, its
+/// key and the state it was recorded with. Two probes that hold this identity
+/// ask the validator the same question.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct DataDepIdentity {
+ pub kind_fp: Fingerprint,
+ pub key_fp: Fingerprint,
+ pub state_fp: Fingerprint,
+}
+
+impl DataDepRecord {
+ pub fn identity(&self) -> DataDepIdentity {
+ DataDepIdentity {
+ kind_fp: self.kind_fp,
+ key_fp: self.key_fp,
+ state_fp: self.state_fp,
+ }
+ }
+}
+
+/// What a validator answered for one record identity.
+#[derive(Clone, Debug)]
+pub struct DataDepVerdict {
+ pub memo_valid: bool,
+ /// The state the validator returned, serialized, when it differs from the
+ /// record's; `None` when it is unchanged.
+ pub new_state: Option<bytes::Bytes>,
+}
+
+impl DataDepVerdict {
+ /// The record as this verdict leaves it: as stored, or with the new state.
+ pub fn apply(&self, record: DataDepRecord) -> DataDepRecord {
+ match &self.new_state {
+ None => record,
+ Some(state) => DataDepRecord {
+ state_fp: Fingerprint::from_bytes(state),
+ state: state.clone(),
+ ..record
+ },
+ }
+ }
+}
+
+/// The verdicts of the data-dependency records validated in one operation, by
+/// record identity. Every context of the operation shares one (see
+/// [`ComponentProcessorContext::data_dep_verdicts`]), so a record a probe
+/// validated is not validated again by a later probe in the same operation:
+/// a component's probe and then, when its body re-runs, the probe of a
+/// memoized function beneath it that recorded the same read, or each level
+/// of a chain of flagged ancestors.
+///
+/// An operation acts on the first verdict recorded for an identity. A source
+/// that changes after it is seen by the next operation, which validates the
+/// stored records afresh. Probes of one identity that run concurrently may
+/// each call the validator; [`record`](Self::record) then hands every one the
+/// first verdict, so they still agree. Nothing here persists: the cache lives
+/// as long as the operation's contexts.
+#[derive(Debug, Default)]
+pub struct DataDepVerdicts {
+ verdicts: Mutex<HashMap<DataDepIdentity, DataDepVerdict>>,
+}
+
+impl DataDepVerdicts {
+ /// The verdict this operation already holds for `identity`, if any.
+ pub fn get(&self, identity: &DataDepIdentity) -> Option<DataDepVerdict> {
+ self.verdicts.lock().unwrap().get(identity).cloned()
+ }
+
+ /// Record the verdict a validator just returned for `identity`, and return
+ /// the verdict the operation acts on: this one, or the one a concurrent
+ /// probe recorded first.
+ pub fn record(&self, identity: DataDepIdentity, verdict: DataDepVerdict) -> DataDepVerdict {
+ self.verdicts
+ .lock()
+ .unwrap()
+ .entry(identity)
+ .or_insert(verdict)
+ .clone()
+ }
+}
+
pub struct FnCallMemo<Prof: EngineProfile> {
pub ret: Prof::FunctionData,
pub(crate) target_state_paths: Vec<TargetStatePath>,
@@ -901,6 +982,8 @@ struct ComponentProcessorContextInner<Prof: EngineProfile> {
app_store: AppStore,
/// See [`ComponentProcessorContext::operation_generation`].
operation_generation: u64,
+ /// See [`ComponentProcessorContext::data_dep_verdicts`].
+ data_dep_verdicts: Arc<DataDepVerdicts>,
/// This run's in-flight token and the lender its children borrow from;
/// see [`crate::engine::admission`].
@@ -1050,6 +1133,10 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
Some(parent) => parent.operation_generation(),
None => component.app_ctx().next_operation_generation(),
};
+ let data_dep_verdicts = match &parent_context {
+ Some(parent) => parent.data_dep_verdicts().clone(),
+ None => Arc::default(),
+ };
Self {
inner: Arc::new(ComponentProcessorContextInner {
component,
@@ -1057,6 +1144,7 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
processing_action,
app_store,
operation_generation,
+ data_dep_verdicts,
admission,
update_refusal,
left_out_children: Arc::new(AtomicBool::new(false)),
@@ -1397,6 +1485,16 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
self.inner.operation_generation
}
+ /// The verdicts of the data-dependency records validated so far in this
+ /// context's operation (see [`DataDepVerdicts`]). It follows
+ /// [`operation_generation`](Self::operation_generation): a context without
+ /// a parent starts an empty one, children share their parent's. A preview
+ /// is an operation of its own, so it validates afresh and keeps its
+ /// verdicts to itself.
+ pub fn data_dep_verdicts(&self) -> &Arc<DataDepVerdicts> {
+ &self.inner.data_dep_verdicts
+ }
+
/// The collector of a preview run's actions. Only a build runs as a
/// preview: a preview plans no deletes of components.
pub(crate) fn preview_collector(&self) -> Option<&PreviewActionCollector<Prof>> {
diff --git a/rust/core/src/engine/execution.rs b/rust/core/src/engine/execution.rs
index 5fe43c43..7d4177ac 100644
--- a/rust/core/src/engine/execution.rs
+++ b/rust/core/src/engine/execution.rs
@@ -326,7 +326,13 @@ pub(crate) async fn validate_open_descendants<Prof: EngineProfile>(
};
if !memo_info.data_deps.is_empty() {
let records = decode_data_deps(memo_info.data_deps);
- let validation = Prof::validate_data_deps(host_runtime_ctx, &path, records)?.await?;
+ let validation = Prof::validate_data_deps(
+ host_runtime_ctx,
+ comp_ctx.data_dep_verdicts().clone(),
+ &path,
+ records,
+ )?
+ .await?;
if !validation.can_reuse {
return Ok(OpenDescendantsVerdict::NotReusable(format!(
"a data dependency of open descendant {path} no longer validates"
diff --git a/rust/core/src/engine/profile.rs b/rust/core/src/engine/profile.rs
index 8fb61780..7a66bf77 100644
--- a/rust/core/src/engine/profile.rs
+++ b/rust/core/src/engine/profile.rs
@@ -2,7 +2,7 @@ use std::{fmt::Debug, hash::Hash, sync::Arc};
use crate::engine::{
component::ComponentProcessor,
- context::DataDepRecord,
+ context::{DataDepRecord, DataDepVerdicts},
target_state::{TargetActionSink, TargetHandler},
};
use crate::prelude::*;
@@ -62,8 +62,14 @@ pub trait EngineProfile: Debug + Clone + PartialEq + Eq + Hash + Default + 'stat
/// longer registered, or whose key or state no longer decodes, make
/// `can_reuse` false (logged, no validator called); a validator's own
/// error propagates.
+ ///
+ /// `verdicts` is the operation's (see `DataDepVerdicts`): a record whose
+ /// identity it holds takes that verdict without calling its validator, and
+ /// a validator's answer is recorded there, as at a component's or a
+ /// function's probe.
fn validate_data_deps(
host_runtime_ctx: &Self::HostRuntimeCtx,
+ verdicts: Arc<DataDepVerdicts>,
path: &StablePath,
records: Vec<DataDepRecord>,
) -> Result<impl Future<Output = Result<DataDepsValidation>> + Send + 'static>;
diff --git a/rust/py/src/context.rs b/rust/py/src/context.rs
index 09724ae0..91e8b956 100644
--- a/rust/py/src/context.rs
+++ b/rust/py/src/context.rs
@@ -1,5 +1,5 @@
use crate::fingerprint::PyFingerprint;
-use crate::function::context_initial_states_to_pydict;
+use crate::function::{PyDataDepVerdicts, context_initial_states_to_pydict};
use crate::prelude::*;
use crate::deadline::PyDeadlineContext;
@@ -34,6 +34,12 @@ impl PyComponentProcessorContext {
self.0.live()
}
+ /// The data-dependency verdicts of this context's operation.
+ #[getter]
+ fn data_dep_verdicts(&self) -> PyDataDepVerdicts {
+ PyDataDepVerdicts(self.0.data_dep_verdicts().clone())
+ }
+
fn join_fn_call(&self, fn_ctx: &PyFnCallContext) -> PyResult<()> {
self.0.join_fn_call(&fn_ctx.0);
Ok(())
diff --git a/rust/py/src/function.rs b/rust/py/src/function.rs
index edc5b5b2..ad6853c6 100644
--- a/rust/py/src/function.rs
+++ b/rust/py/src/function.rs
@@ -1,6 +1,8 @@
use std::collections::HashMap;
-use cocoindex_core::engine::context::{DataDepRecord, MemoStatesPayload};
+use cocoindex_core::engine::context::{
+ DataDepIdentity, DataDepRecord, DataDepVerdict, DataDepVerdicts, MemoStatesPayload,
+};
use cocoindex_core::engine::function::FnCallMemoGuard;
use cocoindex_core::engine::profile::Persist;
use cocoindex_core::engine::runtime::get_runtime;
@@ -97,9 +99,9 @@ pub(crate) fn build_memo_states_payload(
}
/// Convert stored data-dependency records into a Python list of
-/// `(kind_fp, key_fp, key, state)` tuples (the same shape as
-/// [`PyRefreshedDataDep`]), key and state as `StoredValue`s the probe decodes
-/// through the kind's deserializers.
+/// `(kind_fp, key_fp, state_fp, key, state)` tuples, key and state as
+/// `StoredValue`s the probe decodes through the kind's deserializers. The
+/// three fingerprints are the record's identity (see `DataDepVerdicts`).
pub(crate) fn data_deps_to_pylist<'py>(
py: Python<'py>,
records: &[DataDepRecord],
@@ -112,6 +114,7 @@ pub(crate) fn data_deps_to_pylist<'py>(
Ok((
Py::new(py, PyFingerprint(r.kind_fp))?,
Py::new(py, PyFingerprint(r.key_fp))?,
+ Py::new(py, PyFingerprint(r.state_fp))?,
key,
state,
))
@@ -120,6 +123,101 @@ pub(crate) fn data_deps_to_pylist<'py>(
PyList::new(py, items)
}
+/// What a validator answered for one record identity, as a probe reads it.
+#[pyclass(frozen, name = "DataDepVerdict")]
+pub struct PyDataDepVerdict {
+ memo_valid: bool,
+ new_state: Option<PyStoredValue>,
+}
+
+#[pymethods]
+impl PyDataDepVerdict {
+ #[getter]
+ fn memo_valid(&self) -> bool {
+ self.memo_valid
+ }
+
+ /// The validator's changed state; `None` when it equals the stored one.
+ #[getter]
+ fn new_state(&self) -> Option<PyStoredValue> {
+ self.new_state.clone()
+ }
+}
+
+fn verdict_to_py(verdict: DataDepVerdict) -> PyResult<PyDataDepVerdict> {
+ let new_state = verdict
+ .new_state
+ .map(|bytes| PyStoredValue::from_bytes(&bytes).into_py_result())
+ .transpose()?;
+ Ok(PyDataDepVerdict {
+ memo_valid: verdict.memo_valid,
+ new_state,
+ })
+}
+
+fn identity(
+ kind_fp: &PyFingerprint,
+ key_fp: &PyFingerprint,
+ state_fp: &PyFingerprint,
+) -> DataDepIdentity {
+ DataDepIdentity {
+ kind_fp: kind_fp.0,
+ key_fp: key_fp.0,
+ state_fp: state_fp.0,
+ }
+}
+
+/// The data-dependency verdicts of one operation (`DataDepVerdicts` in the
+/// core): a probe takes the verdict of a record identity validated earlier in
+/// the operation instead of calling its validator, and records the answer of
+/// each validator it does call.
+#[pyclass(frozen, name = "DataDepVerdicts")]
+pub struct PyDataDepVerdicts(pub Arc<DataDepVerdicts>);
+
+#[pymethods]
+impl PyDataDepVerdicts {
+ /// The verdict this operation holds for the record identity, if any.
+ fn get(
+ &self,
+ kind_fp: PyFingerprint,
+ key_fp: PyFingerprint,
+ state_fp: PyFingerprint,
+ ) -> PyResult<Option<PyDataDepVerdict>> {
+ self.0
+ .get(&identity(&kind_fp, &key_fp, &state_fp))
+ .map(verdict_to_py)
+ .transpose()
+ }
+
+ /// Record a validator's answer for the record identity: `memo_valid`, and
+ /// the state it returned, which is kept only when `state_changed` (it
+ /// differs from the stored one). Returns the verdict the operation acts
+ /// on: this one, or one a concurrent probe recorded first.
+ #[allow(clippy::too_many_arguments)]
+ fn record(
+ &self,
+ py: Python<'_>,
+ kind_fp: PyFingerprint,
+ key_fp: PyFingerprint,
+ state_fp: PyFingerprint,
+ memo_valid: bool,
+ state_changed: bool,
+ state: Py<PyAny>,
+ ) -> PyResult<PyDataDepVerdict> {
+ let new_state = state_changed
+ .then(|| data_dep_bytes(py, state))
+ .transpose()?;
+ let verdict = self.0.record(
+ identity(&kind_fp, &key_fp, &state_fp),
+ DataDepVerdict {
+ memo_valid,
+ new_state,
+ },
+ );
+ verdict_to_py(verdict)
+ }
+}
+
/// Convert the stored context-borne memo states into a Python `dict`
/// `{Fingerprint: list[PyStoredValue]}` keyed by fingerprint for O(1) lookup
/// on the Python side.
diff --git a/rust/py/src/lib.rs b/rust/py/src/lib.rs
index 44ca443b..cd9b149a 100644
--- a/rust/py/src/lib.rs
+++ b/rust/py/src/lib.rs
@@ -53,6 +53,8 @@ fn core_module(m: &pyo3::Bound<'_, pyo3::types::PyModule>) -> pyo3::PyResult<()>
m.add_class::<context::PyComponentProcessorContext>()?;
m.add_class::<context::PyFnCallContext>()?;
+ m.add_class::<function::PyDataDepVerdict>()?;
+ m.add_class::<function::PyDataDepVerdicts>()?;
m.add_class::<deadline::PyDeadlineContext>()?;
m.add_function(wrap_pyfunction!(deadline::deadline_none, m)?)?;
diff --git a/rust/py/src/profile.rs b/rust/py/src/profile.rs
index 317126d8..837d2ba0 100644
--- a/rust/py/src/profile.rs
+++ b/rust/py/src/profile.rs
@@ -1,10 +1,12 @@
-use cocoindex_core::engine::context::DataDepRecord;
+use cocoindex_core::engine::context::{DataDepRecord, DataDepVerdicts};
use cocoindex_core::engine::profile::{DataDepsValidation, EngineProfile};
use cocoindex_core::state::stable_path::StablePath;
use crate::{
component::PyComponentProcessor,
- function::{PyRefreshedDataDep, build_data_dep_records, data_deps_to_pylist},
+ function::{
+ PyDataDepVerdicts, PyRefreshedDataDep, build_data_dep_records, data_deps_to_pylist,
+ },
prelude::*,
runtime::{PyAsyncContext, python_objects},
target_state::{PyTargetActionSinkInner, PyTargetHandler},
@@ -33,16 +35,22 @@ impl EngineProfile for PyEngineProfile {
/// context around them.
fn validate_data_deps(
host_runtime_ctx: &PyAsyncContext,
+ verdicts: Arc<DataDepVerdicts>,
path: &StablePath,
records: Vec<DataDepRecord>,
) -> Result<impl Future<Output = Result<DataDepsValidation>> + Send + 'static> {
- let py_records: Py<PyAny> = Python::attach(|py| {
- data_deps_to_pylist(py, &records).map(|list| list.unbind().into_any())
- })
- .from_py_result()?;
- let fut = python_objects()
- .validate_data_deps_fn
- .call(host_runtime_ctx, (path.to_string(), py_records))?;
+ let (py_verdicts, py_records): (Py<PyDataDepVerdicts>, Py<PyAny>) =
+ Python::attach(|py| -> PyResult<_> {
+ Ok((
+ Py::new(py, PyDataDepVerdicts(verdicts))?,
+ data_deps_to_pylist(py, &records)?.unbind().into_any(),
+ ))
+ })
+ .from_py_result()?;
+ let fut = python_objects().validate_data_deps_fn.call(
+ host_runtime_ctx,
+ (py_verdicts, path.to_string(), py_records),
+ )?;
Ok(async move {
let result = fut.await?;
Python::attach(|py| -> PyResult<DataDepsValidation> {
diff --git a/rust/sdk/cocoindex/src/deps.rs b/rust/sdk/cocoindex/src/deps.rs
index b6a9cb47..45d6de6d 100644
--- a/rust/sdk/cocoindex/src/deps.rs
+++ b/rust/sdk/cocoindex/src/deps.rs
@@ -14,7 +14,9 @@ use std::future::Future;
use std::marker::PhantomData;
use std::sync::{Arc, LazyLock, RwLock, Weak};
-use cocoindex_core::engine::context::{DataDepRecord, FnCallContext};
+use cocoindex_core::engine::context::{
+ DataDepRecord, DataDepVerdict, DataDepVerdicts, FnCallContext,
+};
use cocoindex_core::engine::logic_registry;
use cocoindex_utils::fingerprint::Fingerprint;
use futures::future::BoxFuture;
@@ -180,6 +182,11 @@ impl Drop for DataDepInner {
/// in place of the old one when it differs) and whether the entry is still
/// valid. `K` and `S` are the key and state types; both are stored serialized.
///
+/// A stored record is validated at most once per operation (one update):
+/// every later probe in the same operation that holds the same kind, key and
+/// stored state takes the first answer without calling `validate`. A source
+/// that changes after that answer is seen by the next operation.
+///
/// **Construct before any component runs.** A memo entry is validated against
/// the kinds registered at that moment, so a kind constructed inside a
/// component registers too late for the entries that recorded it. A second
@@ -326,12 +333,31 @@ impl DataDepsOutcome {
/// SDK: decode (a kind no longer registered or a stored key or state that no
/// longer deserializes is a logged miss, and no validator runs), then the
/// validators, concurrently; a validator's error propagates.
+///
+/// `verdicts` is the operation's: a record whose identity it holds takes that
+/// verdict and calls no validator, and each validator's answer is recorded
+/// there, so a record is validated once per operation (see
+/// `DataDepVerdicts`).
pub(crate) async fn validate_data_deps(
+ verdicts: &DataDepVerdicts,
records: Vec<DataDepRecord>,
where_: &str,
) -> Result<DataDepsOutcome> {
- let mut validations = Vec::with_capacity(records.len());
+ use futures::future::{Either, TryFutureExt, ready};
+
+ /// A record's answer: the verdict the operation already holds, or what its
+ /// validator decided just now.
+ enum Answer {
+ Known(DataDepVerdict),
+ Decided(MemoStateDecision),
+ }
+
+ let mut answers = Vec::with_capacity(records.len());
for record in &records {
+ if let Some(verdict) = verdicts.get(&record.identity()) {
+ answers.push(Either::Left(ready(Ok(Answer::Known(verdict)))));
+ continue;
+ }
let Some(kind) = registered_kind(&record.kind_fp) else {
tracing::warn!(
"{where_}: memo misses on a data dependency of kind {}, which is no longer registered (renamed or removed); the body re-runs",
@@ -340,7 +366,7 @@ pub(crate) async fn validate_data_deps(
return Ok(DataDepsOutcome::miss(records));
};
match (kind.validate)(&record.key, &record.state) {
- Ok(fut) => validations.push(fut),
+ Ok(fut) => answers.push(Either::Right(fut.map_ok(Answer::Decided))),
Err(err) => {
tracing::warn!(
"{where_}: memo misses on a data dependency of kind {:?} whose stored key or state failed to deserialize ({err}); the body re-runs",
@@ -350,25 +376,27 @@ pub(crate) async fn validate_data_deps(
}
}
}
- let decisions = futures::future::try_join_all(validations).await?;
+ let answers = futures::future::try_join_all(answers).await?;
let mut can_reuse = true;
let mut states_changed = false;
let refreshed = records
.into_iter()
- .zip(decisions)
- .map(|(record, decision)| {
- let (state, memo_valid) = decision.into_parts();
- can_reuse &= memo_valid;
- if state.0 == record.state {
- record
- } else {
- states_changed = true;
- DataDepRecord {
- state_fp: Fingerprint::from_bytes(&state.0),
- state: state.0,
- ..record
+ .zip(answers)
+ .map(|(record, answer)| {
+ let verdict = match answer {
+ Answer::Known(verdict) => verdict,
+ Answer::Decided(decision) => {
+ let (state, memo_valid) = decision.into_parts();
+ let verdict = DataDepVerdict {
+ memo_valid,
+ new_state: (state.0 != record.state).then_some(state.0),
+ };
+ verdicts.record(record.identity(), verdict)
}
- }
+ };
+ can_reuse &= verdict.memo_valid;
+ states_changed |= verdict.new_state.is_some();
+ verdict.apply(record)
})
.collect();
Ok(DataDepsOutcome {
diff --git a/rust/sdk/cocoindex/src/memo.rs b/rust/sdk/cocoindex/src/memo.rs
index fb48d6bd..cb7a642b 100644
--- a/rust/sdk/cocoindex/src/memo.rs
+++ b/rust/sdk/cocoindex/src/memo.rs
@@ -920,9 +920,14 @@ impl<'a> MemoProbe<'a> {
// Data dependencies the entry recorded (`use_data_dep`): validated only
// when the states still allow a reuse.
let data_deps = match guard.cached() {
- Some(cached) if states_valid && !cached.data_deps.is_empty() => {
- Some(validate_data_deps(cached.data_deps.to_vec(), "memoized function").await?)
- }
+ Some(cached) if states_valid && !cached.data_deps.is_empty() => Some(
+ validate_data_deps(
+ comp_ctx.data_dep_verdicts(),
+ cached.data_deps.to_vec(),
+ "memoized function",
+ )
+ .await?,
+ ),
_ => None,
};
diff --git a/rust/sdk/cocoindex/src/profile.rs b/rust/sdk/cocoindex/src/profile.rs
index edb9d33b..6daa201e 100644
--- a/rust/sdk/cocoindex/src/profile.rs
+++ b/rust/sdk/cocoindex/src/profile.rs
@@ -8,7 +8,7 @@ use std::sync::Arc;
use async_trait::async_trait;
use cocoindex_core::engine::component::{ComponentProcessor, ComponentProcessorInfo};
use cocoindex_core::engine::context::{
- ComponentProcessorContext, DataDepRecord, MemoStatesPayload,
+ ComponentProcessorContext, DataDepRecord, DataDepVerdicts, MemoStatesPayload,
};
use cocoindex_core::engine::profile::{DataDepsValidation, EngineProfile, Persist};
use cocoindex_core::engine::target_state::{
@@ -51,6 +51,7 @@ impl EngineProfile for RustProfile {
/// its records, validated through the registered [`crate::DataDep`] kinds.
fn validate_data_deps(
_host_runtime_ctx: &(),
+ verdicts: Arc<DataDepVerdicts>,
path: &StablePath,
records: Vec<DataDepRecord>,
) -> cocoindex_utils::error::Result<
@@ -58,7 +59,7 @@ impl EngineProfile for RustProfile {
> {
let where_ = format!("component {path}");
Ok(async move {
- let outcome = validate_data_deps(records, &where_)
+ let outcome = validate_data_deps(&verdicts, records, &where_)
.await
.map_err(Error::into_core)?;
Ok(DataDepsValidation {
@@ -214,6 +215,7 @@ impl ComponentProcessor<RustProfile> for BoxedProcessor {
let context = Arc::clone(comp_ctx.host_ctx());
let state_inputs = self.state_inputs.clone();
let where_ = format!("component {}", comp_ctx.stable_path());
+ let verdicts = Arc::clone(comp_ctx.data_dep_verdicts());
let initial_context_states = stored_states
.is_none()
.then(|| comp_ctx.collect_context_initial_states());
@@ -238,7 +240,7 @@ impl ComponentProcessor<RustProfile> for BoxedProcessor {
// The component's own data dependencies (`use_data_dep`),
// validated only when the states still allow a reuse.
let data_deps = if can_reuse && !stored_states.data_deps.is_empty() {
- let outcome = validate_data_deps(stored_states.data_deps, &where_)
+ let outcome = validate_data_deps(&verdicts, stored_states.data_deps, &where_)
.await
.map_err(Error::into_core)?;
can_reuse &= outcome.can_reuse;
diff --git a/rust/sdk/cocoindex/tests/memo_deps.rs b/rust/sdk/cocoindex/tests/memo_deps.rs
index 2ac35a96..c0ed30db 100644
--- a/rust/sdk/cocoindex/tests/memo_deps.rs
+++ b/rust/sdk/cocoindex/tests/memo_deps.rs
@@ -562,11 +562,19 @@ fn a_record_reaches_every_enclosing_memoized_function() {
run(&app, "outer:A1");
assert_eq!(collect(T), metrics(&[("validate", 1)]));
+ // The inner's probe takes the verdict the outer's probe got for the same
+ // record in this update: the read is validated once.
write(&a, "A2");
run(&app, "outer:A2");
- let after = collect(T);
- assert_eq!(after["run.outer"], 1);
- assert_eq!(after["run.n"], 1);
+ assert_eq!(
+ collect(T),
+ metrics(&[
+ ("validate", 1),
+ ("validate.digest", 1),
+ ("run.outer", 1),
+ ("run.n", 1)
+ ])
+ );
}
#[cocoindex::function]
@@ -611,15 +619,15 @@ fn an_open_component_is_reused_while_its_reads_are_unchanged() {
assert_eq!(collect(T), metrics(&[("validate", 1)]));
// The read changed: the parent's walk finds the child's record invalid
- // and the parent re-runs; the child's own probe validates once more when
- // it is mounted, misses, and re-runs.
+ // and the parent re-runs; the child's own probe, when it is mounted, takes
+ // that verdict without validating again, misses, and re-runs.
write(&a, "A2");
run(&app, "A2");
assert_eq!(
collect(T),
metrics(&[
- ("validate", 2),
- ("validate.digest", 2),
+ ("validate", 1),
+ ("validate.digest", 1),
("run.parent", 1),
("run.c", 1)
])