Skip to content

API Reference parrot.tools.repl_worker.protocol

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

parrot.tools.repl_worker.protocol

View source

Control protocol for the persistent REPL worker (FEAT-380 Module 2).

Length-prefixed Pydantic messages exchanged between the host (PythonREPLTool / WorkerHandle, TASK-1941+) and the persistent REPL worker process spawned by worker.py. One message per request/response, framed as a 4-byte big-endian unsigned length prefix followed by the message's JSON payload (spec Sandbox Hardening §2 "Control Protocol").

Values that are not natively JSON-serializable (e.g. a DataFrame passed to set_var) are wrapped with :func:encode_value / :func:decode_value — a pickle+base64 fallback, the same "works for everything, fast for nothing" posture the spec calls for on the DataFrame transport (G9). Zero-copy Arrow IPC / shared-memory transport for DataFrames is TASK-1945; this task only guarantees some value makes it across the wire for get_var/set_var/ snapshot.

Class ErrorResponse

Worker -> host: generic error envelope (unknown/unimplemented op, dispatch failure).

Fields:

Field Type Default Description
op Literal['error'] 'error'
message str

Class ExecRequest

Host -> worker: execute code under a deadline.

Fields:

Field Type Default Description
op Literal['exec'] 'exec'
code str
debug bool False
deadline_ms int

Class ExecResult

Worker -> host: mirrors today's _execute() contract (G5).

Fields:

Field Type Default Description
op Literal['result'] 'result'
output str | None None
status str | None None
result Any | None None
error str | None None
new_vars list[str]

Class GetVarRequest

Host -> worker: read one namespace variable (namespace API).

Fields:

Field Type Default Description
op Literal['get_var'] 'get_var'
name str

Class InjectDfRequest

Host -> worker: inject a DataFrame into the namespace.

Implemented by TASK-1945: Arrow IPC over shared memory as the primary transport (format="arrow"), pickle+base64 as the fallback (format="pickle") for dtypes Arrow cannot represent (spec G9).

FEAT-538 adds an opt-in strict mode for task-memory evidence. It is off by default, so the legacy wire shape and behaviour are unchanged for every existing caller.

Fields:

Field Type Default Description
op Literal['inject_df'] 'inject_df'
name str
format Literal['arrow', 'pickle'] 'arrow'
shm_name Optional[str] None
size Optional[int] None
payload Optional[str] None
strict bool False
envelope Optional[TransportEnvelope] None

Class ListNsRequest

Host -> worker: cheap, name-only namespace listing (host name-shadow feed).

Fields:

Field Type Default Description
op Literal['list_ns'] 'list_ns'

Class ListNsResponse

Worker -> host: reply to :class:ListNsRequest.

Fields:

Field Type Default Description
op Literal['list_ns_result'] 'list_ns_result'
names list[str]

Class MemoryVerdict

Recorded by ProcessObserver when a worker crosses the hard RSS limit.

Fields:

Field Type Default Description
cause Literal['memory'] 'memory' Always "memory" — matches NamespaceLossError.cause.
rss int Measured RSS, in bytes, at the moment of the breach.
limit int The memory_hard_limit_bytes that was crossed.

Class NamespaceLossError

Payload embedded in the {status, result, error} dict after a kill.

Constructed host-side (TASK-1941+ owns deadline/SIGKILL enforcement); defined here because it is part of the frozen protocol contract (spec §2 Data Models).

Fields:

Field Type Default Description
cause Literal['timeout', 'memory', 'crash']
lost_variables list[str]
message str

Class OkResponse

Worker -> host: generic acknowledgement (set_var, reset).

Fields:

Field Type Default Description
op Literal['ok'] 'ok'

Class PingRequest

Host -> worker: health check.

Fields:

Field Type Default Description
op Literal['ping'] 'ping'

Class PongResponse

Worker -> host: reply to :class:PingRequest.

Fields:

Field Type Default Description
op Literal['pong'] 'pong'

Class ProcessSample

One point-in-time reading of a worker process' vitals.

Fields:

Field Type Default Description
t float time.monotonic() timestamp of the sample.
cpu_s float Cumulative user + system CPU seconds at sample time.
rss int Resident set size, in bytes.
state str psutil process status ("running", "sleeping", ...).
wchan str '' Linux-only kernel wait channel (/proc/<pid>/wchan); empty elsewhere or when unavailable.
threads int 0 Live thread count.

Class ReadyResponse

Worker -> host: the readiness handshake frame (FEAT-500).

The very first frame a worker writes, emitted after its :class:~parrot.tools.repl_worker.worker.WorkerNamespace has finished constructing (framework + pandas import + REPL bootstrap) and before it enters its service loop. The host arms a readiness future in WorkerHandle.start() and refuses to write any request frame until this frame has been read, so no caller can ever hit a still-booting worker (spec G1/AC1).

Fields:

Field Type Default Description
op Literal['ready'] 'ready' Frame discriminator, always "ready".
pid int The worker process' own pid, for log/error correlation.
bootstrap_ms int Monotonic milliseconds from the worker's main() entry to the moment the namespace became usable.

Class ResetRequest

Host -> worker: reset the REPL environment (equivalent to reset_environment()).

Fields:

Field Type Default Description
op Literal['reset'] 'reset'

Class SetVarRequest

Host -> worker: write one namespace variable (namespace API).

Fields:

Field Type Default Description
op Literal['set_var'] 'set_var'
name str
value Any None

Class SnapshotRequest

Host -> worker: serializable dump of the whole namespace.

Fields:

Field Type Default Description
op Literal['snapshot'] 'snapshot'

Class SnapshotResponse

Worker -> host: reply to :class:SnapshotRequest.

Fields:

Field Type Default Description
op Literal['snapshot_result'] 'snapshot_result'
data dict[str, Any]

Class TransportEnvelope

Bounded runtime context carried across the REPL process boundary (FEAT-538).

Only a bounded envelope crosses the boundary — never a live task context object. Every field is revalidated on return: scope drift is a hard boundary violation, while task, generation or fencing drift means the binding is stale and the artifact must be re-resolved rather than trusted.

Fields:

Field Type Default Description
scope_key str Opaque, collision-safe encoding of the trusted scope.
task_id Optional[str] None The selected task at the time of the request.
artifact_id Optional[str] None Identity of the artifact being materialized.
version Optional[int] None Exact version of that artifact. A binding is to a version, never to a mutable alias.
worker_generation Optional[str] None Identity of the worker generation the caller believes it is talking to. A PID alone is not a generation identity — a recycled PID would masquerade as the same worker.
fencing_token Optional[int] None Monotonic token used to reject a late reply from a superseded owner.

Class ValueResponse

Worker -> host: reply to :class:GetVarRequest.

Fields:

Field Type Default Description
op Literal['value'] 'value'
name str
value Any None

Attribute Verdict

Class WorkerConfig

Deployment-tunable limits (all with working defaults).

Timeout budgets (FEAT-500): bootstrap_timeout_ms: How long the host waits for the worker's :class:ReadyResponse frame after spawning it. Expiry is lethal: a process that cannot finish bootstrapping within this budget is not a live worker, so it is killed and every waiter receives a WorkerBootstrapError (spec §2, Q1). namespace_timeout_ms: Budget for every non-exec request (get_var/set_var/list_vars/snapshot/reset/ inject_dataframe). Expiry is non-lethal: the caller gets a NamespaceTimeoutError with a real message, the worker stays alive and its namespace is preserved (spec G2/U2). Only deadline_ms (the execute() deadline) still kills.

Fields:

Field Type Default Description
rlimit_as_bytes int 12 * 1024 ** 3
rlimit_cpu_seconds int 300
rlimit_nofile int 256
deadline_ms int 60000
max_workers int 0
idle_ttl_seconds int 1800
prewarm_pool_size int 2
bootstrap_timeout_ms int 30000
namespace_timeout_ms int 30000
observer_poll_ms int 500
stall_window_ms int 5000
bootstrap_stall_ms int 0
interrupt_before_kill bool True
interrupt_grace_ms int 2000
memory_soft_limit_bytes int 4 * 1024 ** 3
memory_hard_limit_bytes int 8 * 1024 ** 3
host_memory_reserve_bytes int 2 * 1024 ** 3

Function decode_snapshot

Decode a SnapshotResponse.data mapping one entry at a time.

One value the insecure-deserialization guard refuses (e.g. an altair Chart, whose pickle references a module outside the allowlist) must not cost the caller every other variable. Such an entry is replaced by an inert placeholder string and a warning is logged; no object is ever constructed for it. Any other exception propagates unchanged.

decode_snapshot(data: dict[str, Any]) -> dict[str, Any]

Parameter Type Default Description
data dict[str, Any] The worker's {name: encode_value(value)} mapping.

Returns: dict[str, Any] — {name: decoded value or placeholder}.

Function decode_value

Inverse of :func:encode_value.

decode_value(value: Any) -> Any

Parameter Type Default Description
value Any A JSON-safe value previously produced by :func:encode_value.

Returns: Any — The original Python value (unpickled if it was pickle-wrapped).

Function encode_value

Best-effort JSON-safe encoding for one namespace value.

Native JSON types (None/bool/int/float/str and list/dict composed of them) pass through unchanged. Anything else (DataFrames, custom objects, …) is pickled and base64-wrapped so it can still travel inside the JSON frame.

encode_value(value: Any) -> Any

Parameter Type Default Description
value Any The namespace value to encode.

Returns: Any — A JSON-serializable representation of value.

Attribute logger

Function read_frame

Read one length-prefixed protocol message from stream.

read_frame(stream: BinaryIO) -> BaseModel

Parameter Type Default Description
stream BinaryIO Binary stream to read from.

Returns: BaseModel — The parsed Pydantic protocol message.

Raises:

  • EOFError — the stream closed before a full frame was read.
  • ValueError — the payload's op field is not a known message type.

Function write_frame

Write one length-prefixed protocol message to stream.

Frame layout: 4-byte big-endian unsigned length, followed by the message's JSON payload (the op field is included, so the reader can dispatch without an out-of-band schema).

write_frame(stream: BinaryIO, message: BaseModel) -> None

Parameter Type Default Description
stream BinaryIO Binary stream to write to (flushed after writing).
message BaseModel The Pydantic protocol message to send.

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