Skip to content

API Reference parrot.tools.working_memory.task_memory.store.postgres

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

parrot.tools.working_memory.task_memory.store.postgres

View source

PostgreSQL backing for durable task memory (FEAT-538, Delivery B).

This module owns three things, and deliberately not a fourth:

  1. The migration — reading, parsing and explicitly applying migrations/001_task_memory.sql, plus verifying that a database has the shape the code expects before anything touches it.

  2. The connection pool lifecycle — created lazily, so importing this module (or running the in-memory backend) never pays for asyncpg.

  3. The shared transaction coordinator — one connection that the task store and the artifact store both enlist in, because durable artifact publication must commit the alias/version index, the evidence rows and the artifact_registered journal event together. Two unrelated pool transactions would let a crash between them publish a storage reference whose bytes or whose journal entry never existed.

  4. The durable journal and reducer projections — the append protocol below, which must be behaviourally identical to :class:~.memory.InMemoryTaskMemoryStore (AC2). Where the two could differ, this module follows the in-memory store's decisions rather than inventing its own, and the shared conformance suite is run against both.

  5. The durable artifact store — :class:PostgresArtifactStore, which owns aliases, versions and evidence pins. It lives here rather than in its own module precisely because it must share this module's pool and transaction coordinator: an artifact's index rows, its evidence rows and its artifact_registered journal event have to commit on ONE connection or not at all.

The append protocol (spec §2 Persistence and Recovery) is one transaction, in this order:

  1. INSERT ... ON CONFLICT DO NOTHING / SELECT ... FOR UPDATE the task row. The row lock is what serializes appends to the same task while letting different tasks proceed concurrently — PostgreSQL does the serialization the in-memory store gets from a per-task asyncio.Lock.
  2. Verify scope.
  3. Classify by event_id — before the revision check, so a caller retrying a batch that in fact committed gets a no-op rather than a conflict it cannot resolve.
  4. Check expected_revision.
  5. Check capacity.
  6. Reduce into a local variable, allocating contiguous sequences.
  7. Insert the journal rows, update the projection, and commit.

Steps 2–6 write nothing, so "a rejected command changes nothing" holds both by construction and, for anything that escapes it, by the transaction rolling back.

.. warning::

asyncpg is imported lazily, inside the functions that need a connection. Importing it at module load would mean a deployment without the PostgreSQL extra could not even import the task-memory package, and the in-memory backend would pay for a driver it never uses. There is a test asserting this.

Attribute MIGRATION_NAME

Type: str

Attribute MIGRATION_VERSION

Type: int

Class PostgresArtifactStore

Durable aliases, versions and evidence pins on PostgreSQL (Delivery B).

The catalog backend of decision D1, made durable. It satisfies :class:~parrot.interfaces.artifact_store.ArtifactStore and must be behaviourally identical to :class:~..artifacts.InMemoryArtifactStore (AC2) — where the two could differ, this class follows the in-memory store's decisions rather than inventing its own, and the shared conformance suite runs against both.

The publish order is the guarantee (spec §2 Persistence and Recovery)::

write the immutable blob
  -> verify readability and checksum
    -> ATOMICALLY commit the alias/version index, the evidence
       rows and the `artifact_registered` journal event, on ONE
       connection

A crash between the blob write and the commit leaves an orphan blob, which is expected and sweepable. The order exists to make the opposite impossible: an index row pointing at bytes that were never written is a phantom reference, and nothing downstream can recover from one.

Version allocation serializes on the alias row. A writer takes SELECT ... FOR UPDATE on artifact_aliases before computing latest_version + 1, so two concurrent overwrites of the same alias cannot both allocate the same number. PostgreSQL does here what the in-memory store gets from its asyncio.Lock.

Pinning is derived, never stored. A version is pinned while any nonterminal task references it in artifact_evidence — including a task other than the one that produced it. A single mutable flag could not express "two tasks reference this, one has finished", and consulting only the producing task would let a cross-task reference be swept out from under its holder.

Parameter Type Default Description
tasks 'PostgresTaskMemoryStore' The task store whose pool, schema and transaction coordinator this store shares.
blobs Optional[Any] None Durable byte storage (:class:~..blob.ArtifactBlobStore). Without it, versions are registered as metadata only and reported honestly as missing — durable metadata with no durable bytes is not evidence, and is never presented as such.
config Optional[TaskMemoryConfig] None Capacity configuration. Defaults to the task store's.

Method PostgresArtifactStore.transaction

Open a transaction this store and the task store can share.

transaction() -> Any

Returns: Any — An async context manager yielding a class:PostgresTransaction.

Method PostgresArtifactStore.close

Release resources. The pool belongs to the task store.

close() -> None

Method PostgresArtifactStore.put

Register a value durably, allocating or incrementing its version.

Snapshotting and fingerprinting run on a worker thread before the transaction opens, so no database lock is held across CPU work. Only allocation, the blob write and publication happen inside it.

pin_for registers and pins in one act. As in the in-memory store this matters for more than convenience: an unpinned version is an ordinary retention candidate, so a value pinned only afterwards can be swept before its pin ever applies.

put(scope: TaskScope, key: str, value: Any, *, task_id: Optional[str] = None, kind: Optional[ArtifactKind] = None, description: str = '', producer_call_id: Optional[str] = None, attribution: Attribution = Attribution.NONE, turn_id: Optional[str] = None, metadata: Optional[dict] = None, transaction: Optional[Any] = None, pin_for: Optional[str] = None) -> ArtifactDescriptor

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
key str Working-memory alias to publish under.
value Any The value to register.
task_id Optional[str] None Owning task, when one is selected.
kind Optional[ArtifactKind] None Explicit evidence type; inferred when None.
description str '' Human-readable description, retained by the caller's catalog rather than stored here.
producer_call_id Optional[str] None The physical attempt that produced it.
attribution Attribution Attribution.NONE How that attempt was attributed.
turn_id Optional[str] None Conversation turn, stamped on the journal event.
metadata Optional[dict] None Caller metadata. Unused here; the catalog owns it.
transaction Optional[Any] None Shared transaction to enlist in, so the index rows and the journal event commit together.
pin_for Optional[str] None Task id to pin this version for, atomically with registration.

Returns: ArtifactDescriptor — The read projection of the newly registered version.

Raises:

  • LimitExceeded — If the alias exceeds :data:Limits.MAX_IDENTIFIER.
  • TaskMemoryUnavailable — If the database cannot be reached.

Method PostgresArtifactStore.pin_evidence

Pin a version for a task by recording an evidence reference.

pin_evidence(scope: TaskScope, ref: EvidenceRef, task_id: str, *, step_id: str = '__task__') -> bool

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
ref EvidenceRef The version to pin.
task_id str The referencing task.
step_id str '__task__' The referencing step.

Returns: bool — True when the version exists in this scope and was pinned.

Method PostgresArtifactStore.unpin_evidence

Drop every reference a task holds on a version.

unpin_evidence(scope: TaskScope, ref: EvidenceRef, task_id: str) -> bool

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
ref EvidenceRef The version.
task_id str The task releasing it.

Returns: bool — True when a reference was removed.

Method PostgresArtifactStore.pins_for

Return the NONTERMINAL tasks still referencing a version.

This is the pin query, and its shape is the point: a version is pinned while any nonterminal task references it, including one other than its producer. A terminal task's reference stops pinning, which is what lets retention proceed once every holder has finished — and what stops a cross-task reference being swept out from under a task that is still working.

pins_for(scope: TaskScope, ref: EvidenceRef) -> Tuple[str, ...]

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
ref EvidenceRef The version.

Returns: Tuple[str, ...] — The pinning task ids, sorted.

Method PostgresArtifactStore.get_current

Resolve an alias to the version it currently points at.

A plain key never searches another task's namespace, and a tombstoned alias resolves to nothing.

get_current(scope: TaskScope, key: str, *, task_id: Optional[str] = None) -> Optional[ArtifactDescriptor]

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
key str The alias.
task_id Optional[str] None Owning task namespace.

Returns: Optional[ArtifactDescriptor] — The current descriptor, or None.

Method PostgresArtifactStore.get_version

Resolve one exact version, checking scope.

A globally unique artifact id is an identifier, not a capability: the scope check is not optional. A same-scope cross-task reference must be explicit, so a task_id mismatch reports the version as absent rather than resolving it implicitly.

get_version(scope: TaskScope, ref: EvidenceRef, *, task_id: Optional[str] = None) -> Optional[ArtifactDescriptor]

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
ref EvidenceRef The exact version.
task_id Optional[str] None Owning task, when validating a cross-task reference.

Returns: Optional[ArtifactDescriptor] — The descriptor, or None.

Method PostgresArtifactStore.load_payload

Materialize a version's payload under a hard byte ceiling.

The bounds are delegated to the blob store, which checks the stored object's size before downloading it and verifies the checksum of what it transferred. A refusal never carries a payload.

load_payload(scope: TaskScope, ref: EvidenceRef, *, max_bytes: int, offset: Optional[int] = None, limit: Optional[int] = None) -> PayloadResult

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
ref EvidenceRef The exact version.
max_bytes int Ceiling on the decoded payload. 0 never materializes.
offset Optional[int] None First row, for a tabular page.
limit Optional[int] None Row count, for a tabular page.

Returns: PayloadResult — A result carrying either the payload or a refusal.

Method PostgresArtifactStore.list

Page artifact descriptors in a scope.

Descriptors are metadata only: building a page reads no blob, calls no repr() and computes no summary.

list(scope: TaskScope, *, task_id: Optional[str] = None, kinds: Optional[Sequence[ArtifactKind]] = None, limit: int = 50, cursor: Optional[str] = None, as_of_seq: Optional[int] = None) -> ArtifactPage

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
task_id Optional[str] None Restrict to one task's namespace.
kinds Optional[Sequence[ArtifactKind]] None Restrict to these evidence types.
limit int 50 Bounded page size.
cursor Optional[str] None Opaque cursor from a previous page.
as_of_seq Optional[int] None Recorded in the cursor query, for symmetry with the in-memory store.

Returns: ArtifactPage — A bounded page of descriptors.

Raises:

  • CursorError — If the cursor is malformed, out of bounds, or issued for a different scope or query.

Method PostgresArtifactStore.invalidate

Mark one version's content as no longer valid evidence.

Bytes are left alone: invalidation is a statement about evidence, not about storage, and a persisted payload remains on disk. evidence_verifiable is cleared, because a fingerprint that no longer describes the content proves nothing.

invalidate(scope: TaskScope, ref: EvidenceRef, *, reason: str, transaction: Optional[Any] = None) -> ArtifactDescriptor

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
ref EvidenceRef The exact version.
reason str Why.
transaction Optional[Any] None Shared transaction to enlist in.

Returns: ArtifactDescriptor — The updated descriptor.

Raises:

  • ScopeViolation — If the version does not exist in this scope.

Method PostgresArtifactStore.evict

Release a version's stored bytes, keeping its metadata.

Explicit eviction does not invalidate: the caller asked for the bytes back, and the fingerprint still describes what the version contained. A metadata tombstone always remains, so no step is left labelled valid against evidence that silently vanished.

The index row is updated first and the object deleted afterwards. A crash between them leaves an orphan blob, which retention sweeps — the opposite order would leave the index pointing at bytes that are already gone.

evict(scope: TaskScope, ref: EvidenceRef) -> bool

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
ref EvidenceRef The exact version.

Returns: bool — True when bytes were released.

Method PostgresArtifactStore.drop_alias

Remove a live alias without deleting the versions behind it.

The identity and its version counter survive as a tombstone, so a later re-put under the same key continues at latest + 1. Restarting at 1 would let a fresh, unrelated version shadow still-pinned evidence at the same coordinates.

drop_alias(scope: TaskScope, key: str, *, task_id: Optional[str] = None) -> bool

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
key str The alias to remove.
task_id Optional[str] None Owning task namespace.

Returns: bool — True when the alias existed and was live.

Class PostgresTaskMemoryStore

Durable task-memory storage on PostgreSQL (Delivery B).

The schema lifecycle, the pool, the transaction coordinator and the journal/projection command and read paths are implemented here.

Durable aliases, versions and evidence pins belong to :class:PostgresArtifactStore, which shares this store's pool and transaction coordinator.

Parameter Type Default Description
dsn Optional[str] None PostgreSQL connection string. None defers to pool.
pool Optional[Any] None An already-built asyncpg pool to borrow. When given, this store does not own it and will not close it.
schema str SCHEMA_NAME Schema to operate in. Overridable only for test isolation; production always uses :data:SCHEMA_NAME.
min_size int 1 Minimum pool size when this store builds the pool.
max_size int 10 Maximum pool size when this store builds the pool.
config Optional[TaskMemoryConfig] None

Method PostgresTaskMemoryStore.close

Close the pool, if this store owns it.

close() -> None

Method PostgresTaskMemoryStore.coordinator

Return the coordinator that hands out shareable transactions.

coordinator() -> PostgresTransactionCoordinator

Returns: PostgresTransactionCoordinator

Method PostgresTaskMemoryStore.transaction

Open a transaction this store and an artifact store can share.

transaction() -> Any

Returns: Any — An async context manager yielding a class:PostgresTransaction.

Method PostgresTaskMemoryStore.apply_migrations

Apply the packaged migration explicitly.

Safe to repeat: every statement is IF NOT EXISTS-guarded and the version row uses ON CONFLICT DO NOTHING, so re-running is a no-op that also completes a migration interrupted part-way.

This is never called from a tool path. Automatic DDL on a hot path would mean any agent turn could attempt a schema change.

apply_migrations() -> int

Returns: int — The migration version now recorded in the database.

Raises:

  • TaskMemoryUnavailable — If the database already records a NEWER migration than this build implements. Running old code against a new schema is refused rather than attempted.

Method PostgresTaskMemoryStore.revert_migrations

Run the DOWN migration.

.. danger::

Destructive and irreversible: it drops the whole schema, and every journal, projection and artifact index row with it. It also orphans every blob in external storage, which this migration does not touch. Read the rollback guidance at the top of the migration file before calling this.

revert_migrations() -> None

Method PostgresTaskMemoryStore.verify_schema

Check the database has the shape this build expects.

Called at enabled-backend startup, not per operation. A missing table is reported by name, so an operator sees "you did not run the migration" rather than a confusing error inside the first append.

verify_schema() -> None

Raises:

  • TaskMemoryUnavailable — If the schema is absent, incomplete, or records a newer migration than this build implements.

Method PostgresTaskMemoryStore.create_task

Create a task and append its first batch of events atomically.

There is no window in which a task exists with an empty journal: the row and its whole creation batch commit together.

Creation is idempotent and safe to race. Two pods creating the same task id concurrently produce one row and one journal — the loser of the INSERT ... ON CONFLICT DO NOTHING falls through to the ordinary append path, which recognises the identical batch as a redelivery.

create_task(scope: TaskScope, *, goal: str, events: Sequence[JournalEvent], transaction: Optional[PostgresTransaction] = None) -> AppendResult

Parameter Type Default Description
scope TaskScope Trusted runtime scope the task belongs to.
goal str The task's goal, stamped onto task_started when the event does not already carry it.
events Sequence[JournalEvent] Initial events, beginning with task_started.
transaction Optional[PostgresTransaction] None A transaction to enlist in, or None.

Returns: AppendResult — The append result, including the reduced projection.

Raises:

  • LimitExceeded — If the scope already holds the maximum number of open tasks.
  • ScopeViolation — If the task id already exists in a different scope.
  • ReducerError — If the batch is malformed.
  • PlanValidationError — If the initial plan is invalid.

Method PostgresTaskMemoryStore.append_events

Append a batch of events under an optimistic revision check.

append_events(scope: TaskScope, task_id: str, events: Sequence[JournalEvent], *, expected_revision: Optional[int] = None, transaction: Optional[PostgresTransaction] = None) -> AppendResult

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
task_id str The task to append to.
events Sequence[JournalEvent] The batch, in order.
expected_revision Optional[int] None Revision the caller believes is current. None skips the check.
transaction Optional[PostgresTransaction] None A transaction to enlist in, or None.

Returns: AppendResult — The append result.

Raises:

  • ScopeViolation — If the task does not exist in this scope.
  • RevisionConflict — If the revision is stale and the batch is not a pure redelivery. Nothing is written.
  • ReducerError — If an id is reused with a different payload, or an event is malformed.
  • LimitExceeded — If the journal's capacity is exhausted.

Method PostgresTaskMemoryStore.load_snapshot

Load one task's projection consistently.

The projection, its sequence fence and the event count are read in ONE transaction, so a concurrent append cannot make them describe different instants.

load_snapshot(scope: TaskScope, task_id: str) -> Optional[TaskSnapshot]

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

Returns: Optional[TaskSnapshot] — The snapshot, or None when no such task exists in this scope. A task owned by another scope reads as absent rather than forbidden — an existence oracle is a leak.

Method PostgresTaskMemoryStore.list_tasks

List tasks in a scope, newest activity first.

Ordering is (updated_at desc, task_id asc), matching the in-memory store. The task-id tiebreak makes the order total, so keyset pagination cannot skip or repeat a row when two tasks share a timestamp.

list_tasks(scope: TaskScope, *, statuses: Optional[Sequence[TaskStatus]] = None, limit: int = 20, cursor: Optional[str] = None) -> TaskPage

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
statuses Optional[Sequence[TaskStatus]] None Restrict to these statuses; None means open (non-terminal) tasks only.
limit int 20 Bounded page size.
cursor Optional[str] None Opaque cursor from a previous page.

Returns: TaskPage — A bounded page of summaries.

Raises:

  • CursorError — If the cursor is malformed, out of bounds, or was issued for a different scope or query.

Method PostgresTaskMemoryStore.list_events

Page a task's journal in ascending sequence order.

Reads never append: no statement here writes, so repeated reads cannot change a task's sequence or fill its journal.

list_events(scope: TaskScope, task_id: str, *, after_seq: int = 0, limit: int = 50, as_of_seq: Optional[int] = None) -> EventPage

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
task_id str The task to read.
after_seq int 0 Return events strictly after this sequence.
limit int 50 Bounded page size.
as_of_seq Optional[int] None Fence the read at this sequence.

Returns: EventPage — A bounded page of events.

Raises:

  • ScopeViolation — If the task does not exist in this scope.

Method PostgresTaskMemoryStore.unresolved_calls

List calls this task started but never settled.

Read-only and appends nothing. An unresolved call is a question, not a verdict: a ten-minute tool call is unresolved for ten minutes and is perfectly healthy throughout.

unresolved_calls(scope: TaskScope, task_id: str) -> Tuple[UnresolvedCall, ...]

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

Returns: Tuple[UnresolvedCall, ...] — The unresolved calls, in start order.

Raises:

  • ScopeViolation — If the task does not exist in this scope.

Method PostgresTaskMemoryStore.has_terminal_event

Whether a call already has a settled outcome.

This is the durable half of fencing. A late result from an old owner is rejected on the strength of this, not on Redis: the journal is the record, and a decision already written there cannot be overwritten by a slower owner that has just woken up.

has_terminal_event(scope: TaskScope, task_id: str, call_id: str) -> bool

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
task_id str The owning task.
call_id str The attempt.

Returns: bool — True when a terminal event exists for the call.

Raises:

  • ScopeViolation — If the task does not exist in this scope.

Method PostgresTaskMemoryStore.reconcile_calls

Settle provably-dead calls as tool_outcome_unknown, once.

Three properties this method exists to guarantee:

  • A live call is never touched. is_live must return False — provably gone — before anything is appended. True and None are both left alone, so neither a slow call nor an unreachable cache can be mistaken for a crash. An expired append lease is not consulted at all: it says nothing about whether a call is running.
  • At most one unknown per call, ever. The whole pass runs under the task row's SELECT ... FOR UPDATE, and the unresolved set is read inside that lock. A second reconciler blocks, then re-reads and finds the call already settled. Two concurrent reconcilers therefore append one event between them, not two — and a repeated scan appends none.
  • Nothing is retried. This records that an outcome is unknown. It never re-dispatches: the effect may already have happened, and repeating it is the one unrecoverable mistake.

reconcile_calls(scope: TaskScope, task_id: str, *, is_live: Optional[LivenessProbe] = None, min_age_seconds: float = 0.0, now: Optional[datetime] = None, reason: str = 'the owner of this call is no longer live and its outcome was never recorded; the tool may or may not have run, so this is UNKNOWN and must not be retried automatically') -> ReconcileReport

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
task_id str The task to reconcile.
is_live Optional[LivenessProbe] None Tri-state liveness probe. None means no probe is available, in which case nothing is reconciled — refusing to guess is the point.
min_age_seconds float 0.0 Grace period. A call younger than this is left alone even if it looks dead, so a claim that has not yet been written cannot be raced.
now Optional[datetime] None Injected clock, for deterministic tests.
reason str 'the owner of this call is no longer live and its outcome was never recorded; the tool may or may not have run, so this is UNKNOWN and must not be retried automatically' Text recorded on the event.

Returns: ReconcileReport — class:ReconcileReport distinguishing every skip reason.

Raises:

  • ScopeViolation — If the task does not exist in this scope.

Method PostgresTaskMemoryStore.count_events

Return how many events a task's journal holds.

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

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

Returns: int — The event count, or 0 when the task does not exist in this scope.

Method PostgresTaskMemoryStore.purge_task

Delete one terminal task's journal and projection.

Implements :class:~..retention.JournalPurge. Two guards make this safe to call from a sweeper that may be racing anything else in the system:

Only a terminal task is ever purged. Retention only selects terminal tasks, but the check is repeated here because this is the last point before the rows are gone. A task that was resumed between selection and purge is left alone — the sweeper's view is a snapshot, and acting on a stale one is exactly how live work gets deleted.

Pins held by other tasks survive. Deleting the row cascades to this task's task_journal and artifact_evidence rows only. A version another, still-live task references keeps that task's evidence row, so it stays pinned and is not swept afterwards. The artifact rows themselves are never touched here.

.. warning::

This destroys the local audit trail, including the retention_scheduled event recording the intent to destroy it. With archive_uri configured the archive carries that final event; without one the deletion is deliberately irreversible. Nothing in this method preserves in-journal audit, and it does not pretend to.

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 rows were removed. Idempotent: purging an already-purged task returns False rather than failing, so a retry after a crash converges instead of erroring.

Method PostgresTaskMemoryStore.live_storage_refs

Return every storage key an index row still points at.

This is the "live index" half of the orphan rule. A blob absent from this set is not automatically an orphan — a publish may be in flight, or an archive may reference it — but a blob present in it is definitively not one.

live_storage_refs(scope: TaskScope) -> FrozenSet[str]

Parameter Type Default Description
scope TaskScope Trusted runtime scope.

Returns: FrozenSet[str] — The referenced storage keys.

Class PostgresTransaction

One unit of work, bound to exactly one pooled connection.

Satisfies the :class:~parrot.interfaces.task_memory.Transaction protocol. The connection is exposed so that the task store and the artifact store write through the same one — that shared connection is the whole point of the coordinator, and the reason an artifact's index row, its evidence rows and its journal event become visible together or not at all.

Parameter Type Default Description
connection 'asyncpg.Connection' The pooled connection this unit of work runs on.
transaction Any The driver-level transaction object.

Attributes:

Attribute Type Description
connection 'asyncpg.Connection' The connection every enlisted store must use.
is_active bool Whether this transaction is still open.

Method PostgresTransaction.rollback

Abandon the unit of work, discarding every change made in it.

Idempotent: rolling back an already-finished transaction is a no-op, so a cleanup path never has to guess whether it ran.

rollback() -> None

Class PostgresTransactionCoordinator

Hands out transactions the task and artifact stores share.

Satisfies :class:~parrot.interfaces.task_memory.TransactionCoordinator.

Parameter Type Default Description
store 'PostgresTaskMemoryStore' The store whose pool supplies connections.

Method PostgresTransactionCoordinator.begin

Open a transaction, committing on clean exit, rolling back on error.

begin() -> AsyncIterator[PostgresTransaction]

Returns: AsyncIterator[PostgresTransaction]

Raises:

  • TaskMemoryUnavailable — If no pool is configured.

Attribute REQUIRED_TABLES

Type: Tuple[str, ...]

Class ReconcileReport

What one reconciliation pass actually did.

Every bucket is reported separately, because "did nothing" has three very different meanings and collapsing them would hide the case this task exists to protect.

There is deliberately no already_resolved bucket. The unresolved set is read inside the task lock, so a call another reconciler has already settled is simply not in it — scanned drops instead. A field that could never be populated would imply a distinction this design does not make.

Parameter Type Default Description
scanned int 0
reconciled Tuple[str, ...] ()
alive Tuple[str, ...] ()
unknown_liveness Tuple[str, ...] ()
too_young Tuple[str, ...] ()

Fields:

Field Type Default Description
scanned int 0 Unresolved calls considered.
reconciled Tuple[str, ...] () Calls newly recorded as tool_outcome_unknown.
alive Tuple[str, ...] () Calls skipped because their owner still holds them.
unknown_liveness Tuple[str, ...] () Calls skipped because liveness could not be determined. Not reconciled — an unreachable cache is not evidence of death.
too_young Tuple[str, ...] () Calls skipped as inside the grace period.

Attributes:

Attribute Type Description
changed bool Whether this pass appended anything.

Attribute SCHEMA_NAME

Type: str

Attribute TERMINAL_CALL_EVENTS

Type: Tuple[str, ...]

Class UnresolvedCall

A call the journal shows starting but never finishing.

Being unresolved says nothing about whether the call is alive. It is the question recovery asks, not the answer.

Parameter Type Default Description
call_id str
tool_name str
started_at datetime
started_seq int
step_id Optional[str] None
turn_id Optional[str] None
parent_call_id Optional[str] None
attempt int 1
is_aggregate bool False

Fields:

Field Type Default Description
call_id str The physical attempt.
tool_name str The tool it dispatched, as recorded at start.
started_at datetime When tool_started was persisted.
started_seq int Its journal sequence.
step_id Optional[str] None The step it was attributed to, if any.
turn_id Optional[str] None The turn it belonged to.
parent_call_id Optional[str] None Its parent aggregate, if any.
attempt int 1 The attempt number recorded at start.
is_aggregate bool False Whether other calls name it as their parent. An aggregate is not a physical attempt and must not be counted as one.

Function migration_path

Return the path of the packaged migration file.

migration_path() -> Path

Returns: Path — Absolute path to migrations/001_task_memory.sql.

Function read_migration

Read the packaged migration file.

read_migration() -> str

Returns: str — The file's full text.

Raises:

  • TaskMemoryUnavailable — If the migration is missing from the installed package. A durable deployment without its schema definition cannot be made durable, so this fails loudly at startup rather than at the first append.

Function split_migration

Split the migration into its UP and DOWN halves.

split_migration(sql: Optional[str] = None) -> Tuple[str, str]

Parameter Type Default Description
sql Optional[str] None Migration text; read from the package when None.

Returns: Tuple[str, str] — A (up_sql, down_sql) pair, each stripped.

Raises:

  • TaskMemoryUnavailable — If either fence is missing or malformed. A migration whose DOWN half cannot be located is, for operational purposes, an irreversible one — better to refuse it than to discover that during a rollback.

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