Skip to content

API Reference parrot.tools.working_memory.task_memory.snapshots

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

parrot.tools.working_memory.task_memory.snapshots

View source

Bounded evidence snapshots and deterministic fingerprints (FEAT-538).

Implements §2 Catalog Backend, Versions, and Evidence of the approved specification. Registering a value as task evidence has to answer three questions honestly, and this module is where they are answered:

  1. Is the snapshot really independent of the live value? Only then can a later mutation of the caller's object be detected instead of silently following it.
  2. Does the fingerprint actually prove content integrity? A digest you can compute is not the same as a digest that means something.
  3. How many bytes are we really retaining? An estimate must be labelled an estimate.

Phase 0 (TASK-2970) measured the traps this module exists to avoid:

  • pandas does not raise on unhashable object cells. It silently hashes their str repr, so hash_pandas_object happily returns a digest for a column of dicts. That digest is worthless as integrity proof — it even changes when a dict's key order changes while its content does not.
  • DataFrame.copy(deep=True) does not detach nested dict / list / set cells. Verified by object identity at 8/64/256 MiB: df["obj"].iloc[0] is snapshot["obj"].iloc[0] is True.
  • Column name changes do not alter row hashes, so the ordered column names must be folded into the fingerprint header explicitly.
  • Fingerprinting dominates cost (~9.5 s for a 256 MiB numeric frame, ~123 s for a nested-object one) while the copy is nearly free. Heavy work therefore goes through :func:capture_snapshot_async, and no caller may hold a lock across it.

Consequently: a frame carrying nested mutable object cells is reported :data:SnapshotOutcome.UNVERIFIABLE with evidence_verifiable=False, even though a fingerprint could have been computed for it. Refusing to launder a repr hash into an integrity claim is the entire point.

.. warning::

Delivery A is not durable. A captured snapshot lives in this process only. :data:SnapshotOutcome.SPILL_REQUIRED reports that a supported value exceeded the RAM cap and needs the durable tier; this module never writes bytes anywhere itself.

Class ByteAccount

Byte accounting for one candidate piece of evidence.

Live and snapshot copies are counted separately because both may be resident at once — that is exactly the doubling the spec warns about.

Parameter Type Default Description
live_bytes Optional[int]
snapshot_bytes int
method SizeMethod

Fields:

Field Type Default Description
live_bytes Optional[int] Footprint of the caller's value, or None when it could not be established.
snapshot_bytes int Footprint of the retained snapshot. 0 when no snapshot was retained.
method SizeMethod How the counts were obtained.

Attributes:

Attribute Type Description
exact bool Whether these counts are measured rather than estimated.
total_retained int Bytes this registration adds while both copies are resident.

Attribute CHECKSUM_ALGORITHM

Type: str

Attribute CHECKSUM_PREFIX

Type: str

Class ContentSnapshot

The full, honest outcome of offering a value as task evidence.

Parameter Type Default Description
kind ArtifactKind
outcome SnapshotOutcome
payload Optional[Any]
fingerprint Optional[str]
fingerprint_algorithm Optional[str]
evidence_verifiable bool
account ByteAccount
shape Optional[Tuple[int, ...]]
schema_summary Optional[Dict[str, Any]]
reason Optional[str]

Fields:

Field Type Default Description
kind ArtifactKind Detected evidence type.
outcome SnapshotOutcome What happened.
payload Optional[Any] The detached snapshot, when one was retained. None otherwise — a refusal never smuggles the value out.
fingerprint Optional[str] Canonical content fingerprint, when the value has a meaningful one.
fingerprint_algorithm Optional[str] :data:FINGERPRINT_ALGORITHM when a fingerprint is present.
evidence_verifiable bool Whether the fingerprint actually proves content integrity. False whenever the digest would be a repr hash, the kind is unsupported, or no snapshot backs it.
account ByteAccount Byte accounting.
shape Optional[Tuple[int, ...]] Captured shape, e.g. (rows, cols).
schema_summary Optional[Dict[str, Any]] Bounded structural description.
reason Optional[str] Why the value is unverifiable or needs spilling.

Attributes:

Attribute Type Description
captured bool Whether an independent snapshot is being retained.

Attribute FINGERPRINT_ALGORITHM

Type: str

Attribute FINGERPRINT_PREFIX

Type: str

Attribute MAX_SUMMARY_COLUMNS

Type: int

Class SizeMethod

How a byte count was obtained — and therefore how much it is worth.

Attributes:

Attribute Type Description
is_exact bool Whether this method yields a true byte count rather than an estimate.

Class SnapshotOutcome

What happened when a value was offered as evidence.

Class UnsupportedEvidence

A value has no reproducible canonical fingerprint.

Raised by the low-level fingerprint helpers. The high-level :func:capture_snapshot catches it and returns an explicit unverifiable :class:ContentSnapshot instead — an unsupported value is a result, not a crash.

Function blob_checksum

Checksum stored blob bytes — not a content fingerprint.

A blob checksum answers "did these bytes survive the round trip to storage intact". A content fingerprint answers "is this the same logical content". They are not interchangeable: the Parquet encoding of a frame has a different checksum on every write, while the frame's content fingerprint is stable. The distinct :data:CHECKSUM_PREFIX exists so the two can never be silently compared.

blob_checksum(data: bytes) -> str

Parameter Type Default Description
data bytes The exact bytes written to or read from storage.

Returns: str — data:CHECKSUM_PREFIX followed by a 16-hex-character BLAKE2b-8 digest.

Function canonical_json_bytes

Serialize value to canonical UTF-8 JSON with sorted keys.

Uses orjson with OPT_SORT_KEYS — measured byte-identical to the stdlib encoder for this subset and roughly 40x faster (1.6 s vs 65 s at 256 MiB, TASK-2970).

Serialization is strict in two respects, both deliberate:

  • No default= fallback. Coercing an unserializable object to its repr would produce a digest that looks authoritative while proving nothing, which is the exact failure mode this module exists to prevent.
  • No OPT_NON_STR_KEYS. That option stringifies keys, so {1: "a"} and {"1": "a"} would encode to identical bytes and earn identical fingerprints despite being different values. A fingerprint that equates distinct content is worse than no fingerprint, so non-string keys are rejected instead.

canonical_json_bytes(value: Any) -> bytes

Parameter Type Default Description
value Any A JSON-serializable value.

Returns: bytes — The canonical encoding.

Raises:

  • UnsupportedEvidence — If value cannot be serialized strictly.

Function capture_snapshot

Snapshot, fingerprint and account for a value offered as evidence.

Never raises for an unsupported value: an unsupported or oversized value is a result the caller must record honestly, not an error. The only exception is an invalid max_bytes, which is a caller bug.

This is CPU-bound for large inputs — measured at ~9.5 s to fingerprint a 256 MiB numeric frame. Call :func:capture_snapshot_async from an event loop, and never hold a lock across either form.

capture_snapshot(value: Any, *, max_bytes: int, kind: Optional[ArtifactKind] = None) -> ContentSnapshot

Parameter Type Default Description
value Any The value to snapshot.
max_bytes int RAM snapshot cap in bytes. 0 means never retain a RAM snapshot, so every supported value reports :data:SnapshotOutcome.SPILL_REQUIRED.
kind Optional[ArtifactKind] None Force an evidence type instead of detecting one. A forced kind that does not match the value falls through to the unverifiable path rather than being trusted.

Returns: ContentSnapshot — class:ContentSnapshot outcome.

Raises:

  • ValueError — If max_bytes is negative.

Function capture_snapshot_async

Await :func:capture_snapshot on a worker thread.

Copying and hashing are CPU-bound and dominate registration cost, so they must not run on the event loop. This function is pure with respect to shared state — it mutates no catalog and no cache — which is what makes running it off-thread safe. The caller commits the result on the owning loop, and must not hold the catalog lock while awaiting this.

capture_snapshot_async(value: Any, *, max_bytes: int, kind: Optional[ArtifactKind] = None) -> ContentSnapshot

Parameter Type Default Description
value Any The value to snapshot.
max_bytes int RAM snapshot cap in bytes.
kind Optional[ArtifactKind] None Force an evidence type instead of detecting one.

Returns: ContentSnapshot — class:ContentSnapshot outcome.

Raises:

  • ValueError — If max_bytes is negative.

Function dataframe_schema_summary

Describe a frame's structure within the schema-summary byte bound.

Records structure only — no values, no statistics, no previews.

dataframe_schema_summary(df: pd.DataFrame) -> Dict[str, Any]

Parameter Type Default Description
df pd.DataFrame The frame to describe.

Returns: Dict[str, Any] — A summary that serializes within data:Limits.MAX_SCHEMA_SUMMARY_BYTES. When the frame has too many columns the list is truncated and columns_truncated says so, rather than the summary being dropped or the bound breached.

Function detect_kind

Classify a value's evidence type.

detect_kind(value: Any) -> ArtifactKind

Parameter Type Default Description
value Any The value being offered as evidence.

Returns: ArtifactKind — The matching :class:~parrot.tools.working_memory.task_memory. models.ArtifactKind. Anything not recognised is data:ArtifactKind.OBJECT, which can never carry verifiable evidence.

Function fingerprint_bytes

Fingerprint canonical bytes (JSON and text evidence).

fingerprint_bytes(data: bytes) -> str

Parameter Type Default Description
data bytes Canonical UTF-8 bytes.

Returns: str — data:FINGERPRINT_PREFIX followed by a 16-hex-character BLAKE2b-8 digest.

Function fingerprint_dataframe

Fingerprint a DataFrame's canonical content.

Canonical content is the ordered structural header — shape, ordered column names, dtypes, index names and index dtype — followed by stable per-row hashes including the index. The header is not optional: measured on pandas 2.2.3, renaming a column does not change hash_pandas_object's output at all, so a fingerprint built from row hashes alone would call two differently-shaped frames identical.

Never touches compact_summary(), describe() or an object's repr().

fingerprint_dataframe(df: pd.DataFrame) -> str

Parameter Type Default Description
df pd.DataFrame The frame to fingerprint.

Returns: str — data:FINGERPRINT_PREFIX followed by a 16-hex-character BLAKE2b-8 digest.

Raises:

  • UnsupportedEvidence — If pandas cannot hash the frame's values — for example a column of list cells, which raises rather than repr-hashing.

Function unsafe_object_columns

Return the object-dtype columns that block a verifiable snapshot.

A column is unsafe when any of its values is not an immutable scalar. Two independent problems make such a column unusable as evidence, and either one alone is disqualifying:

  • copy(deep=True) does not detach it, so the "snapshot" still aliases the caller's mutable object.
  • pandas hashes it by repr, so the digest tracks formatting rather than content.

unsafe_object_columns(df: pd.DataFrame) -> Tuple[str, ...]

Parameter Type Default Description
df pd.DataFrame The frame to analyse.

Returns: Tuple[str, ...] — Names of the offending columns, in column order. Empty when every column is safe.

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