Skip to content

API Reference parrot.tools.working_memory.task_memory.recall

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.tools.working_memory.task_memory.recall

View source

Deterministic bounded recall selection (FEAT-538, decision D5).

One recall must restore everything an agent needs to carry on after context loss — goal, constraints, active and ready work, evidence references, unresolved failures, truthful completion sources — inside a token budget, from captured inputs only.

This module is a pure selector. Like the reducer, purity is the contract rather than a preference:

  • No I/O, no clock, no randomness, no tool execution, no LLM call, no data load. Recall never appends an event, so repeated reads cannot change a task's sequence or fill its journal (AC10).
  • Everything it needs is passed in: the projection, a bounded event page, a bounded descriptor page, an availability snapshot, the caller's arguments, and the token counter plus its captured calibration.

Determinism means: identical captured state, availability snapshot, counter identity, calibration and arguments produce identical bytes. It deliberately does not mean that expired content stays available forever at the same task sequence — availability can change with no task event at all (an eviction, an expiry, a worker restart), which is exactly why it is captured as an explicit input and folded into the result.

Selection is by whole units, in the specification's priority order:

  1. identity, goal, active constraints, critical blockers — required
  2. active and ready steps
  3. active decisions and the resume hint
  4. completed required steps and recent calls, unresolved failures first
  5. relevant recent artifact descriptors

Optional units are removed, lowest priority first, until the complete result fits. Serialized JSON strings are never truncated mid-value: a half-written reference is worse than an honestly omitted one, and the truncation account says exactly what was dropped.

Class AvailabilitySnapshot

What was actually reachable at the moment recall ran.

Captured explicitly because availability changes without a task event: an artifact is evicted, an omission expires, a worker restarts. Folding it into the inputs is what lets recall be deterministic for captured inputs while still being honest about what is gone.

Attributes:

Attribute Type Description
artifacts Dict[str, ArtifactAvailability] "artifact_id@version" → availability. A reference absent from the mapping is reported as missing.
omissions Dict[str, Optional[bool]] om_... id → True (present), False (known gone) or None (unknown — a custom omission store with no availability probe). None is reported as unknown, never optimistically as present.
worker_generation Optional[str] Identity of the REPL worker generation whose bindings were checked. A binding from another generation is reported as invalid.
generation int Monotonic marker that changes whenever availability changes with no task event. Part of the cache key.

Method AvailabilitySnapshot.availability_of

Return the captured availability of one reference.

availability_of(ref: str) -> ArtifactAvailability

Parameter Type Default Description
ref str Canonical artifact_id@version.

Returns: ArtifactAvailability — The captured availability, or MISSING when the reference was not in the snapshot. Absence is reported as missing rather than assumed available.

Attribute HEURISTIC_BYTES_PER_TOKEN

Type: int

Class InMemoryRecallCache

Process-local recall cache with a monotonic-clock TTL.

The clock is injectable so expiry can be tested without sleeping — a test that slept would be slow and, worse, flaky under load.

Parameter Type Default Description
clock Callable[[], float] Monotonic time source, in seconds. Required, not defaulted. This module is held to a purity guard that forbids importing a clock anywhere in it — precisely so that hidden time dependencies cannot creep into recall — so the time source is supplied by the caller instead. Production wiring passes time.monotonic; tests pass a controllable fake, which is also how TTL expiry is tested without sleeping.

Method InMemoryRecallCache.get

Return a live entry, dropping it when its TTL has passed.

get(key: str) -> Optional[bytes]

Parameter Type Default Description
key str The cache key.

Returns: Optional[bytes] — The payload, or None when absent or expired.

Method InMemoryRecallCache.set

Store a payload with a TTL.

set(key: str, payload: bytes, ttl_seconds: int) -> None

Parameter Type Default Description
key str The cache key.
payload bytes Serialized recall result.
ttl_seconds int Lifetime. 0 or less stores nothing.

Method InMemoryRecallCache.clear

Drop every entry.

clear() -> None

Attribute MAX_RECALL_TOKENS

Type: int

Attribute MAX_RECENT_CALLS

Type: int

Attribute MIN_RECALL_TOKENS

Type: int

Attribute NEEDS_SELECTION_PAGE

Type: int

Attribute RECALL_ARTIFACT_LIMIT

Type: int

Attribute RECALL_EVENT_WINDOW

Type: int

Attribute RECALL_SCHEMA_VERSION

Type: int

Class RecallCache

A TTL cache for serialized recall results.

Method RecallCache.get

Return the cached payload for key, or None.

get(key: str) -> Optional[bytes]

Parameter Type Default Description
key str

Returns: Optional[bytes]

Method RecallCache.set

Store payload under key for ttl_seconds.

set(key: str, payload: bytes, ttl_seconds: int) -> None

Parameter Type Default Description
key str
payload bytes
ttl_seconds int

Class RecallInputs

Everything recall is allowed to look at.

Bounded by construction: the caller supplies pages, not a whole journal. Recall never scans a full journal, loads a payload, or runs a query of its own.

Attributes:

Attribute Type Description
state TaskState The reduced projection.
as_of_seq int Sequence fence the pages were read at. Every page must describe the same instant.
events Tuple[JournalEvent, ...] A bounded, ascending page of recent journal events.
artifacts Tuple[ArtifactDescriptor, ...] A bounded page of artifact descriptors.
availability AvailabilitySnapshot What was reachable when the pages were read.
open_task_ids Tuple[str, ...] Other open tasks in the scope, for the needs_task_selection answer.

Class RecallReader

Builds bounded recall inputs, caches results, and never loads payloads.

This is the I/O half of recall; :func:select_recall remains a pure function and does the choosing. The split matters: everything that could make recall expensive or non-deterministic lives here, where it is bounded and observable, and the selector cannot reach past what it is handed.

Three properties this class exists to guarantee (AC10):

  • One fence. The projection, the event page and the descriptor page are all read at a single as_of_seq, so they describe one instant rather than three nearby ones.
  • No payload reads. It calls list/load_snapshot/ list_events and the omission probe. It never calls load_payload, never calls OmissionStore.get, and never asks a descriptor to summarize itself.
  • Bounded everything. Page sizes are constants, not caller input.
Parameter Type Default Description
store Any The task-memory store.
artifacts Any The artifact store, read for descriptors only.
config Optional[Any] None Capacity and TTL configuration.
cache Optional[RecallCache] None Optional recall cache.
association Optional[Any] None Optional association store, used to resolve an omitted task id and to build the cache key.
omission_store Optional[Any] None Optional omission store to probe.
counter Optional[TokenCounterLike] None Token counter; defaults to the compaction default.

Method RecallReader.omission_key

Compose the omission-store scoping key for a task scope.

Mirrors ConversationMemory.omission_key exactly — that method documents the composition as "{chatbot_id}:{user_id}:{session_id}", so this is a restatement rather than a guess.

omission_key(scope: Any) -> str

Parameter Type Default Description
scope Any The trusted scope.

Returns: str — The omission-store session key.

Method RecallReader.build_inputs

Read one consistent, bounded set of recall inputs.

Every page is fenced at the projection's as_of_seq, so the projection, the journal page and the descriptor page describe one instant rather than three nearby ones.

build_inputs(scope: Any, task_id: str, *, worker_generation: Optional[str] = None) -> Optional[RecallInputs]

Parameter Type Default Description
scope Any The trusted scope.
task_id str The task to read.
worker_generation Optional[str] None Identity of the live REPL worker generation, so stale bindings can be labelled.

Returns: Optional[RecallInputs] — The inputs, or None when the task does not exist in this scope.

Method RecallReader.recall

Produce one bounded recall, serving a cached result when valid.

recall(scope: Any, task_id: Optional[str] = None, *, max_tokens: Optional[int] = None, recent_calls_limit: Optional[int] = None, calibration: float = 1.0, worker_generation: Optional[str] = None, use_cache: bool = True) -> RecallResult

Parameter Type Default Description
scope Any The trusted scope.
task_id Optional[str] None The task to recall. When None, resolved from the authoritative selected association — never by similarity.
max_tokens Optional[int] None Budget; defaults to the configured value.
recent_calls_limit Optional[int] None Recent-call count; defaults to configured.
calibration float 1.0 Captured compaction calibration.
worker_generation Optional[str] None Live REPL worker generation.
use_cache bool True Whether to consult and populate the cache.

Returns: RecallResult — The recall result. needs_task_selection carries a bounded list of open tasks to choose from.

Class RecallResult

The result of one recall.

Attributes:

Attribute Type Description
status RecallStatus Whether a snapshot was produced, and if not, why.
snapshot Dict[str, Any] The canonical snapshot payload. Empty on failure.
payload_bytes int Canonical serialized bytes of snapshot.
estimated_tokens int Measured cost of payload_bytes.
tokens_estimated bool True when the heuristic counter was used — the number is an estimate, not a guaranteed upper bound on a provider's tokenization.
required_min_tokens Optional[int] On budget_too_small, the measured cost of the required units alone, so the caller knows what budget would actually work.
truncation TruncationAccount What was omitted.
cache_key_parts Tuple[Tuple[str, str], ...] The inputs a cache key must include, so a caller cannot accidentally cache on too little.

Method RecallResult.to_bytes

Return the canonical serialization of the snapshot.

to_bytes() -> bytes

Returns: bytes — Deterministic sorted-key UTF-8 JSON.

Class RecallStatus

Outcome of a recall attempt.

Class RedisRecallCache

Recall cache over an existing async Redis client.

Never opens its own connection: it borrows the one the conversation memory already owns, exactly as :class:RedisOmissionStore does.

Parameter Type Default Description
redis_client Any An already-constructed async Redis client.

Method RedisRecallCache.get

Return the cached payload, or None.

get(key: str) -> Optional[bytes]

Parameter Type Default Description
key str The cache key.

Returns: Optional[bytes] — The payload as bytes, or None.

Method RedisRecallCache.set

Store a payload with a Redis TTL.

set(key: str, payload: bytes, ttl_seconds: int) -> None

Parameter Type Default Description
key str The cache key.
payload bytes Serialized recall result.
ttl_seconds int Lifetime in seconds. 0 or less stores nothing, rather than storing something that never expires.

Class TokenCounterLike

The compaction token counter's shape, restated to stay leaf-safe.

Attributes:

Attribute Type Description
name str

Method TokenCounterLike.count

Return the token count for text.

count(text: str) -> int

Parameter Type Default Description
text str

Returns: int

Class TruncationAccount

What recall left out, counted rather than silently dropped.

Attributes:

Attribute Type Description
steps_omitted int Active/ready steps not included.
completed_steps_omitted int Completed required steps not included.
decisions_omitted int Active decisions not included.
calls_omitted int Recent calls not included.
artifacts_omitted int Artifact descriptors not included.
unresolved_omitted int Unresolved outcomes not included. Should stay 0 except under a genuinely tiny budget — unresolved failures outrank every other optional unit.
any_omitted bool Whether anything at all was left out.

Function build_cache_key_parts

Return every input a recall cache key must cover.

Extracted so the reader can compute the key before running a selection — a cache that could only be keyed after doing the work it is meant to avoid would be useless — while keeping exactly one definition of what the key contains. A part omitted here is a part a stale entry could be served across.

availability_generation is the subtle one: it moves when an artifact is evicted, an omission expires or a worker restarts, none of which appends a task event. Without it, "deterministic" would decay into "expired content stays available forever at the same task sequence".

build_cache_key_parts(*, scope_key: str, task_id: str, as_of_seq: int, availability_generation: int, tokenizer: str, calibration: float, max_tokens: int, recent_calls_limit: int) -> Tuple[Tuple[str, str], ...]

Parameter Type Default Description
scope_key str Collision-safe encoding of the trusted scope.
task_id str The task recalled.
as_of_seq int Journal fence the pages were read at.
availability_generation int Availability marker at read time.
tokenizer str Token counter identity.
calibration float Captured compaction calibration.
max_tokens int Requested budget.
recent_calls_limit int Requested recent-call count.

Returns: Tuple[Tuple[str, str], ...] — Ordered (name, value) pairs.

Function cache_digest

Digest cache-key parts into one opaque, collision-safe token.

cache_digest(parts: Sequence[Tuple[str, str]]) -> str

Parameter Type Default Description
parts Sequence[Tuple[str, str]] The parts from :func:build_cache_key_parts.

Returns: str — A hex digest. Derived from the canonical serialization of the parts, so two different part sets cannot collide by concatenation (the failure a naive ":".join invites when a value contains the separator).

Function collect_omission_ids

Return the omission ids referenced by a bounded page of events.

Scans the serialized payloads rather than reaching for a specific field, because omission references can appear anywhere redaction put one. The scan is bounded twice over: the event page is bounded, and each payload is capped at 8 KiB.

collect_omission_ids(events: Sequence[JournalEvent]) -> Tuple[str, ...]

Parameter Type Default Description
events Sequence[JournalEvent] The bounded event page.

Returns: Tuple[str, ...] — The distinct ids, in first-seen order so the result is stable.

Function needs_task_selection

Whether the caller must choose a task before recall can run.

An omitted task id resolves only from the authoritative selected association. With several open tasks and no selection the answer is a bounded list to choose from — never a similarity guess.

needs_task_selection(open_task_ids: Sequence[str], selected: Optional[str]) -> bool

Parameter Type Default Description
open_task_ids Sequence[str] Open tasks in the scope.
selected Optional[str] The selected task id, if any.

Returns: bool — True when selection is required.

Function select_recall

Select a bounded, deterministic recall snapshot.

select_recall(inputs: RecallInputs, *, counter: TokenCounterLike, calibration: float = 1.0, max_tokens: int = 2500, recent_calls_limit: int = 8) -> RecallResult

Parameter Type Default Description
inputs RecallInputs Everything recall is permitted to see. Bounded by the caller: recall never scans a whole journal.
counter TokenCounterLike The token counter, whose name participates in the cache key.
calibration float 1.0 The captured compaction calibration factor.
max_tokens int 2500 Requested budget, clamped to [MIN_RECALL_TOKENS, MAX_RECALL_TOKENS].
recent_calls_limit int 8 Requested recent-call count, clamped to [0, MAX_RECENT_CALLS].

Returns: RecallResult — class:RecallResult. status is budget_too_small when even the required units do not fit, carrying the measured required_min_tokens so the caller learns what budget works. needs_task_selection when no task is selected and several are open — never resolved by similarity.

Raises:

  • ValueError — If max_tokens or recent_calls_limit is outside its permitted range. A silently clamped nonsensical request would hide a caller bug.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally