Skip to content

API Reference parrot.tools.working_memory.task_memory.blob

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

parrot.tools.working_memory.task_memory.blob

View source

Bounded, immutable artifact blob I/O (FEAT-538, Delivery B).

Implements the durable half of §2 Catalog Backend, Versions, and Evidence: a supported payload that cannot stay in RAM is written once, verified, and only then referenced.

Three rules shape everything here.

Never publish a reference before its bytes exist. :meth:ArtifactBlobStore. publish writes, re-reads and checksum-verifies the blob before returning a :class:BlobRef. Any failure raises and yields no reference at all. An orphan blob left behind by a crash is expected and is swept later; a phantom reference — an index row pointing at bytes that were never written — is unrecoverable, so the ordering is not negotiable.

Blobs are immutable. A version's bytes are written exactly once. The underlying file manager happily overwrites (verified: a second create_from_bytes to the same path succeeds and changes the size), so immutability is enforced here rather than assumed of storage. A re-publish of byte-identical content is accepted as an idempotent retry; a re-publish of different content raises.

A blob checksum is not a content fingerprint. They answer different questions and must never be compared. Parquet encoding is not deterministic across writes, so the same frame yields a different checksum each time while its content fingerprint is stable. :mod:~parrot.tools.working_memory.task_memory.snapshots already provides both with deliberately distinct prefixes (ck_ vs fp_) and this module reuses them rather than hashing anything itself.

Supported formats are Parquet for DataFrames and canonical UTF-8 bytes for JSON and text. Binary and arbitrary objects are refused: there is no canonical content model for them, so a stored digest could not support a completion claim. There is no pickle path and no inline fallback.

.. warning::

Durability depends on the mount, not on this code. LocalFileManager is durable only over a shared, persistent volume visible to every pod. A pod-local directory is not durable, and TempFileManager never is — it is for tests only.

.. note::

Known transport limitation. The pinned file-manager interface (Phase 0 / TASK-2970) has no byte-range read: download_file transfers a whole object. A bounded page read therefore transfers the full encoded blob and then decodes only the requested rows, so the decoded table is bounded but the transfer is not. That is why :attr:ArtifactBlobStore.max_encoded_bytes exists — an object larger than it is refused on its get_file_metadata size before any download starts, rather than being pulled into memory to find out.

Class ArtifactBlobStore

Immutable, verified blob storage for durable task evidence.

Wraps any FileManagerInterface implementation using only the operations Phase 0 pinned against the installed navigator-api: create_from_bytes, download_file, get_file_metadata, exists and delete_file. No streaming or byte-range API is assumed, because the interface has none.

Parameter Type Default Description
file_manager Any Any FileManagerInterface implementation. Durable only over a shared persistent mount; a pod-local directory or TempFileManager is not durable.
prefix str DEFAULT_BLOB_PREFIX Root path segment for every blob.
max_encoded_bytes int DEFAULT_MAX_ENCODED_BYTES Largest encoded object to write or transfer in one operation.

Method ArtifactBlobStore.blob_key

Return the immutable storage key for one artifact version.

Every path component is encoded by :meth:_segment, so a value containing / — or consisting of .. — can neither escape its scope's subtree nor collide with a different scope. The encoding is injective, so distinct scopes always yield distinct keys.

blob_key(scope: TaskScope, ref: EvidenceRef, blob_format: BlobFormat) -> str

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
ref EvidenceRef The exact artifact version.
blob_format BlobFormat Encoding, which fixes the extension.

Returns: str — A storage key of the form {prefix}/{chatbot}/{user}/{session}/{artifact_id}/v{n}.{ext}.

Method ArtifactBlobStore.publish

Write, verify and reference one artifact version's bytes.

The order is the guarantee: encode → write → stat → read back → checksum → then return a reference. Nothing here mutates an index; the caller commits the alias/version row, the evidence metadata and the artifact_registered event together, on one connection, only after this returns.

A retry with byte-identical content succeeds without rewriting.

publish(scope: TaskScope, ref: EvidenceRef, value: Any, *, kind: Optional[ArtifactKind] = None) -> BlobRef

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
ref EvidenceRef The exact artifact version.
value Any The payload.
kind Optional[ArtifactKind] None Force an evidence type instead of detecting one.

Returns: BlobRef — A verified :class:BlobRef.

Raises:

  • UnsupportedBlobPayload — If the value has no canonical durable encoding.
  • LimitExceeded — If the encoded payload exceeds :attr:max_encoded_bytes.
  • BlobImmutabilityError — If a different payload is already stored for this version.
  • BlobPublishError — If the write, the size check or the read-back verification failed. No reference is returned, and the partial object is best-effort removed — an orphan is sweepable either way.

Method ArtifactBlobStore.load

Materialize a stored payload under explicit byte bounds.

Enforcement happens in this order, and the order matters:

  1. max_bytes == 0 refuses immediately — never rehydrate.
  2. The object's get_file_metadata size is checked against :attr:max_encoded_bytes before any download. This is the only bound available on the transfer, because the pinned interface has no byte-range read.
  3. The checksum of the transferred bytes is verified.
  4. For a tabular payload, only the requested rows are decoded.
  5. The decoded size is checked against max_bytes.

A refusal never carries a payload.

load(scope: TaskScope, ref: EvidenceRef, blob: BlobRef, *, 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 artifact version.
blob BlobRef Its verified reference.
max_bytes int Ceiling on the decoded payload. 0 means never materialize.
offset Optional[int] None First row, for a tabular page read.
limit Optional[int] None Row count, for a tabular page read.

Returns: PayloadResult — class:~parrot.interfaces.artifact_store.PayloadResult carrying either the payload or a refusal reason.

Raises:

  • ValueError — If max_bytes is negative, offset is negative, or limit is not positive.

Method ArtifactBlobStore.delete

Delete one version's stored bytes.

Retention calls this only after recording its intent, and only when nothing pins the version.

delete(scope: TaskScope, blob: BlobRef) -> bool

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
blob BlobRef The reference to delete.

Returns: bool — True when bytes were removed, False when there were none to remove. A missing object is not an error: retention retries must be idempotent.

Method ArtifactBlobStore.archive

Copy a blob to an archive location and verify it landed.

Terminal deletion may only proceed after the archive is verified (spec §2 Retention), so this returns a reference only when the copy has been read back and checksummed.

archive(scope: TaskScope, blob: BlobRef, destination_key: str) -> BlobRef

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
blob BlobRef The reference to archive.
destination_key str Archive storage key.

Returns: BlobRef — A verified :class:BlobRef for the archived copy.

Raises:

  • BlobPublishError — If the source cannot be read, or the copy cannot be written and verified. The caller must not treat an unverified archive as permission to delete.

Method ArtifactBlobStore.exists

Whether a blob's bytes are present.

exists(blob: BlobRef) -> bool

Parameter Type Default Description
blob BlobRef The reference to probe.

Returns: bool — True when the object exists.

Method ArtifactBlobStore.scope_prefix

Return the storage sub-tree holding one scope's blobs.

scope_prefix(scope: TaskScope) -> str

Parameter Type Default Description
scope TaskScope Trusted runtime scope.

Returns: str — The prefix, without a trailing separator.

Method ArtifactBlobStore.archive_prefix

Return the sub-tree holding one scope's archived copies.

archive_prefix(scope: TaskScope, *, segment: str = DEFAULT_ARCHIVE_SEGMENT) -> str

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
segment str DEFAULT_ARCHIVE_SEGMENT Archive segment name.

Returns: str — The archive prefix.

Method ArtifactBlobStore.list_stored

Enumerate every object currently stored for a scope.

Uses find_files(prefix=...), which is recursive — verified against the installed navigator implementation, which delegates to Path.rglob. list_files is deliberately not used: it is non-recursive and returns nothing for a directory that holds only sub-directories, so it would report every blob as absent and, through the orphan rule, as sweepable.

list_stored(scope: TaskScope) -> Tuple['StoredBlob', ...]

Parameter Type Default Description
scope TaskScope Trusted runtime scope.

Returns: Tuple['StoredBlob', ...] — class:StoredBlob per object, oldest first. An unreadable or absent prefix yields an empty tuple rather than raising: "I could not list" must never be reported as "there is nothing here", which for a sweeper would be a licence to delete.

Attribute BLOB_CORRUPTED

Type: str

Class BlobError

Base class for blob-storage failures.

Class BlobFormat

On-disk encoding of a stored blob.

Attributes:

Attribute Type Description
extension str File extension for this format.
is_tabular bool Whether this format supports row-bounded page reads.

Class BlobImmutabilityError

A published version's bytes were about to change.

A version is written once. A retry with byte-identical content is accepted silently; anything else is a bug that would retroactively alter evidence a completed step already cites.

Class BlobPublishError

A blob could not be written and verified, so no reference exists.

Raised whenever the write, the size check or the read-back checksum fails. The caller must not record a storage reference: an orphan blob is sweepable, a phantom reference is not.

Class BlobRef

A verified, immutable reference to stored bytes.

Returned only after the bytes have been written and read back successfully, so possessing one of these means the payload exists.

Fields:

Field Type Default Description
key str Storage path, unique per (scope, artifact_id, version).
blob_format BlobFormat How the payload is encoded.
checksum str ck_ digest of the exact stored bytes.
checksum_algorithm str CHECKSUM_ALGORITHM Identity and version of the checksum rules.
byte_size int Size of the stored object.
content_fingerprint Optional[str] None fp_ digest of the logical content, when the payload has a meaningful one. Never compared against :attr:checksum.
fingerprint_algorithm Optional[str] None Identity and version of the fingerprint rules.
kind ArtifactKind ArtifactKind.OBJECT Evidence type the payload was published as.
row_count Optional[int] None Rows in a tabular payload.
compression Optional[str] None Parquet codec, when applicable.

Attribute DEFAULT_ARCHIVE_SEGMENT

Type: str

Attribute DEFAULT_BLOB_PREFIX

Type: str

Attribute DEFAULT_MAX_ENCODED_BYTES

Type: int

Class DurableBlobSweeper

Finds and removes orphan blobs, conservatively.

Implements :class:~.retention.BlobSweeper. A blob is an orphan only when all three references are absent — no live index row, no in-flight publish lease, no archive. Each is checked independently because each fails differently:

  • the index is authoritative but says nothing about a publish that has written its bytes and not yet committed its row;
  • a publish lease covers exactly that window;
  • an archive is a reference with deliberately no index row, so a sweeper that only consulted the index would delete every archive.

Every uncertainty resolves to "not an orphan". A blob wrongly kept is swept on the next pass once the doubt clears; a blob wrongly deleted is gone.

Parameter Type Default Description
blobs 'ArtifactBlobStore' The blob store, for enumeration and deletion.
live_refs Any Async callable returning the storage keys the index still references for a scope.
publish_lease Optional[Any] None Optional async predicate answering "is a publish in flight for this key?". Without one, no key is treated as leased — so wire it in any deployment where a publish can race a sweep.
archive_segment str DEFAULT_ARCHIVE_SEGMENT Path segment marking archived copies.
clock Optional[Any] None Injected clock.

Method DurableBlobSweeper.list_orphans

Return candidate orphans with their reference flags resolved.

list_orphans(scope: TaskScope) -> Tuple[Any, ...]

Parameter Type Default Description
scope TaskScope Trusted runtime scope.

Returns: Tuple[Any, ...] — One BlobRetentionView per stored object. The grace period is applied by the pure selector, not here.

Method DurableBlobSweeper.sweep

Delete one orphan blob.

sweep(scope: TaskScope, storage_ref: str) -> bool

Parameter Type Default Description
scope TaskScope Trusted runtime scope.
storage_ref str The object to delete.

Returns: bool — True when bytes were removed. A missing object returns False rather than raising, so a retry after a partial sweep converges.

Attribute PARQUET_COMPRESSION

Type: str

Class StoredBlob

One object found in storage, independent of any index row.

Parameter Type Default Description
key str
byte_size int 0
modified_at Optional[datetime] None

Fields:

Field Type Default Description
key str Its storage path.
byte_size int 0 Size in bytes.
modified_at Optional[datetime] None Last modification time, when storage reports one.

Class UnsupportedBlobPayload

A value has no safe durable encoding.

Binary blobs and arbitrary objects reach this: there is no canonical content model for them, so nothing stored could later support a completion claim. Refusing is the point — an inline or pickle fallback would produce durable bytes that prove nothing.

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