Search and contents

Order-Narrative Result Caching: fingerprint-keyed, not identity-keyed

OrderNarrativeCache in engine/order_narrative_cache.py caches OrderNarrativeTask.narrate() from engine/order_narrative.py. A repeat call over an unchanged order or genealogy reuses the prior result instead of paying for another inference call.

The cache is keyed by a fingerprint of the content, not by order_id or call count. A cache hit still writes an Activity Log entry, distinguishable from a real inference call (see "Cache-hit logging" below).

Scope: OrderNarrativeTask.narrate() only

This cache never backs TimeRangedActivityNarrativeTask.query() in engine/time_ranged_activity_narrative.py. That is a deliberate scope boundary, not an oversight.

That Task's own docs (docs/operations/time-ranged-activity-narrative.md) already state that every call is a fresh, caller-scoped window, with no "since last run" state to track. Two arbitrary caller-supplied date ranges are rarely identical from call to call. A content-fingerprint cache there would add real complexity for a near-zero hit rate, and would contradict a design principle that Task already states for itself.

1. Build the cache alongside the Task

from engine.order_narrative_cache import OrderNarrativeCache
from engine.order_narrative import OrderNarrativeTask

cache = OrderNarrativeCache()
cache.ensure_schema()

task = OrderNarrativeTask(
    inference_client,
    narrative_prompt,
    activity_log,
    "MES",
    node_instance_id,
    cache=cache,
)

cache=None (the default) disables caching entirely. Every call then runs inference, or the Inference Operating Mode fallback.

2. What gets fingerprinted

engine.order_narrative._content_fingerprint hashes two things together:

  • the exact serialized payload that _serialize_trail and _serialize_genealogy build, which is the JSON _draft actually sends the model, not the raw OrderTrail or Genealogy dataclass; and
  • the name and version of the narrative prompt (prompt_name, prompt_version).

Two calls fingerprint identically only when every field that reaches the model is identical (the record's own state, and every entry) and the same prompt wrote the text. A genuinely new Activity Log entry, any change to the record itself (for example a Reconciliation update), or a revised prompt always changes the fingerprint and forces a fresh draft. It never produces a stale hit.

A prompt revision therefore needs no flush, provided its version is bumped when its wording changes. Moving the prompt from version A to version B misses the cache once per order and drafts under B. Moving back to A is served again from the entries A wrote.

The key holds the name and version, never the wording. A prompt edited without a version bump has the same key, so the cache keeps serving prose written under the old wording, and the Activity Log entry for such a hit names a version that did not write that text. Bump the version with every wording change. If one was missed, cache.clear() is the remedy.

What the fingerprint deliberately does not cover: a configured-model swap. It touches neither the assembled trail's content nor the prompt's identity, so the fingerprint alone would keep matching and serving pre-change prose. See "Flushing" below.

3. Cache-hit logging

The entry for a run where a model wrote the text, and the entry for a cache hit, both carry prompt_name and prompt_version in their reference ids beside order_id. On a hit they name the prompt in the cache key, which wrote the cached text. The Inference Operating Mode fallback is written by code, not a prompt, so its entry names none.

A cache hit still writes exactly one ActivityLogEntry, the same as a real draft, so narrate()'s "exactly one entry per run" contract is unchanged. Its outcome is "narrated_cached" rather than "narrated".

The reason is that "narrated" is deliberately mechanism-agnostic: it doesn't claim a model ran, even for the Inference Operating Mode fallback. A cache hit does no work at all this time, which is a different kind of thing worth being able to tell apart in the record. "narrated_cached" keeps the chronology-growth property that a repeat narrate() call on an unchanged order already has (it always adds a row, because Kindred logs its own actions), while staying honest about which calls actually ran inference.

The Inference Operating Mode fallback (inference_enabled=False) never reads or writes the cache at all, even when one is configured. It is already free, so caching it buys nothing, and it always logs "narrated" as before.

4. cache_policy: a caller-supplied predicate, not a config rule

task = OrderNarrativeTask(
    inference_client,
    narrative_prompt,
    activity_log,
    "MES",
    node_instance_id,
    cache=cache,
    cache_policy=lambda subject: subject.record.status != IdentityStatus.PENDING,
)

cache_policy is only consulted when cache is not None, and defaults to "always eligible".

It mirrors the shape of run_plan's merge parameter (see merging-paginated-call-results.md): an optional callback, where omitting it means the default. This is preferred to a second, schema-driven rule mechanism for "when should this be cached".

No rule is wired in. narrate()'s subject is always one order's OrderTrail or Genealogy, never a time-ranged window. The one concrete exclusion, history and time-based queries, is therefore the hard scope boundary above, not a runtime predicate.

Flushing

Two methods handle the staleness the fingerprint can't see on its own: a model swap, or a cached narrative that is simply wrong.

  • cache.invalidate_order(order_id) clears every cached entry for one order. Use it for a manual correction (a bad cached narrative) without disturbing every other order's results.
  • cache.clear() clears the whole cache. Use it after a configured-model change, since the model is not part of the fingerprint, or after a prompt edit that was not given a new version. A prompt revision with a new version does not need it.

Neither is wired to a CLI verb. Call them directly. This is the same "documented method, not a bespoke admin tool" shape that TriggerQueue in engine/trigger_queue.py and EmbeddingStore in engine/embedding_store.py use for their own maintenance operations.

Pitfalls

  • A cache hit and a fresh draft return identical text by construction, but only a fresh draft's chronology can include an entry logged by the fresh draft itself. Narrating an order, then narrating it again to show the first narration logged as a chronology entry, only works uncached, or on the first (cache-populating) call. A cache hit replays the exact text from when it was cached, which did not yet include that entry.
  • Two callers racing to cache the same fingerprint is a benign no-op, not a race condition to guard against. OrderNarrativeCache.put uses ON CONFLICT (fingerprint) DO NOTHING. The fingerprint is a hash of the input, so two callers computing it for the same input are, by construction, drafting from byte-identical data. Whichever write lands first wins, and the second is redundant, not wrong.
  • Changing the configured model does not itself invalidate anything. Follow it with cache.clear() (see "Flushing" above), or stale pre-change narratives keep being served for any order whose trail content hasn't otherwise changed. Revising the narrative prompt asset does invalidate, because the prompt's name and version are in the key.
  • The table has no TTL, row cap or automatic eviction, so it grows without bound.
    • Every new order, every genuinely new content fingerprint for an order already seen, and every order's first narration under a new prompt version adds a row. The row stays until an operator calls invalidate_order or clear.
    • The rows a superseded prompt version wrote are never served again unless the prompt returns to that version. A clear() after a prompt revision therefore reclaims space, and is not needed for correctness.
    • No periodic maintenance runs, in this codebase or wired into engine/node_main.py. This matches every other small store here (TriggerQueue doesn't prune resolved rows either). A long-running, high-order-volume site needs an operator-run periodic clear(), since no pruning mechanism exists.
  • A node with Inference Operating Mode disabled (inference_enabled=False) never constructs an OrderNarrativeCache at all. engine/node_main.py only builds and ensure_schema()s one when inference_is_enabled(config) is true, since the disabled fallback never reads or writes it. order_narrative_task.narrate() still works identically either way, but there is no cache table to inspect or flush on such a node.

Release: v0.11.0