Skip to content

API Reference parrot.tools.working_memory.internals

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

parrot.tools.working_memory.internals

View source

Internal engine classes for WorkingMemoryToolkit.

Contains catalog storage, operation execution, and shape limiting components. These are internal implementation details — consumers should use WorkingMemoryToolkit from the package directly.

Two catalog configurations coexist (FEAT-538):

Legacy (default). No backend is attached. put/put_generic/ get/drop/list_entries behave exactly as they always have: a plain dict, no locks, no versions, no I/O. Every existing caller — the nine direct _catalog.put* sites in tool.py, and bots/flows/plan/node.py's direct _catalog reads — is unaffected.

Enabled (opt-in). A :class:~parrot.interfaces.artifact_store.ArtifactStore backend is attached, making the catalog versioned and persistent. Writes then go through the awaited API (:meth:WorkingMemoryCatalog.aput, :meth:~WorkingMemoryCatalog.aput_generic, :meth:~WorkingMemoryCatalog.aget, :meth:~WorkingMemoryCatalog.adrop), and a synchronous write is refused outright rather than being allowed to fire-and-forget the persistence half or block the event loop. That refusal is deliberate: a sync put that silently skipped the backend would publish an alias with no artifact version behind it, which is precisely the phantom-evidence failure versioning exists to prevent.

Reads stay synchronous in both configurations, because PlanToolNode._read_key / _has_key reach into the catalog directly and must keep working.

Alias AggFunc

Re-exported from parrot.tools.working_memory.models.AggFunc.

Alias ArtifactAvailability

Re-exported from parrot.tools.working_memory.task_memory.models.ArtifactAvailability.

Alias ArtifactDescriptor

Re-exported from parrot.tools.working_memory.task_memory.models.ArtifactDescriptor.

Alias ArtifactKind

Re-exported from parrot.tools.working_memory.task_memory.models.ArtifactKind.

Alias ArtifactStore

Re-exported from parrot.interfaces.artifact_store.ArtifactStore.

Alias Attribution

Re-exported from parrot.tools.working_memory.task_memory.models.Attribution.

Class CatalogEntry

Metadata and data container for a stored DataFrame in the catalog.

Parameter Type Default Description
key str
df pd.DataFrame
created_at float time.time()
source_operation Optional[OperationSpecInput] None
parent_keys list[str] list()
description str ''
error Optional[str] None
turn_id Optional[str] None
session_id Optional[str] None
version_metadata Optional[VersionMetadata] None

Fields:

Field Type Default Description
key str Unique identifier in the working memory catalog.
df pd.DataFrame The stored DataFrame.
created_at float field(default_factory=time.time) Unix timestamp when this entry was created.
source_operation Optional[OperationSpecInput] None Operation spec that produced it, when derived.
parent_keys list[str] field(default_factory=list) Keys this entry was derived from.
description str '' Optional human-readable description.
error Optional[str] None Error state, when the entry represents a failure.
turn_id Optional[str] None Optional conversation turn identifier.
session_id Optional[str] None Optional session identifier.
version_metadata Optional[VersionMetadata] None Captured version/evidence metadata (FEAT-538). None in the legacy configuration, where entries are not versioned.

Attributes:

Attribute Type Description
shape tuple[int, int] Return the shape of the stored DataFrame. This reads the live frame. It is intentionally left as-is and is not the same thing as :attr:VersionMetadata.captured_shape, which records the shape at the moment the fingerprint was taken. A mutated frame reports a new shape here while its captured shape — and the evidence that shape belongs to — stays fixed.
is_versioned bool Whether this entry was registered through the awaited API.
columns list[str] Return column names of the stored DataFrame.
dtypes_summary dict[str, str] Return column dtypes as a string dictionary.

Method CatalogEntry.to_descriptor

Project this entry's captured metadata as an artifact descriptor.

Builds the descriptor purely from :attr:version_metadata. It never touches :attr:df — no compact_summary(), no describe(), no memory_usage(deep=True). Those are expensive (describe() scans every numeric column) and recall pages descriptors in bulk, so the projection has to be free of them to stay on the hot path at all.

to_descriptor() -> 'ArtifactDescriptor'

Returns: 'ArtifactDescriptor' — class:ArtifactDescriptor for this entry's version.

Raises:

  • CatalogNotEnabledError — If the entry has no captured metadata, i.e. it was stored through the legacy synchronous path and therefore has no artifact identity to describe.

Method CatalogEntry.compact_summary

Return a token-efficient summary for the LLM context.

compact_summary(max_rows: int = 5, max_cols: int = 20) -> dict

Parameter Type Default Description
max_rows int 5
max_cols int 20

Returns: dict

Class CatalogNotEnabledError

An awaited catalog operation was used without a configured backend.

The awaited API is meaningful only when a backend and a trusted scope are attached; without them there is no version to allocate and no scope to attribute the write to.

Alias EntryType

Re-exported from parrot.tools.working_memory.models.EntryType.

Alias FilterSpec

Re-exported from parrot.tools.working_memory.models.FilterSpec.

Class GenericEntry

Catalog entry for non-DataFrame data.

Stores arbitrary Python objects alongside type-specific metadata and provides a type-aware compact summary for the LLM context.

Parameter Type Default Description
key str
data Any
entry_type EntryType
created_at float time.time()
description str ''
turn_id Optional[str] None
session_id Optional[str] None
metadata dict dict()
version_metadata Optional[VersionMetadata] None

Fields:

Field Type Default Description
key str Unique identifier in the working memory catalog.
data Any The stored Python object (any type).
entry_type EntryType Discriminator describing the kind of data.
created_at float field(default_factory=time.time) Unix timestamp when this entry was created.
description str '' Optional human-readable description.
turn_id Optional[str] None Optional conversation turn identifier.
session_id Optional[str] None Optional session identifier.
metadata dict field(default_factory=dict) Optional arbitrary user-defined metadata dict.
version_metadata Optional[VersionMetadata] None Captured version/evidence metadata (FEAT-538). None in the legacy configuration, where entries are not versioned.

Attributes:

Attribute Type Description
is_versioned bool Whether this entry was registered through the awaited API.

Method GenericEntry.to_descriptor

Project this entry's captured metadata as an artifact descriptor.

Builds the descriptor purely from :attr:version_metadata. It never touches :attr:data — no compact_summary(), no repr(), no type introspection. Recall pages descriptors in bulk, so touching the payload would put an arbitrary object's repr on the hot path and risk leaking its contents into a listing that is supposed to be metadata only.

to_descriptor() -> 'ArtifactDescriptor'

Returns: 'ArtifactDescriptor' — class:ArtifactDescriptor for this entry's version.

Raises:

  • CatalogNotEnabledError — If the entry has no captured metadata, i.e. it was stored through the legacy synchronous path and therefore has no artifact identity to describe.

Method GenericEntry.compact_summary

Return a type-aware compact summary suitable for the LLM context.

compact_summary(max_length: int = 500) -> dict

Parameter Type Default Description
max_length int 500 Maximum characters for text/content previews.

Returns: dict — A dict with entry metadata and type-specific preview fields.

Alias JoinHow

Re-exported from parrot.tools.working_memory.models.JoinHow.

Class OperationExecutor

Executes OperationSpecInput against DataFrames from the catalog.

Purely deterministic — no LLM calls, no free-form code execution. Each operation type is dispatched to a dedicated handler method.

Method OperationExecutor.execute

Dispatch the operation spec to the appropriate handler.

execute(spec: OperationSpecInput, catalog: dict[str, CatalogEntry]) -> pd.DataFrame

Parameter Type Default Description
spec OperationSpecInput
catalog dict[str, CatalogEntry]

Returns: pd.DataFrame

Alias OperationSpecInput

Re-exported from parrot.tools.working_memory.models.OperationSpecInput.

Alias ReplBinding

Re-exported from parrot.tools.working_memory.task_memory.models.ReplBinding.

Class ShapeLimit

Maximum shape constraint for summaries returned to the LLM.

Parameter Type Default Description
max_rows int 10
max_cols int 30

Fields:

Field Type Default Description
max_rows int 10
max_cols int 30

Class SyncCatalogWriteError

A synchronous write was attempted against an enabled catalog (FEAT-538).

Raised by :meth:WorkingMemoryCatalog.put, :meth:~WorkingMemoryCatalog.put_generic and :meth:~WorkingMemoryCatalog.drop once an artifact-store backend is attached.

The alternatives were both worse. Writing to the local dict and scheduling the backend write in the background would publish an alias with no committed artifact version behind it — a phantom alias, which is exactly the failure versioned evidence exists to rule out. Driving the coroutine to completion from a sync frame would block the event loop. So the call is refused, and the message names the awaited method to use instead.

Alias TaskScope

Re-exported from parrot.tools.working_memory.task_memory.models.TaskScope.

Class VersionMetadata

Version and evidence facts captured when an entry was registered.

Shared by :class:CatalogEntry and :class:GenericEntry. Both need it: plan node results and compression-tee payloads are stored as generic entries, so attaching versions only to the DataFrame entry would leave most of the catalog unversioned.

Every field here is captured at registration time by the artifact store and then frozen. Nothing is recomputed from the live payload later, which is what lets :meth:to_descriptor stay cheap enough for recall's hot path — and what makes a descriptor describe the value as it was when its fingerprint was taken, rather than as it is now.

captured_shape is deliberately a separate field rather than a reuse of :attr:CatalogEntry.shape. That property reads self.df.shape live; shadowing it would mean a mutated frame silently reported a shape its fingerprint never covered.

Parameter Type Default Description
artifact_id str
version int
scope 'TaskScope'
kind 'ArtifactKind'
availability 'ArtifactAvailability'
created_at 'datetime'
task_id Optional[str] None
producer_call_id Optional[str] None
attribution Optional['Attribution'] None
fingerprint Optional[str] None
fingerprint_algorithm Optional[str] None
evidence_verifiable bool False
invalidated bool False
binding_invalid bool False
byte_size Optional[int] None
captured_shape Optional[tuple[int, ...]] None
schema_summary Optional[dict] None
storage_ref Optional[str] None
repl_binding Optional['ReplBinding'] None
invalidated_at Optional['datetime'] None

Fields:

Field Type Default Description
artifact_id str Stable identity allocated by the backend.
version int 1-based version within that identity.
scope 'TaskScope' Trusted :class:TaskScope the write was attributed to.
kind 'ArtifactKind' Captured :class:ArtifactKind.
availability 'ArtifactAvailability' Captured :class:ArtifactAvailability.
created_at 'datetime' When this version was registered (UTC).
task_id Optional[str] None Owning task, when one was selected.
producer_call_id Optional[str] None Physical attempt that produced the value.
attribution Optional['Attribution'] None How that attempt was attributed.
fingerprint Optional[str] None Canonical content fingerprint, when computable.
fingerprint_algorithm Optional[str] None Algorithm identity and version.
evidence_verifiable bool False Whether the fingerprint actually proves content integrity.
invalidated bool False Whether this version's evidence was invalidated.
binding_invalid bool False Whether its REPL binding is stale.
byte_size Optional[int] None Recorded payload size.
captured_shape Optional[tuple[int, ...]] None Shape as captured, e.g. (rows, cols).
schema_summary Optional[dict] None Bounded captured schema description.
storage_ref Optional[str] None Backend storage reference, when persisted.
repl_binding Optional['ReplBinding'] None Current REPL binding, when one exists.
invalidated_at Optional['datetime'] None When it was invalidated, if it was.

Method VersionMetadata.from_descriptor

Capture the facts an entry keeps from a backend descriptor.

from_descriptor(descriptor: 'ArtifactDescriptor') -> 'VersionMetadata'

Parameter Type Default Description
descriptor 'ArtifactDescriptor' What the artifact store returned for this write.

Returns: 'VersionMetadata' — The captured metadata.

Method VersionMetadata.to_descriptor

Rebuild the read projection from the captured facts.

to_descriptor(*, alias: Optional[str] = None) -> 'ArtifactDescriptor'

Parameter Type Default Description
alias Optional[str] None Current working-memory key. Passed by the owning entry so a renamed or dropped alias is reported truthfully.

Returns: 'ArtifactDescriptor' — class:ArtifactDescriptor for this version.

Class WorkingMemoryCatalog

In-memory catalog of DataFrames and generic entries.

Session-scoped storage engine that supports both DataFrame-centric CatalogEntry objects and polymorphic GenericEntry objects.

Key namespace is shared: storing either type with an existing key replaces the previous entry regardless of its type. This is intentional.

With an artifact-store backend attached the catalog becomes versioned and persistent (FEAT-538): writes must use the awaited API, and each write allocates or increments an artifact_id@version behind the alias. Without one, everything below behaves exactly as it always has.

Parameter Type Default Description
session_id Optional[str] None Session identifier stamped on every entry. Defaults to a fresh uuid4, as before.
backend Optional['ArtifactStore'] None Optional artifact store. Attaching one enables the versioned, persistent configuration and makes synchronous writes an error.
scope Optional['TaskScope'] None Trusted runtime scope every enabled write is attributed to. Required whenever backend is given — a versioned write with no scope could not be authorized on read back.
task_id Optional[str] None Default owning task for enabled writes. Individual calls may override it.

Attributes:

Attribute Type Description
is_enabled bool Whether a versioned, persistent backend is attached.
backend Optional['ArtifactStore'] The attached artifact store, or None in legacy mode.
scope Optional['TaskScope'] The trusted scope enabled writes are attributed to.

Method WorkingMemoryCatalog.put

Store a DataFrame under the given key and return the catalog entry.

put(key: str, df: pd.DataFrame, *, operation: Optional[OperationSpecInput] = None, parent_keys: Optional[list[str]] = None, description: str = '', error: Optional[str] = None, turn_id: Optional[str] = None) -> CatalogEntry

Parameter Type Default Description
key str
df pd.DataFrame
operation Optional[OperationSpecInput] None
parent_keys Optional[list[str]] None
description str ''
error Optional[str] None
turn_id Optional[str] None

Returns: CatalogEntry

Raises:

  • SyncCatalogWriteError — If task memory is enabled. Use :meth:aput instead.

Method WorkingMemoryCatalog.put_generic

Store arbitrary data under the given key and return the GenericEntry.

If entry_type is None the type is auto-detected via _detect_entry_type(). Storing with a key that already holds a CatalogEntry replaces it (intentional shared namespace).

put_generic(key: str, data: Any, *, entry_type: Optional[EntryType] = None, description: str = '', metadata: Optional[dict] = None, turn_id: Optional[str] = None) -> GenericEntry

Parameter Type Default Description
key str Unique identifier for this entry.
data Any The Python object to store.
entry_type Optional[EntryType] None Explicit EntryType; auto-detected when None.
description str '' Human-readable description.
metadata Optional[dict] None Optional user-defined metadata dict.
turn_id Optional[str] None Optional conversation turn identifier.

Returns: GenericEntry — The newly created GenericEntry.

Raises:

  • SyncCatalogWriteError — If task memory is enabled. Use :meth:aput_generic instead.

Method WorkingMemoryCatalog.get

Retrieve a catalog entry by key.

get(key: str) -> CatalogEntry | GenericEntry

Parameter Type Default Description
key str

Returns: CatalogEntry | GenericEntry

Method WorkingMemoryCatalog.drop

Remove an entry by key. Returns True if the key existed.

drop(key: str) -> bool

Parameter Type Default Description
key str

Returns: bool

Raises:

  • SyncCatalogWriteError — If task memory is enabled. Use :meth:adrop instead — dropping an enabled alias has to reach the backend so the alias tombstone is recorded and the pinned versions behind it are preserved.

Method WorkingMemoryCatalog.aput

Register a DataFrame with the backend, then publish its alias.

The order is the whole point. The backend allocates the version and acknowledges the write first; only then does the alias appear in the local dict. If the backend raises, nothing is published — a caller that sees the alias can always resolve the artifact version behind it.

aput(key: str, df: pd.DataFrame, *, operation: Optional[OperationSpecInput] = None, parent_keys: Optional[list[str]] = None, description: str = '', error: Optional[str] = None, turn_id: Optional[str] = None, task_id: Optional[str] = None, producer_call_id: Optional[str] = None, attribution: Optional['Attribution'] = None, pin_for: Optional[str] = None) -> CatalogEntry

Parameter Type Default Description
key str Alias to publish under.
df pd.DataFrame The DataFrame to store.
operation Optional[OperationSpecInput] None Operation spec that produced it, when derived.
parent_keys Optional[list[str]] None Keys it was derived from.
description str '' Human-readable description.
error Optional[str] None Error state, when the entry represents a failure.
turn_id Optional[str] None Conversation turn identifier.
task_id Optional[str] None Owning task; falls back to :attr:task_id.
producer_call_id Optional[str] None Physical attempt that produced the value.
attribution Optional['Attribution'] None How that attempt was attributed.
pin_for Optional[str] None Task id to pin this version for, atomically with registration. Without it a newly registered version is an ordinary eviction candidate and can be evicted at birth.

Returns: CatalogEntry — The published :class:CatalogEntry, carrying its captured attr:~CatalogEntry.version_metadata.

Raises:

  • CatalogNotEnabledError — If no backend is configured.

Method WorkingMemoryCatalog.aput_generic

Register arbitrary data with the backend, then publish its alias.

Same publish-after-acknowledgement ordering as :meth:aput. This is the path plan-node results and compression-tee payloads take, which is why generic entries carry version metadata too.

aput_generic(key: str, data: Any, *, entry_type: Optional[EntryType] = None, description: str = '', metadata: Optional[dict] = None, turn_id: Optional[str] = None, task_id: Optional[str] = None, producer_call_id: Optional[str] = None, attribution: Optional['Attribution'] = None, pin_for: Optional[str] = None) -> GenericEntry

Parameter Type Default Description
key str Alias to publish under.
data Any The Python object to store.
entry_type Optional[EntryType] None Explicit EntryType; auto-detected when None.
description str '' Human-readable description.
metadata Optional[dict] None User-defined metadata dict.
turn_id Optional[str] None Conversation turn identifier.
task_id Optional[str] None Owning task; falls back to :attr:task_id.
producer_call_id Optional[str] None Physical attempt that produced the value.
attribution Optional['Attribution'] None How that attempt was attributed.
pin_for Optional[str] None Task id to pin this version for, atomically with registration.

Returns: GenericEntry — The published :class:GenericEntry, carrying its captured attr:~GenericEntry.version_metadata.

Raises:

  • CatalogNotEnabledError — If no backend is configured.

Method WorkingMemoryCatalog.aget

Retrieve a catalog entry by key, under the catalog lock.

aget(key: str) -> CatalogEntry | GenericEntry

Parameter Type Default Description
key str The alias to read.

Returns: CatalogEntry | GenericEntry — The stored entry.

Raises:

  • KeyError — If the key is not present — same message shape as the synchronous :meth:get.

Method WorkingMemoryCatalog.adrop

Drop a live alias through the backend, then locally.

Dropping removes the alias, never the versions behind it. Pinned evidence survives, and the backend keeps an identity tombstone so a later re-registration cannot reuse a version number that some completed step still cites.

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

Parameter Type Default Description
key str The alias to drop.
task_id Optional[str] None Owning task namespace; falls back to :attr:task_id.

Returns: bool — True if the alias existed locally.

Raises:

  • CatalogNotEnabledError — If no backend is configured.

Method WorkingMemoryCatalog.descriptors

Project every versioned entry as an artifact descriptor.

Legacy entries — those stored through the synchronous path, with no artifact identity — are skipped rather than fabricated.

descriptors() -> list['ArtifactDescriptor']

Returns: list['ArtifactDescriptor'] — One descriptor per versioned entry, in insertion order.

Method WorkingMemoryCatalog.list_entries

Return compact summaries of all stored entries, optionally filtered by turn_id.

Handles both CatalogEntry (DataFrames) and GenericEntry objects. DataFrame entries always include "entry_type": "dataframe" for consistency with GenericEntry summaries.

list_entries(turn_id: Optional[str] = None, shape_limit: Optional[ShapeLimit] = None) -> list[dict]

Parameter Type Default Description
turn_id Optional[str] None If provided, only entries with a matching turn_id are returned.
shape_limit Optional[ShapeLimit] None Shape constraints for DataFrame previews.

Returns: list[dict] — List of summary dicts, one per stored entry.

Method WorkingMemoryCatalog.keys

Return all stored keys.

keys() -> list[str]

Returns: list[str]

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