Skip to content

API Reference parrot.tools.working_memory.task_memory.association

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

parrot.tools.working_memory.task_memory.association

View source

Task association and hot Redis keys (FEAT-538).

A task lives in PostgreSQL (Delivery B) or in process memory (Delivery A). What lives in Redis is only the association: which tasks are open in a conversation, and which one is currently selected. That distinction is the whole design, and two rules follow from it:

  • Task creation commits first, association second. If the association write then fails, the caller gets the committed task id back together with an explicit degradation marker, so it can recover or select the task — never create a second one. Duplicating a task because a cache write failed would be far worse than a missing pointer.
  • A missing association never deletes a task. The association is a pointer, not the record. Losing it costs a selection, not the work.

The association is stored inside ConversationHistory.metadata["task_memory"] so it shares the conversation's lifecycle and its scoping, rather than inventing a second source of truth about which conversation a task belongs to.

Concurrency

The association is written by task-memory code; metadata["compaction"] is written by the compaction layer, which knows nothing about tasks. They share one Redis hash field. A task-scoped lock therefore cannot protect it — the other writer would not take the lock. That is why the merge is a server-side WATCH/MULTI/EXEC compare-and-swap (:meth:~parrot.memory.redis.RedisConversation.merge_metadata): it is enforced by Redis against every writer to that key, including ones that have never heard of this module.

Hot keys

Three families, all scoped by :meth:TaskScope.cache_key, which percent-encodes its components so a value containing the separator cannot forge another scope's key:

=================== ===== ================================================ family TTL purpose =================== ===== ================================================ _task_lease 30 s append ownership; renewed only by its owner _task_recall 10 m the recall cache _task_ctx 24 h turn-context cache — never authoritative =================== ===== ================================================

The context cache is a convenience. Task state comes from the store; a cached context that disagrees is stale, not a second opinion.

Call ownership vs. the append lease

_task_lease carries two different things, and conflating them is the specific bug this design exists to prevent:

<prefix>_task_lease:<scope>:<task> The append lease. Short, contended, and expected to expire constantly — it serialises journal appends, nothing more.

<prefix>_task_lease:<scope>:<task>:call:<call_id> Per-call ownership, heartbeated for as long as the call is actually running. A ten-minute tool call renews this for ten minutes.

An expired append lease is not evidence that a call died — a healthy long-running call lets it lapse constantly, because it only needs it while appending. Only expired call ownership is evidence, and even then only when Redis was reachable enough to say so. :meth:is_call_alive therefore returns a tri-state: True alive, False provably gone, None unknown. Recovery must treat None as "leave it alone". Reading "not alive" out of an unreachable cache is how a healthy call gets declared dead and its external effect retried.

Attribute ASSOCIATION_KEY

Type: str

Class AssociationResult

Outcome of an association write.

degraded is the load-bearing field. A task that has been committed but not associated is still a real task: the caller must be told its id so it can select or recover it, and must not treat the failure as a reason to create another one.

Fields:

Field Type Default Description
association TaskAssociation The association as it now stands. On failure this is the last value that could be read.
degraded bool False Whether the association could not be persisted.
reason Optional[str] None Why, when it could not.
task_id Optional[str] None The task the write concerned.

Attribute CONTEXT_FAMILY

Type: str

Attribute LEASE_FAMILY

Type: str

Attribute RECALL_FAMILY

Type: str

Class TaskAssociation

Which tasks a conversation knows about, and which one is selected.

Fields:

Field Type Default Description
open_task_ids Tuple[str, ...] () Non-terminal tasks in this conversation, in the order they were opened.
selected_task_id Optional[str] None The authoritative selection. An omitted task id resolves only from here — never by similarity.
revision int 0 Monotonic association revision, so a caller can detect that someone else changed the selection underneath it.
updated_at Optional[str] None When the association last changed.

Method TaskAssociation.from_metadata

Read the association out of a conversation's metadata.

Tolerant by design: a malformed or absent block yields an empty association rather than raising. A conversation whose association is unreadable has simply lost a pointer, and refusing to talk to the user over it would be a worse outcome than re-selecting.

from_metadata(metadata: Optional[Dict[str, Any]]) -> 'TaskAssociation'

Parameter Type Default Description
metadata Optional[Dict[str, Any]] The conversation metadata, or None.

Returns: 'TaskAssociation' — The association.

Method TaskAssociation.to_metadata_value

Return the JSON-safe block stored under :data:ASSOCIATION_KEY.

to_metadata_value() -> Dict[str, Any]

Returns: Dict[str, Any] — The serialized association.

Method TaskAssociation.with_task

Return this association with task_id opened, optionally selected.

with_task(task_id: str, *, select: bool = True) -> 'TaskAssociation'

Parameter Type Default Description
task_id str The task to register.
select bool True Whether to make it the selected task.

Returns: 'TaskAssociation' — The new association.

Raises:

  • ValueError — If the scope already holds the maximum number of open tasks.

Method TaskAssociation.without_task

Return this association with task_id closed.

Closing the selected task clears the selection rather than guessing a replacement — picking one would be exactly the similarity-style inference the specification forbids.

without_task(task_id: str) -> 'TaskAssociation'

Parameter Type Default Description
task_id str The task to close.

Returns: 'TaskAssociation' — The new association.

Method TaskAssociation.selecting

Return this association with task_id selected.

selecting(task_id: str) -> 'TaskAssociation'

Parameter Type Default Description
task_id str The task to select. Registered as open if it was not already — this is how an explicit id repairs a lost association.

Returns: 'TaskAssociation' — The new association.

Raises:

  • ValueError — If the open-task ceiling would be exceeded.

Class TaskAssociationStore

Reads and writes the association, and owns the hot Redis keys.

Parameter Type Default Description
memory Any The conversation memory holding the association. It must expose merge_metadata — that is, :class:~parrot.memory.redis.RedisConversation or something compatible. A memory without it is usable read-only.
config Optional[TaskMemoryConfig] None TTLs and capacity limits.

Method TaskAssociationStore.key_for

Build a scoped hot key.

key_for(family: str, scope: TaskScope, *, suffix: Optional[str] = None) -> str

Parameter Type Default Description
family str One of :data:LEASE_FAMILY, :data:RECALL_FAMILY, :data:CONTEXT_FAMILY.
scope TaskScope The trusted scope.
suffix Optional[str] None Optional extra component (e.g. a task id).

Returns: str — The key. Scope components are percent-encoded by meth:TaskScope.cache_key, so a value containing : cannot forge another scope's key.

Method TaskAssociationStore.lease_key

Return the append-lease key for one task.

lease_key(scope: TaskScope, task_id: str) -> str

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The task.

Returns: str — The key.

Method TaskAssociationStore.call_lease_key

Return the per-call ownership key for one in-flight call.

Deliberately a sub-key of the task's append lease rather than a fourth key family: the spec names three families, and ownership is a lease. Both components are percent-encoded, so the literal :call: separator cannot be forged by a task id or call id that happens to contain it.

call_lease_key(scope: TaskScope, task_id: str, call_id: str) -> str

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The owning task.
call_id str The physical attempt.

Returns: str — The key.

Method TaskAssociationStore.recall_key

Return the recall-cache key for one recall shape.

recall_key(scope: TaskScope, cache_digest: str) -> str

Parameter Type Default Description
scope TaskScope The trusted scope.
cache_digest str Digest of the recall's cache-key parts.

Returns: str — The key.

Method TaskAssociationStore.context_key

Return the turn-context cache key.

context_key(scope: TaskScope) -> str

Parameter Type Default Description
scope TaskScope The trusted scope.

Returns: str — The key. The context cache is never authoritative for task state.

Method TaskAssociationStore.acquire_lease

Take the append lease for a task, if it is free.

acquire_lease(scope: TaskScope, task_id: str, owner: str) -> bool

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The task to lease.
owner str Opaque identity of the acquirer.

Returns: bool — True when the lease was taken.

Method TaskAssociationStore.renew_lease

Extend a lease we still own.

Read-and-extend is done in one Lua call: between a separate GET and PEXPIRE the lease could expire and be taken by someone else, and we would then be extending their lease.

renew_lease(scope: TaskScope, task_id: str, owner: str) -> bool

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The leased task.
owner str The identity that took the lease.

Returns: bool — True when the lease was still ours and was extended.

Method TaskAssociationStore.release_lease

Release a lease we still own, and only that one.

release_lease(scope: TaskScope, task_id: str, owner: str) -> bool

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The leased task.
owner str The identity that took the lease.

Returns: bool — True when our lease was released; False when it had already expired and possibly belongs to someone else now.

Method TaskAssociationStore.acquire_call

Claim ownership of one in-flight call.

acquire_call(scope: TaskScope, task_id: str, call_id: str, owner: str, *, ttl_seconds: Optional[int] = None) -> bool

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The owning task.
call_id str The physical attempt.
owner str Opaque identity of this worker.
ttl_seconds Optional[int] None TTL override; defaults to the configured lease TTL. Ownership must be heartbeated to outlive it.

Returns: bool — True when ownership was taken. False when someone else already holds it, or when there is no Redis to hold it in — the caller must not treat False as "the call is dead".

Method TaskAssociationStore.heartbeat_call

Extend ownership we still hold, by compare-owner semantics.

This is what keeps a legitimately long call alive. It extends only our own ownership: between a separate GET and PEXPIRE the key could expire and be reclaimed, and we would then be renewing somebody else's claim.

heartbeat_call(scope: TaskScope, task_id: str, call_id: str, owner: str, *, ttl_seconds: Optional[int] = None) -> bool

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The owning task.
call_id str The physical attempt.
owner str The identity that claimed it.
ttl_seconds Optional[int] None TTL override.

Returns: bool — True when ownership was still ours and was extended. False means we have been fenced out — our terminal result is no longer authoritative.

Method TaskAssociationStore.release_call

Release ownership we still hold, and only ours.

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

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The owning task.
call_id str The physical attempt.
owner str The identity that claimed it.

Returns: bool — True when our ownership was released.

Method TaskAssociationStore.call_owner

Return the current owner of a call, if any.

call_owner(scope: TaskScope, task_id: str, call_id: str) -> Optional[str]

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The owning task.
call_id str The physical attempt.

Returns: Optional[str] — The owner identity, or None when unowned or unreadable.

Method TaskAssociationStore.is_call_alive

Report whether a call's owner still holds it — tri-state.

The three answers are genuinely different and recovery depends on the distinction:

True Ownership is held and heartbeated. The call is running. Leave it alone however long it has been going. False Redis answered, and nobody holds this call. Its owner is provably gone: ownership outlives a healthy call by design, so an absent key means the heartbeat stopped. None We could not ask. Not evidence of anything. Treating this as False is how an unreachable cache gets a healthy call declared dead and its external effect retried.

is_call_alive(scope: TaskScope, task_id: str, call_id: str) -> Optional[bool]

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The owning task.
call_id str The physical attempt.

Returns: Optional[bool] — The tri-state liveness.

Method TaskAssociationStore.read

Read the current association.

read(scope: TaskScope) -> TaskAssociation

Parameter Type Default Description
scope TaskScope The trusted scope.

Returns: TaskAssociation — The association, or an empty one when the conversation has none or cannot be read.

Method TaskAssociationStore.associate

Register a task in the conversation, optionally selecting it.

Call this after the task has been committed to its store. A failure here is reported, not raised: the task exists, and the caller must be able to recover it rather than create a second one.

associate(scope: TaskScope, task_id: str, *, select: bool = True) -> AssociationResult

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The committed task's id.
select bool True Whether to select it.

Returns: AssociationResult — The result, with degraded=True when the association could not be written.

Method TaskAssociationStore.select

Select a task explicitly, repairing a lost association.

An explicit, same-scope task id remains usable when the conversation metadata is gone. This is the repair path the specification requires: recall will not silently select such a task, but a caller may say so outright.

select(scope: TaskScope, task_id: str) -> AssociationResult

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The task to select.

Returns: AssociationResult — The result.

Method TaskAssociationStore.close_task

Remove a task from the open set.

close_task(scope: TaskScope, task_id: str) -> AssociationResult

Parameter Type Default Description
scope TaskScope The trusted scope.
task_id str The task to close.

Returns: AssociationResult — The result.

Method TaskAssociationStore.resolve

Decide which task a command without an explicit id refers to.

The rules, in order:

  1. An explicit id wins — but only within this scope. Scope is enforced by the caller's store on the very next read; this method never widens it.
  2. Otherwise the authoritative selection is used.
  3. Otherwise, with exactly one open task, that one.
  4. Otherwise needs_selection with the candidates. Never a similarity guess.

resolve(scope: TaskScope, explicit_task_id: Optional[str] = None) -> TaskSelection

Parameter Type Default Description
scope TaskScope The trusted scope.
explicit_task_id Optional[str] None An id the caller supplied outright.

Returns: TaskSelection — The selection.

Class TaskSelection

The answer to "which task are we talking about?".

Fields:

Field Type Default Description
task_id Optional[str] None The resolved task, when exactly one applies.
needs_selection bool False Whether the caller must choose explicitly.
candidates Tuple[str, ...] () Open task ids to choose between, when it must.
association_revision int 0 The revision this answer was read at.

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