Skip to content

API Reference parrot.bots.flows.core.checkpoint.serializer

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

parrot.bots.flows.core.checkpoint.serializer

View source

FlowStateSerializer — type registry + ormsgpack (FEAT-399, TASK-2047).

Hybrid serialization for checkpoint payloads: registered Pydantic models round-trip with type identity via a small type registry; everything else degrades to a tagged repr and marks the operation lossy instead of raising. Never pickle (spec §2/§7).

Alias AIMessage

Re-exported from parrot.models.responses.AIMessage.

Class FlowStateSerializer

Encode/decode checkpoint payloads with a Pydantic type registry.

Registered model classes are encoded as {"__type__": tag, "data": model.model_dump(mode="json")} and reconstructed via model_cls.model_validate() on decode. Unregistered objects (including unregistered Pydantic models) degrade to {"__type__": "lossy", "__repr__": repr(obj)} — this never raises and instead signals the degradation via encode_with_meta()'s lossy flag.

Exception/BaseException instances are always encoded as a structured {"type": ..., "message": ..., "repr": ...} dict — never as reconstructable objects (spec §7: FlowContext.errors holds live Exceptions; checkpoints must never attempt to rebuild them on resume).

datetime/uuid.UUID are explicitly tagged (not left to ormsgpack's own encoding) — ormsgpack.unpackb() does not restore them to their original type on its own, it returns plain strings, so without tagging they would silently lose type fidelity (never flagged lossy, since the round-trip technically "succeeds").

A plain dict whose own keys happen to collide with the reserved "__type__" sentinel (e.g. a tool result naturally shaped like {"__type__": "lossy", ...}) is escaped in a tagged wrapper on encode so decode() can tell a real envelope apart from user data that merely looks like one, instead of misinterpreting it.

Attributes:

Attribute Type Description
registry dict[str, type[BaseModel]] The types this serializer round-trips, process-wide defaults included.

Method FlowStateSerializer.register

Register a Pydantic model class under a type tag (instance-local).

register(model_cls: type[BaseModel], tag: str | None = None) -> str

Parameter Type Default Description
model_cls type[BaseModel] The Pydantic BaseModel subclass to register.
tag str | None None Optional explicit type tag; defaults to the fully qualified class name (module.QualName).

Returns: str — The tag the class was registered under.

Method FlowStateSerializer.encode_error

Encode an exception as a structured, JSON-safe dict.

encode_error(exc: BaseException) -> dict[str, str]

Parameter Type Default Description
exc BaseException The exception instance to encode.

Returns: dict[str, str] — {"type": ClassName, "message": str(exc), "repr": repr(exc)}.

Method FlowStateSerializer.encode_with_meta

Encode obj to ormsgpack bytes, reporting lossy degradation.

encode_with_meta(obj: Any) -> tuple[bytes, bool]

Parameter Type Default Description
obj Any Arbitrary structure (dict/list/Pydantic model/primitive).

Returns: tuple[bytes, bool] — Tuple of (packed_bytes, lossy) where lossy is True if any value in the structure degraded to a tagged repr.

Method FlowStateSerializer.to_safe_with_meta

Recursively convert obj into a JSON-safe structure.

This is the per-value transform step used internally by encode_with_meta() before the final ormsgpack packb() — it applies the same type-registry tag-enveloping and lossy degradation, but stops short of byte-packing. Callers that need a JSON-safe (dict/list/primitive) representation of arbitrary per-node values — e.g. ContextSnapshot.results/.responses, which are typed dict[str, Any] and are packed again as part of the whole checkpoint by the store layer — use this instead of encode_with_meta() to avoid double-encoding to bytes.

to_safe_with_meta(obj: Any) -> tuple[Any, bool]

Parameter Type Default Description
obj Any Arbitrary structure (dict/list/Pydantic model/primitive).

Returns: tuple[Any, bool] — Tuple of (safe_structure, lossy).

Method FlowStateSerializer.from_safe

Reconstruct values produced by to_safe_with_meta().

from_safe(safe: Any) -> Any

Parameter Type Default Description
safe Any A JSON-safe structure previously produced by to_safe_with_meta().

Returns: Any — The reconstructed structure — registered models rebuilt via model_validate, lossy envelopes replaced by their repr string, everything else returned as plain dict/list/primitives.

Method FlowStateSerializer.encode

Encode obj to ormsgpack bytes (discarding the lossy flag).

encode(obj: Any) -> bytes

Parameter Type Default Description
obj Any Arbitrary structure (dict/list/Pydantic model/primitive).

Returns: bytes — The packed bytes.

Method FlowStateSerializer.decode

Decode ormsgpack bytes produced by encode/encode_with_meta.

decode(data: bytes) -> Any

Parameter Type Default Description
data bytes Packed bytes.

Returns: Any — The reconstructed structure: registered models rebuilt via model_validate, lossy envelopes replaced by their repr string, everything else returned as plain dict/list/primitives.

Attribute logger

Function register_checkpoint_type

Register a Pydantic type for every :class:FlowStateSerializer instance.

Without this a model is not an error — it degrades to its repr and the checkpoint is flagged lossy. That is a reasonable default for a payload nobody reads back, and a silent problem for a flow that routes on a node's typed result, or a resume path that needs to restore a typed dev-loop output (ResearchOutput, DevelopmentOutput, ...).

Idempotent: re-registering the exact same class (or the same module.QualName re-imported as a fresh class object — a legitimate module-reload scenario some test suites exercise deliberately, e.g. del sys.modules[...] + re-import to verify lazy-import boundaries) under the same tag is a no-op / refresh. Registering a genuinely different class (a different qualified name) under a tag already claimed by another class raises, since silently rebinding the tag would make every already-persisted checkpoint referencing it decode as the wrong type.

register_checkpoint_type(model_cls: type[BaseModel], tag: str | None = None) -> str

Parameter Type Default Description
model_cls type[BaseModel] The Pydantic BaseModel subclass to register.
tag str | None None Optional explicit type tag; defaults to the fully qualified class name (module.QualName).

Returns: str — The tag the class was registered under.

Raises:

  • ValueError — If tag is already registered to a class with a different (__module__, __qualname__) — a genuine conflict, not a reload of the same class.

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