Skip to content

API Reference parrot.tools.working_memory.task_memory.retention

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

parrot.tools.working_memory.task_memory.retention

View source

Deterministic retention decisions and in-memory sweeping (FEAT-538).

Retention is the part of task memory most likely to destroy something a user still needed, so every rule here is explicit, configured, and decided by a pure function over captured inputs before any effect runs.

The module separates three things that are usually tangled together:

  1. Selection — :func:select_due_tasks and :func:select_due_artifacts are pure. Given a clock reading and a set of immutable views, they return the actions that are due. No I/O, no randomness, no wall clock of their own. Tests drive time by injection and never sleep.
  2. Ordering — :meth:RetentionSweeper.run_once appends each action's intent event before doing the destructive work, so the intent is auditable at the moment the work is attempted rather than after it succeeded.
  3. Effects — the genuinely destructive capabilities (journal purge, archive, blob sweep) are narrow :class:Protocol s the host wires in. Delivery A ships the in-memory artifact sweeping and none of the durable ones; Delivery B's cleanup task supplies those.

.. warning::

The audit trail does not survive terminal deletion. Deleting a terminal task necessarily removes the journal that recorded the intent to delete it. When archive_uri is configured the archive includes that final retention event, so the record moves rather than disappears. Without an archive, deletion is deliberately irreversible and leaves only bounded operational logs. This module does not claim permanent in-journal audit after deleting the journal, because that claim would be false.

.. warning::

Delivery A cannot promise retained bytes. When the byte budget forces out evidence that a task still references, the store records an invalidation and keeps a metadata tombstone. No eviction may silently remove evidence while leaving a step labeled valid.

Scheduling is a host concern. :meth:RetentionSweeper.run_once is a plain idempotent coroutine: run it from an existing qworker deployment, or use :class:PeriodicRetention for a single-process deployment with explicit startup and shutdown. No queue dependency is introduced.

Attribute ABANDONED_CANCEL_REASON

Type: str

Attribute ARCHIVE_VERIFY_FAILED

Type: str

Class ArchiveVerificationError

A written archive could not be read back and confirmed complete.

Raised only by :class:JsonlArchiveWriter internals; the sweeper turns it into a deferral. It exists so "the archive is bad" is distinguishable from "the write raised", because the two have different causes and the same consequence: do not delete.

Class ArchiveWriter

Writes a terminal task's journal somewhere durable, and verifies it.

The verification step is not optional. Deletion proceeds only after :meth:verify confirms the archive is readable, because an unverified archive plus a deleted journal is indistinguishable from data loss.

Method ArchiveWriter.write

Write a task's journal as JSONL and return its location.

write(uri: str, task_id: str, events: Sequence[JournalEvent]) -> str

Parameter Type Default Description
uri str Configured archive destination.
task_id str The task being archived.
events Sequence[JournalEvent] Its complete journal, including the final retention event announcing the deletion.

Returns: str — A reference to the written archive.

Method ArchiveWriter.verify

Confirm a written archive is readable and complete.

verify(reference: str, expected_events: int) -> bool

Parameter Type Default Description
reference str What :meth:write returned.
expected_events int How many events it should contain.

Returns: bool — True only when the archive is verified.

Class ArtifactRetentionView

Everything the artifact rules are allowed to look at.

Parameter Type Default Description
scope TaskScope
ref EvidenceRef
task_id Optional[str]
created_at datetime
is_current bool
pinned_by Tuple[str, ...] ()
retained_bytes int 0
owner_terminal_at Optional[datetime] None

Fields:

Field Type Default Description
scope TaskScope Owning scope.
ref EvidenceRef The exact version.
task_id Optional[str] The task that produced it.
created_at datetime When the version was registered.
is_current bool Whether an alias still points at it.
pinned_by Tuple[str, ...] () Every task referencing it as evidence. Any pin defers deletion, including a task other than the producer.
retained_bytes int 0 Bytes still held for it.
owner_terminal_at Optional[datetime] None When the producing task went terminal, if it has. Non-terminal evidence is protected regardless of age.

Class BlobRetentionView

Everything the orphan-blob rule is allowed to look at.

Parameter Type Default Description
scope TaskScope
storage_ref str
written_at datetime
has_live_index bool False
has_publish_lease bool False
has_archive_reference bool False

Fields:

Field Type Default Description
scope TaskScope Owning scope.
storage_ref str Backend reference to the bytes.
written_at datetime When the blob was written.
has_live_index bool False Whether an artifact row still references it.
has_publish_lease bool False Whether a publish is still in flight.
has_archive_reference bool False Whether an archive references it.

Attributes:

Attribute Type Description
is_orphan bool Whether nothing at all references this blob.

Class BlobSweeper

Removes orphan blobs from durable storage.

Method BlobSweeper.list_orphans

Return candidate orphan blobs for a scope.

list_orphans(scope: TaskScope) -> Sequence[BlobRetentionView]

Parameter Type Default Description
scope TaskScope Trusted runtime scope.

Returns: Sequence[BlobRetentionView] — The candidates, with their reference flags already resolved.

Method BlobSweeper.sweep

Delete one orphan blob.

sweep(scope: TaskScope, storage_ref: str) -> bool

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
storage_ref str The blob to delete.

Returns: bool — True when bytes were removed.

Class DueAction

One retention action that has come due.

Parameter Type Default Description
policy str
action str
scope TaskScope
task_id Optional[str] None
due_at Optional[datetime] None
target_refs Tuple[EvidenceRef, ...] ()
storage_ref Optional[str] None
reason Optional[str] None
archive_uri Optional[str] None

Fields:

Field Type Default Description
policy str Which rule fired.
action str What it intends to do.
scope TaskScope Owning scope.
task_id Optional[str] None The task, when the action is task-scoped.
due_at Optional[datetime] None When the action became due.
target_refs Tuple[EvidenceRef, ...] () Artifact versions the action targets.
storage_ref Optional[str] None The blob the action targets, when it targets one.
reason Optional[str] None Human-readable explanation, stamped on the transition.
archive_uri Optional[str] None Where the archive will be written, when configured.

Method DueAction.to_payload

Build the journal payload announcing this intent.

to_payload() -> RetentionPayload

Returns: RetentionPayload — class:RetentionPayload for a retention_scheduled event.

Class HotKeyCleaner

Removes a purged task's Redis hot keys.

Terminal deletion removes the durable rows; the lease, recall and context keys for that task would otherwise linger until their TTLs expire. They are all TTL-bounded already, so this is tidiness rather than correctness — which is exactly why it never raises: a failure here must not turn a completed purge into a reported error.

Parameter Type Default Description
association Any A TaskAssociationStore, which owns the key families and their naming.

Method HotKeyCleaner.forget_task

Delete the hot keys belonging to one task.

forget_task(scope: TaskScope, task_id: str) -> int

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
task_id str The purged task.

Returns: int — How many keys were removed. 0 on any failure.

Attribute INACTIVITY_PAUSE_REASON

Type: str

Class JournalPressure

How close a task's journal is to its configured ceilings.

Parameter Type Default Description
event_count int
soft_exceeded bool
foreground_refused bool
reserved_exhausted bool

Fields:

Field Type Default Description
event_count int Events currently in the journal.
soft_exceeded bool Past journal_soft_limit. Recall must stop retaining optional recent-call material — it does not stop recalling, and nothing is discarded.
foreground_refused bool Past journal_hard_limit. New ordinary work is refused.
reserved_exhausted bool Past the hard limit plus the reserved headroom. Even terminal, recovery and retention events can no longer be appended.

Class JournalPurge

Removes a terminal task's journal and projection.

Delivery A supplies no implementation: without one, terminal expiry is reported as deferred rather than silently skipped.

Method JournalPurge.purge_task

Delete one task's journal and projection.

purge_task(scope: TaskScope, task_id: str) -> bool

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
task_id str The task to remove.

Returns: bool — True when something was removed. Idempotent: a repeated purge of an already-deleted task returns False rather than failing.

Class JsonlArchiveWriter

Writes a terminal task's journal as JSONL and verifies it.

The format is one canonical JSON object per line, in sequence order, which is append-friendly, streamable and trivially countable — the last property is what makes verification cheap enough to be mandatory rather than aspirational.

Verification re-reads the object. It is not enough to trust the write call's return value: the whole point is to catch a storage layer that accepted bytes it did not durably keep. :meth:verify downloads what was written, parses every line, and checks the count against what was archived. Only then may the source be deleted.

Re-archiving is idempotent. A retry after a crash between write and delete finds byte-identical content already present and accepts it, rather than writing a second copy under a new name. That is what stops "crash, retry" producing duplicate archives.

Parameter Type Default Description
blobs Any The blob store, reused for its verified file-manager access rather than duplicating that logic here.
scope TaskScope Trusted runtime scope, which fixes the archive sub-tree.
segment str '_archive' Archive path segment.

Method JsonlArchiveWriter.archive_key

Return the deterministic archive key for one task.

Deterministic on purpose: a retry must land on the same key so the second attempt is recognisably the same archive rather than a duplicate.

archive_key(task_id: str) -> str

Parameter Type Default Description
task_id str The task being archived.

Returns: str — The storage key.

Method JsonlArchiveWriter.encode

Serialize a journal as canonical JSONL.

encode(events: Sequence[JournalEvent]) -> bytes

Parameter Type Default Description
events Sequence[JournalEvent] The events, in sequence order.

Returns: bytes — The encoded bytes, one event per line.

Method JsonlArchiveWriter.write

Write a task's journal as JSONL and return its location.

write(uri: str, task_id: str, events: Sequence[JournalEvent]) -> str

Parameter Type Default Description
uri str Configured archive destination. Recorded in the intent event; the concrete location comes from the blob store's own scope sub-tree, so an archive can never be written outside it.
task_id str The task being archived.
events Sequence[JournalEvent] Its complete journal, INCLUDING the final retention event announcing the deletion.

Returns: str — The storage key written.

Raises:

  • ArchiveVerificationError — If the write is refused. No reference is returned, so the caller cannot proceed to delete.

Method JsonlArchiveWriter.verify

Confirm a written archive is readable and complete.

verify(reference: str, expected_events: int) -> bool

Parameter Type Default Description
reference str What :meth:write returned.
expected_events int How many events it should contain.

Returns: bool — True only when the object reads back, every line parses, and the count matches. Any doubt returns False, which the sweeper treats as "do not delete".

Class PeriodicRetention

Runs a sweeper on an interval, for single-process deployments.

A host with a qworker deployment should schedule :meth:RetentionSweeper.run_once there instead. This exists so a single-process deployment does not have to invent one, and it introduces no queue dependency — it is an asyncio task with explicit startup and shutdown.

Parameter Type Default Description
sweeper RetentionSweeper The sweeper to run.
scopes Callable[[], Sequence[TaskScope]] A callable returning the scopes to sweep each cycle, so the set can change without restarting the loop.
interval_seconds float 3600.0 Seconds between sweeps.

Attributes:

Attribute Type Description
is_running bool Whether the loop is active.

Method PeriodicRetention.start

Start the loop. Idempotent.

start() -> None

Method PeriodicRetention.stop

Stop the loop and wait for it to finish. Idempotent.

stop() -> None

Class RetentionAction

What a due action intends to do.

Class RetentionPolicy

Which rule in the specification's retention table fired.

Class RetentionSweeper

Applies due retention actions, intent first.

Idempotent by construction rather than by bookkeeping: every action changes the state that made it due, so a second :meth:run_once over an unchanged world selects nothing. The one deliberate exception is a failed archive, which is retried — "failed archive/deletion retries are idempotent" is a requirement, not an accident.

Parameter Type Default Description
store TaskMemoryStore The task store to read and append to.
service Optional[Any] None Optional command service used for lifecycle transitions, so pauses and cancellations go through exactly the same event rules as an agent's own. Without it, those transitions are reported as deferred rather than performed by a second, divergent code path.
artifacts Optional[Any] None Optional artifact store, for in-memory version expiry.
config Optional[TaskMemoryConfig] None Thresholds. Defaults to :class:TaskMemoryConfig.
clock Callable[[], datetime] utc_now Injected clock. Tests pass a controllable one; nothing here ever sleeps to advance time.
archive Optional[ArchiveWriter] None Optional archive writer. Required before a terminal journal may be deleted when archive_uri is configured.
purge Optional[JournalPurge] None Optional journal purge capability.
blobs Optional[BlobSweeper] None Optional orphan blob sweeper.
hot_keys Optional[Any] None Optional :class:HotKeyCleaner, to drop a purged task's Redis keys instead of waiting out their TTLs.

Method RetentionSweeper.run_once

Apply every due retention action, once.

Idempotent: over an unchanged world a second call selects nothing and the report is a no-op. Every action appends its intent event before the destructive work.

run_once(scopes: Sequence[TaskScope]) -> SweepReport

Parameter Type Default Description
scopes Sequence[TaskScope] The scopes to sweep. Scope is always explicit — there is no "sweep everything" that could cross a boundary.

Returns: SweepReport — class:SweepReport describing what happened, including what was deliberately deferred.

Class SweepReport

What one :meth:RetentionSweeper.run_once did.

Parameter Type Default Description
paused List[str] list()
cancelled List[str] list()
deleted List[str] list()
archived List[str] list()
expired_versions List[EvidenceRef] list()
swept_blobs List[str] list()
deferred List[Tuple[str, str]] list()
invalidations List[Any] list()
errors List[Tuple[str, str]] list()
audit_destroyed List[Tuple[str, Optional[str]]] list()

Fields:

Field Type Default Description
paused List[str] field(default_factory=list) Tasks paused for inactivity.
cancelled List[str] field(default_factory=list) Tasks cancelled for abandonment.
deleted List[str] field(default_factory=list) Tasks whose journal and projection were removed.
archived List[str] field(default_factory=list) Tasks archived before deletion.
expired_versions List[EvidenceRef] field(default_factory=list) Artifact versions whose bytes were released.
swept_blobs List[str] field(default_factory=list) Orphan blobs removed.
deferred List[Tuple[str, str]] field(default_factory=list) Actions that came due but were held back, with the reason — a cross-task pin, a failed archive, a missing capability.
invalidations List[Any] field(default_factory=list) Receipts drained from the artifact store, which the caller turns into artifact_invalidated events.
errors List[Tuple[str, str]] field(default_factory=list) Actions that failed, with their cause.
audit_destroyed List[Tuple[str, Optional[str]]] field(default_factory=list) One (task_id, archive_reference) pair per task whose journal was deleted. The second element is None when no archive was configured, which is the honest record that the audit trail for that task is gone rather than relocated. Callers that need a permanent record must read this and write it somewhere outside the journal — the journal that recorded the intent no longer exists.

Attributes:

Attribute Type Description
action_count int How many destructive actions actually completed.
is_noop bool Whether the sweep changed nothing at all.

Class TaskRetentionView

Everything the task rules are allowed to look at.

Parameter Type Default Description
scope TaskScope
task_id str
status TaskStatus
updated_at datetime
terminal_at Optional[datetime] None
inactivity_paused_at Optional[datetime] None
last_activity_at Optional[datetime] None
event_count int 0

Fields:

Field Type Default Description
scope TaskScope Owning scope.
task_id str The task.
status TaskStatus Its lifecycle status.
updated_at datetime When it last changed.
terminal_at Optional[datetime] None When it reached a terminal status, if it has.
inactivity_paused_at Optional[datetime] None When the sweeper paused it for inactivity, if it did.
last_activity_at Optional[datetime] None When the task last did real work. Distinct from updated_at on purpose — see :func:select_due_tasks.
event_count int 0 Journal size, for the capacity rules.

Attributes:

Attribute Type Description
activity_anchor datetime The instant the inactivity clock is measured from.

Function journal_pressure

Classify a journal's size against the configured ceilings.

History is never silently discarded: passing a ceiling refuses new work rather than trimming old events.

journal_pressure(event_count: int, config: TaskMemoryConfig) -> JournalPressure

Parameter Type Default Description
event_count int Events currently in the journal.
config TaskMemoryConfig The configuration supplying the ceilings.

Returns: JournalPressure — class:JournalPressure classification.

Function select_due_artifacts

Select the artifact versions whose retained bytes may be released.

Pure. Three protections, each of which must hold independently:

  • Non-terminal evidence is protected. A version whose producing task is still live is never expired by age, however old.
  • Any pin defers deletion, including a pin held by a task other than the producer. Cross-task evidence references are exactly the case a naive "is the owner done?" check gets wrong.
  • Current versions are protected from the stale-version rule. Only non-current versions expire on the 24-hour clock; a current version of a terminal task follows the 90-day terminal rule instead.

select_due_artifacts(now: datetime, views: Sequence[ArtifactRetentionView], config: TaskMemoryConfig) -> Tuple[DueAction, ...]

Parameter Type Default Description
now datetime The current instant, injected.
views Sequence[ArtifactRetentionView] Immutable views of the candidate versions.
config TaskMemoryConfig The configuration supplying the thresholds.

Returns: Tuple[DueAction, ...] — The due actions, ordered by reference for stability.

Function select_due_blobs

Select orphan blobs old enough to sweep.

Pure. A blob is swept only when nothing references it — no live index row, no pending publish lease, no archive — and only after the grace period. Orphans are expected after a crash; a blob that is merely mid-publish is not an orphan, and sweeping it would delete bytes a reference is about to point at.

select_due_blobs(now: datetime, views: Sequence[BlobRetentionView], config: TaskMemoryConfig) -> Tuple[DueAction, ...]

Parameter Type Default Description
now datetime The current instant, injected.
views Sequence[BlobRetentionView] Immutable views of the candidate blobs.
config TaskMemoryConfig The configuration supplying the grace period.

Returns: Tuple[DueAction, ...] — The due actions, ordered by storage reference.

Function select_due_tasks

Select the task-level retention actions that are due.

Pure: no clock of its own, no I/O, no randomness. The same inputs always yield the same actions, which is what makes the sweeper testable at a boundary rather than approximately.

The three anchors are deliberately different instants, and confusing them is the classic way retention goes wrong:

  • inactivity is measured from activity_anchor — the last time the task did real work;
  • abandonment is measured from inactivity_paused_at — the sweeper's own pause, not from updated_at. Using updated_at would be a bug that hides itself: the sweeper's own retention_scheduled intent event bumps updated_at, so the sweeper would keep resetting the very clock it was measuring and the task would never be cancelled;
  • terminal expiry is measured from terminal_at.

select_due_tasks(now: datetime, views: Sequence[TaskRetentionView], config: TaskMemoryConfig) -> Tuple[DueAction, ...]

Parameter Type Default Description
now datetime The current instant, injected.
views Sequence[TaskRetentionView] Immutable views of the candidate tasks.
config TaskMemoryConfig The configuration supplying every threshold.

Returns: Tuple[DueAction, ...] — The due actions, in a stable order (by task id within policy).

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