Skip to content

API Reference parrot.tools.repl_worker.handle

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

parrot.tools.repl_worker.handle

View source

Host-side handle to one per-session REPL worker process (FEAT-380 Module 3).

WorkerHandle owns the async, host-side half of the control protocol (protocol.py) and the child process spawned via python -m parrot.tools.repl_worker.worker (worker.py, TASK-1940). This is where the feature's core guarantee lives: the host enforces deadline_ms — if the worker does not answer in time, SIGKILL (G2/AC2).

The handle also maintains a cheap, names-only shadow of the worker's namespace (refreshed from ExecResult.new_vars and list_ns) so that after a kill it can tell the LLM exactly which variables were just lost (AC11), with the cause differentiated as "timeout" / "memory" / "crash".

Prewarming, the worker pool, TTL eviction and the concurrency ceiling are TASK-1942 (WorkerPool) — this module only owns ONE worker's lifecycle.

Alias ExecRequest

Re-exported from parrot.tools.repl_worker.protocol.ExecRequest.

Alias ExecResult

Re-exported from parrot.tools.repl_worker.protocol.ExecResult.

Alias GetVarRequest

Re-exported from parrot.tools.repl_worker.protocol.GetVarRequest.

Alias InjectDfRequest

Re-exported from parrot.tools.repl_worker.protocol.InjectDfRequest.

Alias ListNsRequest

Re-exported from parrot.tools.repl_worker.protocol.ListNsRequest.

Alias ListNsResponse

Re-exported from parrot.tools.repl_worker.protocol.ListNsResponse.

Alias MemoryVerdict

Re-exported from parrot.tools.repl_worker.protocol.MemoryVerdict.

Alias NamespaceLossError

Re-exported from parrot.tools.repl_worker.protocol.NamespaceLossError.

Class NamespaceTimeoutError

A non-exec request timed out; the worker is still ALIVE (FEAT-500).

Only the execute() deadline kills a worker (spec G2/U2). Every other request — get_var/set_var/list_vars/snapshot/reset/ inject_dataframe/ping — raises this instead: the process keeps running, its namespace is preserved, and the late reply is parked and drained before the next request is written. Subclasses TimeoutError so existing broad except TimeoutError callers keep working, but unlike the bare asyncio.TimeoutError it always carries a human-readable message (spec G3).

Alias PingRequest

Re-exported from parrot.tools.repl_worker.protocol.PingRequest.

Alias PongResponse

Re-exported from parrot.tools.repl_worker.protocol.PongResponse.

Alias ProcessObserver

Re-exported from parrot.tools.repl_worker.observer.ProcessObserver.

Alias ReadyResponse

Re-exported from parrot.tools.repl_worker.protocol.ReadyResponse.

Alias ResetRequest

Re-exported from parrot.tools.repl_worker.protocol.ResetRequest.

Alias SetVarRequest

Re-exported from parrot.tools.repl_worker.protocol.SetVarRequest.

Alias SnapshotRequest

Re-exported from parrot.tools.repl_worker.protocol.SnapshotRequest.

Alias SnapshotResponse

Re-exported from parrot.tools.repl_worker.protocol.SnapshotResponse.

Alias TransportEnvelope

Re-exported from parrot.tools.repl_worker.protocol.TransportEnvelope.

Alias ValueResponse

Re-exported from parrot.tools.repl_worker.protocol.ValueResponse.

Class WorkerBootstrapError

The worker never sent its :class:ReadyResponse in time (FEAT-500).

Raised by :meth:WorkerHandle.wait_ready (and therefore by the first :meth:WorkerHandle._send) when a worker fails to finish bootstrapping within WorkerConfig.bootstrap_timeout_ms, or dies / speaks out-of-protocol while doing so. The process has already been killed by the time this is raised: a child that cannot boot is not a live worker (spec §2, Q1). The message always names the pid, the budget, the observed cause and the tail of the worker's stderr.

Alias WorkerConfig

Re-exported from parrot.tools.repl_worker.protocol.WorkerConfig.

Class WorkerHandle

Host-side handle to one per-session REPL worker process.

Parameter Type Default Description
config Optional[WorkerConfig] None Resource-limit / lifecycle configuration for the worker. Defaults to WorkerConfig().
output_dir Optional[str] None Shared output directory for plots/reports, visible to both host and worker.
repl_kwargs Optional[dict[str, Any]] None Extra PythonREPLTool constructor kwargs to mirror on the worker's internal instance (e.g. return_plot_as_base64, TASK-1943) — session config distinct from WorkerConfig's resource-limit fields.
executor Optional[concurrent.futures.Executor] None Dedicated executor for this handle's blocking I/O (pipe read/write, subprocess spawn/kill, Arrow encode). Code-review fix (post-TASK-1945/AC1): every blocking call here previously used run_in_executor(None, ...) — the framework's SHARED default executor, exactly what Module 1 (TASK-1939, PythonREPLTool._repl_executor) exists to stop hijacking. Defaults to a small, self-owned ThreadPoolExecutor (shut down in :meth:kill) so even standalone WorkerHandle usage never falls back to the shared pool; PythonREPLTool/WorkerPool pass their own dedicated executor through explicitly.

Attributes:

Attribute Type Description
observer Optional[ProcessObserver]
known_vars list[str]
is_alive bool Whether the child process is still running.
is_ready bool Whether the worker has signalled readiness and can serve requests.
generation str Stable identity of this worker generation (FEAT-538). A REPL binding records this value. When a binding is presented against a handle whose generation differs, the binding is stale and the artifact must be re-resolved — the persisted artifact is still perfectly locatable, only the binding is invalid. Deliberately not the pid: the OS recycles pids, so a fresh worker could otherwise masquerade as the one the binding was made against.

Method WorkerHandle.start

Spawn the worker process (spawn-only — never fork, see spec).

start() -> None

Method WorkerHandle.wait_ready

Await the worker's readiness handshake.

Safe to call from any number of callers and any number of times: they all await the same one-shot future, and a bootstrap failure is re-raised to every one of them.

wait_ready(timeout_s: float | None = None) -> ReadyResponse

Parameter Type Default Description
timeout_s float | None None Optional extra ceiling on top of the handle's own bootstrap_timeout_ms budget. None (the default) waits for that budget to play out.

Returns: ReadyResponse — The worker's :class:ReadyResponse (pid + measured bootstrap ms).

Raises:

  • WorkerBootstrapError — the worker never became ready (it has already been killed), or start() was never called.
  • asyncio.TimeoutError — timeout_s elapsed while the worker was still booting (the worker is left alone — this is the caller's own ceiling, not the bootstrap budget).

Method WorkerHandle.interrupt

Send SIGINT and wait up to interrupt_grace_ms for the reply (spec G3).

Namespace-preserving alternative to an immediate SIGKILL on a deadline_ms breach: signals go through _lifecycle_executor, never the pipe-reading _executor (same rule as :meth:_kill_process — the kill/signal path must never queue behind a blocked read). Awaits self._inflight_reply — the SAME round-trip future :meth:_send is already waiting on — rather than issuing a second read against the control pipe, which the strictly ordered protocol does not allow.

Never sends SIGINT on a non-POSIX host (send_signal(SIGINT) is unreliable there without a shared console — spec AC11: "interrupt disabled" off-POSIX), when the process is already dead, or when the observer's verdict shows the worker is not actually busy ("settled"/"booting"/"unavailable") — a worker that isn't mid-request has nothing productive to interrupt.

interrupt() -> bool

Returns: bool — True if a reply frame arrived within interrupt_grace_ms (the worker's namespace survives); False if SIGINT was skipped, the grace period elapsed, or the worker died instead of answering — the caller should fall back to meth:_kill_process.

Method WorkerHandle.death_summary

Why this worker is (or might be) dead, for logs and diagnostics.

Public accessor added so callers — notably WorkerPool's restart-loop warning — do not have to reach into _proc / _stderr_tail across the module boundary (code-review finding).

death_summary() -> tuple[int | None, str]

Returns: tuple[int | None, str] — (exit_code, stderr_tail): the process' exit code (None if it was never spawned or is still running) and the most recent stderr line the drain task captured ("" if there is none).

Method WorkerHandle.execute

Execute code in the worker under deadline_ms.

execute(code: str, debug: bool = False) -> str | dict

Parameter Type Default Description
code str Python source to run in the persistent REPL namespace.
debug bool False Enable debug mode (mirrors PythonREPLTool's flag).

Returns: str | dict — The execution output string on success, or a {status, result, error} dict on error/timeout/crash — the same G5 contract PythonREPLTool._execute() returns today.

Method WorkerHandle.inject_dataframe

Inject a DataFrame into the worker namespace via Arrow IPC/shm (TASK-1945).

Encodes df (Arrow IPC into a shared-memory block, or pickle as a logged fallback for dtypes Arrow can't represent — see transport.py), sends it to the worker, and unlinks the shm block only after the worker's ACK (the framed response below) — see transport.py's module docstring for the full shm ownership contract.

inject_dataframe(name: str, df: Any, *, strict: bool = False, envelope: Optional[TransportEnvelope] = None, max_bytes: Optional[int] = None) -> None

Parameter Type Default Description
name str Variable name to bind the DataFrame to.
df Any The pandas.DataFrame to inject.
strict bool False FEAT-538 opt-in strict evidence transport. When True, an unsupported dtype raises :class:~.transport.StrictTransportError before any pickle payload is created, the encoded size is checked against max_bytes, and the worker independently refuses a non-Arrow strict frame. Defaults to False, which preserves the legacy behaviour exactly.
envelope Optional[TransportEnvelope] None Bounded runtime context to carry across the process boundary, revalidated on return.
max_bytes Optional[int] None Strict-mode ceiling for the encoded stream.

Raises:

  • StrictTransportError — In strict mode, when the value cannot travel safely. No shared-memory block is left behind.

Method WorkerHandle.get_var

Read one namespace variable from the worker.

A value the insecure-deserialization guard refuses comes back as the same inert placeholder string snapshot() uses, never as a raised UnpicklingError. One untransportable variable must not fail the caller's whole turn: PandasAgent reads result variables through this method, so a raise here surfaces to the end user as a failed answer instead of a missing dataset.

get_var(name: str) -> Any

Parameter Type Default Description
name str The namespace variable to read.

Returns: Any — The decoded value, or a placeholder string when the guard refused it.

Method WorkerHandle.set_var

Write one namespace variable in the worker.

set_var(name: str, value: Any) -> None

Parameter Type Default Description
name str
value Any

Method WorkerHandle.list_vars

Refresh and return the cheap, names-only namespace shadow.

list_vars() -> list[str]

Returns: list[str]

Method WorkerHandle.snapshot

Return a serializable dump of the whole worker namespace.

Guard-refused entries come back as placeholder strings (see protocol.decode_snapshot).

snapshot() -> dict[str, Any]

Returns: dict[str, Any]

Method WorkerHandle.reset

Reset the worker's REPL environment (equivalent to reset_environment()).

reset() -> None

Method WorkerHandle.ping

Health check. Returns True on a live, responsive worker.

ping(timeout_s: float = 10.0) -> bool

Parameter Type Default Description
timeout_s float 10.0 How long to wait for a pong. Defaults to 10s rather than a tight value — a freshly-start()ed worker is still importing pandas/numpy/matplotlib and running its bootstrap, which can legitimately take several seconds under load, and a ping sent right after start() must not be misreported as "unhealthy" just because it raced the worker's own bootstrap.

Returns: bool

Method WorkerHandle.kill

Terminate the worker process, its drain task, and the control pipes.

Deliberately does NOT take self._lock before killing: an in-flight _send() holds that lock for the entire duration of its blocking read (parked in an executor thread, potentially for up to deadline_ms) — taking the same lock here would deadlock kill() against exactly the in-flight call it needs to be able to interrupt. Killing the OS process directly (unsynchronized) is safe: it makes the worker's end of the pipe close, so a concurrent _send()'s blocked read observes EOF and resolves via its own (EOFError, OSError, ValueError) handling — a possible ValueError: I/O operation on closed file from closing the host's own stream objects here while another thread reads them is caught by that same handler. Only the OS-level kill matters for correctness; the stream-close below is opportunistic cleanup.

kill() -> None

Alias decode_snapshot

Re-exported from parrot.tools.repl_worker.protocol.decode_snapshot.

Alias decode_value

Re-exported from parrot.tools.repl_worker.protocol.decode_value.

Alias encode_value

Re-exported from parrot.tools.repl_worker.protocol.encode_value.

Attribute logger

Function probe_process_state

Best-effort one-line snapshot of a live process from /proc (Linux).

Bootstrap diagnostics (post-FEAT-500): quoted in WorkerBootstrapError when a worker never sends its ready frame, so the error says whether the child was stopped (T: SIGSTOP/SIGTTOU/debugger), sleeping on a kernel wait channel (S + wchan), starved of CPU (R with a tiny cpu=), or thrashing (huge VmPeak). Never raises.

The /proc parsing itself moved to observer.py (FEAT-521 TASK-2775, reused by ProcessObserver's continuous sampling); this function is now a thin compatibility wrapper preserving its original signature and return-value contract for existing callers.

probe_process_state(pid: int | None) -> str

Parameter Type Default Description
pid int | None The process to inspect; None or a non-Linux host yields "".

Returns: str — "state=... threads=... vmpeak=... wchan=... cpu=...s" or "" when unavailable.

Alias read_frame

Re-exported from parrot.tools.repl_worker.protocol.read_frame.

Alias read_proc_cpu_seconds

Re-exported from parrot.tools.repl_worker.observer.read_proc_cpu_seconds.

Alias read_proc_status

Re-exported from parrot.tools.repl_worker.observer.read_proc_status.

Alias read_proc_wchan

Re-exported from parrot.tools.repl_worker.observer.read_proc_wchan.

Alias write_frame

Re-exported from parrot.tools.repl_worker.protocol.write_frame.

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