Skip to content

API Reference parrot.tools.repl_worker.worker

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

parrot.tools.repl_worker.worker

View source

REPL worker process entrypoint (FEAT-380 Sandbox Hardening — Module 2).

Spawn-only child process (never fork — connection pools and parent threads do not tolerate it) that hosts one persistent PythonREPLTool instance for the lifetime of one REPL session. Resource limits are applied first thing in :func:main, before the heavy pandas/numpy imports PythonREPLTool pulls in.

The static allowlist + AST denylist gate is revalidated here too — reusing PythonREPLTool._execute_code(..., enforce_security=True) as-is (see :class:WorkerNamespace) is what provides that revalidation; it is defence in depth alongside the host's own gate check before code is ever sent over (spec G6 / AC6).

The service loop speaks the length-prefixed protocol defined in protocol.py over two binary streams — a dedicated pipe (spec §2: "pipe dedicado"), never stdin/stdout (see :func:main). Host-side spawn/kill/deadline-SIGKILL enforcement and the prewarmed worker pool (WorkerHandle / WorkerPool) are TASK-1941/1942 — this module only owns the child side of the control channel.

Alias ErrorResponse

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

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 OkResponse

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

Alias PingRequest

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

Alias PongResponse

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

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 ValueResponse

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

Alias WorkerConfig

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

Class WorkerNamespace

Owns the persistent PythonREPLTool instance for this worker process.

Deliberately reuses PythonREPLTool rather than re-implementing _execute_code / _describe_new_var in this module: the spec requires those move "as-is" (§2 Overview — "es el corazón y no se reescribe"). Running the real class inside the worker process guarantees zero behavioural drift versus a hand-copied fork that could diverge over time ("Behavior differences vs the current REPL are bugs").

One instance per worker PROCESS also fixes the _bootstrapped class-variable bug (AC14) for free: _bootstrapped is still a class variable on PythonREPLTool, but each spawned worker is a fresh interpreter, so it starts False again in every worker — no code change to pythonrepl.py was needed to get per-worker bootstrap.

Parameter Type Default Description
output_dir Optional[str] None
sanitize_input_enabled bool True
repl_kwargs Optional[dict[str, Any]] None

Method WorkerNamespace.exec

Run one code snippet through the tool's real gate + execution engine.

exec(request: ExecRequest) -> ExecResult

Parameter Type Default Description
request ExecRequest The framed exec request from the host.

Returns: ExecResult — class:ExecResult mirroring PythonREPLTool._execute()'s return-contract classification (G5). A KeyboardInterrupt (host-side SIGINT on deadline_ms expiry, spec G3) is caught here and converted into a bounded status="error" result instead of propagating — the worker process, and its namespace, survive the interruption.

Method WorkerNamespace.list_ns

Cheap, name-only namespace shadow (feeds the host's list_ns).

list_ns() -> list[str]

Returns: list[str]

Method WorkerNamespace.get_var

Read one namespace variable.

get_var(name: str) -> Any

Parameter Type Default Description
name str

Returns: Any

Method WorkerNamespace.set_var

Write one namespace variable (mirrored into both locals and globals).

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

Parameter Type Default Description
name str
value Any

Method WorkerNamespace.snapshot

Serializable dump of the namespace (modules/callables skipped).

snapshot() -> dict[str, Any]

Returns: dict[str, Any]

Method WorkerNamespace.reset

Reset the REPL environment (equivalent to reset_environment()).

reset() -> None

Function apply_rlimits

Apply POSIX resource limits to the CURRENT process.

Must run before any user code executes — and, per the Key Constraint, before the heavy pandas/numpy imports too. Best-effort skip on non-POSIX platforms (Windows) with a visible log line rather than a silent no-op (spec AC16: the Windows degradation must be documented, never hidden).

apply_rlimits(config: WorkerConfig) -> None

Parameter Type Default Description
config WorkerConfig Deployment-tunable resource limits for this worker.

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 main

python -m parrot.tools.repl_worker.worker entrypoint.

Usage::

python -m parrot.tools.repl_worker.worker \
    '<WorkerConfig JSON>' <control_read_fd> <control_write_fd> \
    [output_dir] ['<repl_kwargs JSON>']

The control channel is a dedicated pipe (spec §2 Control Protocol: "pipe dedicado"), never stdin/stdout: this framework's own logging setup (navconfig) attaches a colorized StreamHandler to stdout for every logger — including self.logger.debug/info(...) calls made while PythonREPLTool bootstraps — which would silently corrupt a stdin/stdout-framed binary protocol. The parent (WorkerHandle, TASK-1941) creates two os.pipe() pairs and passes the child's ends via subprocess.Popen(pass_fds=(...)); this process re-opens them by fd number. stdin/stdout/stderr stay free for any incidental library output.

Rlimits are applied from the config given on argv BEFORE any heavy import happens (WorkerNamespace is only constructed inside :func:serve, after :func:apply_rlimits has already run).

main(argv: Optional[list[str]] = None) -> None

Parameter Type Default Description
argv Optional[list[str]] None Command-line arguments (defaults to sys.argv[1:]).

Alias read_frame

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

Function serve

Run the worker service loop: read one framed request, write one framed reply.

Runs until in_stream closes (EOF). Host-side kill/deadline logic (TASK-1941) is what tears the process down on a timeout — this loop never decides to stop on its own except on a clean EOF.

serve(config: WorkerConfig, in_stream: BinaryIO, out_stream: BinaryIO, output_dir: Optional[str] = None, repl_kwargs: Optional[dict[str, Any]] = None, started_at: float | None = None) -> None

Parameter Type Default Description
config WorkerConfig This worker's resource-limit / lifecycle configuration.
in_stream BinaryIO Binary stream carrying host -> worker frames.
out_stream BinaryIO Binary stream carrying worker -> host frames.
output_dir Optional[str] None Shared output directory for plots/reports (visible to both host and worker); None uses PythonREPLTool's default.
repl_kwargs Optional[dict[str, Any]] None Extra PythonREPLTool constructor kwargs to mirror on this worker's internal instance (e.g. return_plot_as_base64, TASK-1943) — session config that shapes execution behaviour, distinct from WorkerConfig's resource-limit/lifecycle fields.
started_at float | None None time.monotonic() sampled at :func:main entry, used to report bootstrap_ms in the readiness frame (FEAT-500). None (callers invoking serve() directly, e.g. tests) reports 0.

Function set_parent_death_signal

Best-effort Linux-only orphan-reaping safety net (spec Module 4/AC12).

If the host process dies WITHOUT running WorkerPool.shutdown()'s orderly sweep (crash, kill -9 on the host, …), PR_SET_PDEATHSIG makes the kernel SIGKILL this worker the instant its parent exits — a portable backstop that doesn't depend on the host doing anything right. Linux-only (prctl doesn't exist elsewhere); a no-op everywhere else, where the pool's own shutdown sweep is the (documented) only backstop.

set_parent_death_signal() -> None

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