Skip to content

API Reference parrot.tools.working_memory.task_memory.context

github-actions[bot] edited this page Nov 10, 2026 · 4 revisions

parrot.tools.working_memory.task_memory.context

View source

Per-turn task context: declaration registry and invocation receipts (FEAT-538).

This module implements the specification's §2 Single Observer and Turn Context and decision D3. It answers one question — which task step, if any, does this tool call belong to? — and it answers it truthfully, which mostly means refusing to guess.

Why a session object rather than a plain ContextVar

The obvious design is a ContextVar holding the declared step ids. It does not work. contextvars copies the context into a spawned :class:asyncio.Task, so a child that assigns a new value publishes it to nobody: not to its parent, not to its siblings. A sub-agent that declares "I am now running step X" inside a child task would be invisible to the very dispatches that need to see it.

So the runtime owns a :class:TurnTaskSession — one mutable object per turn — and the ContextVar holds a reference to it. Mutating the shared session publishes; rebinding the ContextVar does not. That single distinction is the whole reason this module exists.

What is frozen and what is not

The session is mutable for the turn's lifetime. Each dispatch takes a frozen :class:~parrot.tools.working_memory.task_memory.models. TaskContext snapshot of it. A declaration made after a dispatch never changes that dispatch's snapshot — attribution is decided at dispatch time and is never retroactively revised. This is what stops the system from quietly re-attributing a call once it learns more.

Attribution rules (D3)

====================================== ============================== Declared steps at dispatch Attribution ====================================== ============================== zero none (task-level) exactly one declared two or more ambiguous (task-level) explicit plan-to-step mapping plan (overrides the above) plan node with no mapping plan, task-level ====================================== ==============================

A plan node id is not a domain step id. An unmapped plan call keeps plan provenance and stays task-level rather than being attributed to a guessed step. And attribution never completes a step: it only records what the runtime could honestly say about where a call belonged.

Receipt lifetime

PlanToolNode._store (bots/flows/plan/node.py:347) runs after _call_with_retry (:414) has already returned, by which time the dispatcher has reset its per-invocation context. Without help, every artifact a plan node stores would lose its producer_call_id. :meth:TurnTaskSession.retained_producer is that help: it pins a completed attempt's call id across the post-dispatch boundary so the artifact receipt still names the attempt that produced it.

Attribute CURRENT_CALL

Type: contextvars.ContextVar[Optional[str]]

Attribute MAX_DECLARED_STEPS_PER_TURN

Type: int

Attribute RETAINED_PRODUCER

Type: contextvars.ContextVar[Optional[str]]

Class StaleTurnContext

A serialized turn context no longer matches the live runtime.

Raised when an envelope returning from a REPL worker names a task, worker generation or fencing token that has since moved on. The caller must not treat its result as attributable.

Attribute TASK_CONTEXT

Type: contextvars.ContextVar[Optional['TurnTaskSession']]

Class TurnContextEnvelope

The bounded context that may cross a process boundary.

Only this travels to a REPL worker — never the session, never a payload, never anything unbounded. On return, every field is revalidated against the live session (:meth:revalidate), because a worker may have been recycled, the selected task may have changed, and a stale generation must not be able to attribute work.

Fields:

Field Type Default Description
scope TaskScope Trusted runtime scope at the time of serialization.
task_id Optional[str] None The selected task, when one was selected.
turn_id Optional[str] None The conversation turn.
plan_revision int 0 Plan revision in force.
call_id Optional[str] None The attempt that crossed the boundary.
declared_step_ids Tuple[str, ...] () Steps declared at serialization time.
worker_session_id Optional[str] None Identity of the worker process generation.
worker_generation int 0 Monotonic generation within that session. A PID alone is not a generation identity — a recycled worker can reuse one.
fencing_token int 0 Monotonic token proving ownership of the call.

Method TurnContextEnvelope.revalidate

Check this envelope against the live session on return.

revalidate(session: 'TurnTaskSession', *, worker_session_id: Optional[str] = None, worker_generation: Optional[int] = None, fencing_token: Optional[int] = None) -> None

Parameter Type Default Description
session 'TurnTaskSession' The session the work belongs to.
worker_session_id Optional[str] None The worker generation identity observed on return, when the caller can supply one.
worker_generation Optional[int] None The generation counter observed on return.
fencing_token Optional[int] None The ownership token observed on return.

Raises:

  • ScopeViolation — If the scope no longer matches. This is a hard boundary: a mismatched scope is a cross-user read.
  • StaleTurnContext — If the selected task, worker generation or fencing token moved on while the work was out of process.

Class TurnTaskSession

One turn's shared, mutable task context.

Held by reference in :data:TASK_CONTEXT so that every child task and thread of the turn sees the same object. Mutation is what publishes.

The declaration registry is guarded by a :class:threading.RLock rather than an :class:asyncio.Lock, deliberately: the registry is also mutated from thread work (asyncio.to_thread and :func:run_in_thread), which an asyncio lock cannot protect. Every critical section is a few dict operations with no I/O and no await, so the lock is never held across a suspension point and cannot stall the event loop.

Parameter Type Default Description
scope TaskScope Trusted runtime scope. Never taken from a tool argument.
turn_id Optional[str] None The conversation turn's identity; generated when omitted.
task_id Optional[str] None The initially selected task, if any.
plan_revision int 0 Plan revision in force at the turn's start.
owner Optional[str] None Opaque identity of the worker running this turn, used to claim and heartbeat per-call ownership. Generated when omitted, which is what makes two processes — or two turns in one process — distinguishable to a fencing check.

Attributes:

Attribute Type Description
scope Trusted runtime scope for the whole turn.
turn_id The conversation turn's identity.
task_id Optional[str] The currently selected task, or None.
plan_revision int The plan revision in force for new snapshots.
declared_step_ids Tuple[str, ...] Currently declared step ids, in declaration order.
records Tuple[InvocationRecord, ...] Every attempt captured this turn, in start order. This is the canonical capture the enabled path hands to both journal derivation and ConversationTurn.tool_invocations. It is produced once; the legacy AIMessage.tool_calls conversion must be replaced by it, not concatenated with it.
open_call_ids Tuple[str, ...] Call ids of attempts that have started but not terminated.

Method TurnTaskSession.select_task

Select (or clear) the task this turn's work belongs to.

select_task(task_id: Optional[str]) -> None

Parameter Type Default Description
task_id Optional[str] The task to select, or None to clear.

Method TurnTaskSession.set_plan_revision

Record a new plan revision for subsequent snapshots.

set_plan_revision(revision: int) -> None

Parameter Type Default Description
revision int The new plan revision.

Raises:

  • ValueError — If revision is negative.

Method TurnTaskSession.declare

Declare that a step is running for this turn.

Called after a successful running-step update, so the shared session is what publishes the fact — including from inside a child task, where a ContextVar assignment would reach nobody.

Re-declaring an already-declared step is a no-op and keeps its original position, so a retry cannot make attribution look ambiguous.

declare(step_id: str) -> None

Parameter Type Default Description
step_id str The step now running.

Raises:

  • LimitExceeded — If the turn already declares :data:MAX_DECLARED_STEPS_PER_TURN steps.
  • ValueError — If step_id is empty or over-long.

Method TurnTaskSession.undeclare

Withdraw a declaration.

undeclare(step_id: str) -> bool

Parameter Type Default Description
step_id str The step to withdraw.

Returns: bool — True when the step had been declared.

Method TurnTaskSession.declaration

Declare step_id for the duration of the block.

The declaration is withdrawn in a finally, so an exception or a cancellation inside the block cannot leave the turn looking ambiguous for every later dispatch.

declaration(step_id: str) -> Iterator['TurnTaskSession']

Parameter Type Default Description
step_id str The step to declare.

Returns: Iterator['TurnTaskSession']

Method TurnTaskSession.snapshot

Freeze the session's current state into a dispatch snapshot.

Everything is read under one lock acquisition so the snapshot is internally consistent even while other tasks are declaring.

snapshot(*, parent_call_id: Optional[str] = None, plan_run_id: Optional[str] = None, plan_node_id: Optional[str] = None, plan_item_index: Optional[int] = None, plan_attempt: Optional[int] = None, mapped_step_id: Optional[str] = None) -> TaskContext

Parameter Type Default Description
parent_call_id Optional[str] None Parent aggregate call, when nested. Defaults to the call currently executing in this context.
plan_run_id Optional[str] None Explicit plan-run correlation.
plan_node_id Optional[str] None Explicit plan-node correlation.
plan_item_index Optional[int] None Fan-out index within a plan node.
plan_attempt Optional[int] None Attempt number within the node's retry policy.
mapped_step_id Optional[str] None Step id resolved by an explicit plan-to-step mapping. Supplying it is the only way a plan call gets attributed to a specific step.

Returns: TaskContext — An immutable :class:TaskContext.

Method TurnTaskSession.envelope

Serialize the bounded context that may cross a process boundary.

envelope(*, call_id: Optional[str] = None, worker_session_id: Optional[str] = None, worker_generation: int = 0, fencing_token: int = 0) -> TurnContextEnvelope

Parameter Type Default Description
call_id Optional[str] None The attempt crossing the boundary. Defaults to the call currently executing in this context.
worker_session_id Optional[str] None Identity of the worker process generation.
worker_generation int 0 Generation counter within that session.
fencing_token int 0 Ownership token for the call.

Returns: TurnContextEnvelope — The envelope. Nothing unbounded and no payload travels in it.

Method TurnTaskSession.receipt

Look up one attempt's receipt by call id.

receipt(call_id: str) -> Optional[InvocationRecord]

Parameter Type Default Description
call_id str The attempt's identity.

Returns: Optional[InvocationRecord] — The record, or None when this turn has no such attempt.

Method TurnTaskSession.begin_invocation

Open a receipt for one physical dispatch attempt.

The frozen snapshot is taken here, at dispatch time. Declarations made later do not change it.

begin_invocation(tool_name: str, *, attempt: int = 1, parent_call_id: Optional[str] = None, plan_run_id: Optional[str] = None, plan_node_id: Optional[str] = None, plan_item_index: Optional[int] = None, plan_attempt: Optional[int] = None, mapped_step_id: Optional[str] = None) -> InvocationRecord

Parameter Type Default Description
tool_name str The tool about to be dispatched.
attempt int 1 1-based attempt number for this physical call.
parent_call_id Optional[str] None Parent aggregate call; defaults to the call currently executing in this context.
plan_run_id Optional[str] None Explicit plan-run correlation.
plan_node_id Optional[str] None Explicit plan-node correlation.
plan_item_index Optional[int] None Fan-out index within a plan node.
plan_attempt Optional[int] None Attempt number within the node's retry policy.
mapped_step_id Optional[str] None Step resolved by an explicit plan-to-step mapping.

Returns: InvocationRecord — The open :class:InvocationRecord.

Method TurnTaskSession.complete_invocation

Close a receipt with its typed terminal outcome.

complete_invocation(record: InvocationRecord, *, outcome: CallOutcome, executed: bool, error: Optional[str] = None, elapsed_ms: Optional[int] = None, invocation: Any = None, artifact_receipts: Sequence[EvidenceRef] = (), degraded: bool = False, finished_at: Optional[datetime] = None) -> InvocationRecord

Parameter Type Default Description
record InvocationRecord The open receipt.
outcome CallOutcome Typed outcome of the attempt.
executed bool Whether a tool body actually ran. False for the dispatcher's early returns — an unknown tool or a guard denial is an unsuccessful dispatch, not a failed tool.
error Optional[str] None Condensed, redacted error text.
elapsed_ms Optional[int] None Wall-clock duration.
invocation Any None The canonical compaction ToolInvocation.
artifact_receipts Sequence[EvidenceRef] () Artifact versions this attempt produced.
degraded bool False Whether tracking for this attempt is degraded.
finished_at Optional[datetime] None Termination time; defaults to now.

Returns: InvocationRecord — The same record, now closed.

Method TurnTaskSession.add_artifact_receipt

Attach an artifact version to an attempt, even after it closed.

This is what keeps producer_call_id intact for a plan node, whose _store runs after dispatch has already returned.

add_artifact_receipt(call_id: str, ref: EvidenceRef) -> bool

Parameter Type Default Description
call_id str The producing attempt.
ref EvidenceRef The artifact version it produced.

Returns: bool — True when the attempt belongs to this turn.

Method TurnTaskSession.invocation

Open a receipt, publish it as the current call, and always close it.

Wrap the dispatch itself::

with session.invocation("wm_store") as receipt:
    result = await manager.execute_tool(...)
    session.complete_invocation(receipt, outcome=..., executed=True)

If the block raises — including :class:asyncio.CancelledError from a cancelled stream — the receipt is closed with a truthful outcome and :data:CURRENT_CALL is reset regardless. Cancellation recording is bounded (a status flip, no I/O) and the cancellation is then re-raised unchanged.

invocation(tool_name: str, *, attempt: int = 1, parent_call_id: Optional[str] = None, plan_run_id: Optional[str] = None, plan_node_id: Optional[str] = None, plan_item_index: Optional[int] = None, plan_attempt: Optional[int] = None, mapped_step_id: Optional[str] = None) -> Iterator[InvocationRecord]

Parameter Type Default Description
tool_name str The tool about to be dispatched.
attempt int 1 1-based attempt number.
parent_call_id Optional[str] None Parent aggregate call.
plan_run_id Optional[str] None Explicit plan-run correlation.
plan_node_id Optional[str] None Explicit plan-node correlation.
plan_item_index Optional[int] None Fan-out index within a plan node.
plan_attempt Optional[int] None Attempt number within the node's retry policy.
mapped_step_id Optional[str] None Step resolved by an explicit mapping.

Returns: Iterator[InvocationRecord]

Method TurnTaskSession.retained_producer

Keep call_id attributable past the dispatcher's context reset.

PlanToolNode wraps its post-dispatch _store in this, so the artifact it registers still records the attempt that produced it. Without it, :data:CURRENT_CALL has already been reset by the time _store runs and the provenance is simply lost.

retained_producer(call_id: str) -> Iterator[str]

Parameter Type Default Description
call_id str The producing attempt.

Returns: Iterator[str]

Method TurnTaskSession.barrier

Wait until every in-flight attempt in this turn has terminated.

The specification requires explicit completion barriers before concurrent control mutations and dependent work, precisely so the runtime never has to retroactively guess attribution. This is that barrier: await it before declaring a step whose attribution must not be confused with work already in flight.

barrier() -> None

Function async_turn_session

async with form of :func:turn_session.

async_turn_session(scope: TaskScope, *, turn_id: Optional[str] = None, task_id: Optional[str] = None, plan_revision: int = 0, owner: Optional[str] = None, session: Optional[TurnTaskSession] = None)

Parameter Type Default Description
scope TaskScope Trusted runtime scope for the turn.
turn_id Optional[str] None The conversation turn's identity.
task_id Optional[str] None Initially selected task, if any.
plan_revision int 0 Plan revision in force at the turn's start.
owner Optional[str] None Opaque worker identity for per-call ownership.
session Optional[TurnTaskSession] None An existing session to rebind instead of creating one.

Function current_call_id

Return the call id currently executing in this context.

current_call_id() -> Optional[str]

Returns: Optional[str] — The call id, or None outside a dispatch.

Function current_session

Return the turn session bound to this context, if any.

current_session() -> Optional[TurnTaskSession]

Returns: Optional[TurnTaskSession] — The session, or None when task memory is disabled or the turn has ended.

Function producer_call_id

Return the call id an artifact registered now should be attributed to.

An explicitly retained producer wins over the ambient current call: that is the whole point of :meth:TurnTaskSession.retained_producer, which exists because a plan node's _store runs after dispatch has already reset the ambient value.

producer_call_id() -> Optional[str]

Returns: Optional[str] — The producing call id, or None when there is nothing to attribute to. None is a truthful answer — it is never replaced with a guess.

Function run_in_thread

Run fn in a worker thread with this turn's context copied in.

:func:asyncio.to_thread propagates context, but ThreadPoolExecutor.submit and a bare :class:threading.Thread do not — and a thread that cannot see the session cannot declare or record anything. This helper copies the context explicitly so off-loop work is never silently unattributed.

run_in_thread(fn: Callable[..., _T], /, *args: Any, **kwargs: Any) -> _T

Parameter Type Default Description
fn Callable[..., _T] The callable to run.
*args Any () Positional arguments for fn.
**kwargs Any {} Keyword arguments for fn.

Returns: _T — Whatever fn returns.

Function spawn_task

Spawn a child task that shares this turn's session.

:func:asyncio.create_task already copies the context, so the child sees the same session object and its mutations are published back to the parent and to siblings. This wrapper exists to make that guarantee explicit at the call site rather than incidental.

spawn_task(coro: Any, *, name: Optional[str] = None) -> 'asyncio.Task[Any]'

Parameter Type Default Description
coro Any The coroutine to run.
name Optional[str] None Optional task name.

Returns: 'asyncio.Task[Any]' — The spawned task.

Function turn_session

Bind a turn session to :data:TASK_CONTEXT for the block.

The token is reset in a finally, so scope never leaks past the turn — not on an exception, and not when a streaming generator is cancelled and finalized.

Works in synchronous and asynchronous code alike; with around an await is fine, because binding a ContextVar involves no suspension.

turn_session(scope: TaskScope, *, turn_id: Optional[str] = None, task_id: Optional[str] = None, plan_revision: int = 0, owner: Optional[str] = None, session: Optional[TurnTaskSession] = None) -> Iterator[TurnTaskSession]

Parameter Type Default Description
scope TaskScope Trusted runtime scope for the turn.
turn_id Optional[str] None The conversation turn's identity.
task_id Optional[str] None Initially selected task, if any.
plan_revision int 0 Plan revision in force at the turn's start.
owner Optional[str] None Opaque worker identity for per-call ownership.
session Optional[TurnTaskSession] None An existing session to rebind instead of creating one.

Returns: Iterator[TurnTaskSession]

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