Skip to content

Epic: SandboxTransport — language-neutral remote sandbox exec over gRPC #89

Closed

Description

@pdettori

Epic: SandboxTransport — language-neutral remote sandbox exec over gRPC

Tracks the work in the SandboxTransport spec (Status: Design — approved for planning) and ADR-0024 (Accepted). Landed via #78.

Origin

Today the harness runs every Pi tool call (read/write/bash/grep) inside a sandbox pod via kubectl exec — the harness dials into the pod through the kube API. That only works when the harness can reach the sandbox's API server, which rules out sandboxes behind NAT, on-prem, on a laptop, or in another cloud — and blocks the top driver: bring-your-own (untrusted 3rd-party) sandboxes (spec §1).

Target architecture

Invert connectivity: the sandbox dials out to a broker the harness also talks to, over a language-neutral, firewall-friendly protocol (one outbound TLS connection, HTTP/2 on :443), without changing the Pi loop, session backend, or leaf queue (spec §2–§3).

Sandbox (laptop / on-prem / other cloud / same cluster)
  worker (Go static binary) — SandboxWorker.Attach client
     │ outbound only, TLS :443, HTTP/2  (WorkerFrame ↑ / ServerFrame ↓)
     ▼
Kubernetes
  relay (Deployment, 1 replica)  — parks Attach streams; mirrors presence → Redis pool
     │ in-cluster gRPC (SandboxExec.Exec/Abort)
     ▼
  Harness (central brain: Pi loop + LLM)      Redis sandbox pool
     SandboxTransport.exec(...)  ← the ONE seam
       ├─ [local]  KubectlTransport    (existing kubectl-exec, renamed)
       └─ [remote] GrpcRelayTransport  (new; calls the relay)
     select-sandbox → leases pod OR remote record → returns a transport

Key decisions (locked) — see ADR-0024

  • Brain stays central. The Pi loop + LLM key never leave the harness; an untrusted sandbox only ever receives commands and returns bytes (trust-correct for driver harness: tsc fails on cli.ts gateway-header cast (x-api-key: null → Record<string, string>) #1).
  • Contract is a Protobuf IDL (sandbox/v1), not a TypeScript interface. Any gRPC-capable language can host a worker; TS is just one generated client (§4).
  • gRPC-native over HTTP/2 on :443, not Connect — full-duplex bidi needs HTTP/2 regardless, so Connect adds a second toolchain for no gain on the streaming core (§5).
  • Single-replica, presence-only relay — no matchmaking, no presence glue beyond mirroring workers into the existing Redis pool; select-sandbox matches unchanged (§6).
  • One Go reference worker — the honest proof the contract is genuinely language-neutral (§7).
  • Per-sandbox bearer token at the edge day-one; SPIFFE/mTLS upgrades into the same Attach seam later (§9).

What does NOT change

The Pi orchestration loop, run-turn, the session backend (RedisSessionBackend), the leaf queue (@sh/work-queue), and the sandbox pool/lease logic. The change slots strictly below the current ExecInPod call sites (spec §3).

Two tracks (build in parallel off the shared contract)

The worker build is separated from the backend and coded by a different contributor; per the repo's lifecycle conventions, implementation plans are local-only (docs/plans/, gitignored) and per-contributor — one for the backend, one for the worker.

Phases (dependency-ordered)

Deferred / follow-up (spec §13.4, ADR-0024) — not scheduled here

  • Untrusted-BYO isolation → SPIFFE/SPIRE mTLS per-connection identity on the same Attach endpoint.
  • Multi-replica relay / HA (adds a presence map — K8s API or Redis pub/sub).
  • Private-mesh reachability (Headscale / WireGuard) for fleets refusing a public endpoint.
  • Additional-language workers (e.g. Python) — the proto already permits them.
  • HTTP/1.1-only proxy traversal — the Connect / split-stream variant of §5.

Working conventions

  • Spec: docs/specs/2026-07-08-sandbox-transport-grpc-design.md + registry row (docs/specs/README.md). Decision: docs/adrs/0024-sandbox-transport-remote-exec.md.
  • Plans live in docs/plans/ (local-only, gitignored), named for the spec, deleted once coded.
  • DCO: git commit -s; attribution trailer Assisted-By: Claude (Anthropic AI) <[email protected]> (never Co-authored-by).

Activity

  1. pdettori commented on Aug 27, 2026

    @pdettori
    MemberAuthor

    ST4 (worker) is complete — #87 / PR #172

    The Go reference worker is done and green in CI. It replaces the HELLO WORLD stub with
    real bash -c execution in its own process group, timeout_s enforcement, process-group
    kill on abort, fingerprint-guarded dedup of redelivered req_ids, and reconnect that
    preserves the dedup cache. 56 tests under -race.

    Epic status this moves: ST1 (proto) → ST3 (relay + transport) → ST4 (worker) done.
    ST5 (#88) is now unblocked — the worker actually runs commands, which was the stated
    blocker on the live gate. I have posted a handover on #88 covering what ST4's acceptance
    battery proves and, more usefully, the two things it deliberately does not prove:
    the fake relay is self-authored (so its agreement with the contract is not independent
    evidence), and cross-transport equivalence is untested.

    Four findings from ST4 that belong to the epic rather than to the worker, all detailed
    on #87:

    1. req_id is not unique per worker. The harness seeds its counter at module scope —
      per process — while select-sandbox deliberately shares sandboxes across runs, so two
      replicas both send 1, 2, 3… to one worker. The worker ships a fingerprint guard
      (now covering command, stdin, timeout_s, and streaming) as defense-in-depth, but
      the real fix is a globally unique id and it belongs upstream in ST1/ST3.
    2. §7's non-streaming shape is not expressible in sandbox/v1 — End has no data
      field, so "a single End carrying full stdout" cannot be built. The worker buffers and
      emits ChunkSize-capped frames at exit instead. The spec prose wants correcting.
    3. A cache hit re-emits only the terminal frame, never the output chunks, so a
      redelivered streaming cat file returns exit 0 with empty content. The worker is
      spec-compliant; the gap is in the contract. Unreachable today because nothing
      redelivers a req_id — which is exactly why it should be settled before something does.
    4. Neither worker image shipped a shell, so every exec would have failed with ENOENT.
      Fixed in the PR; worth noting as a class — the "static binary, no runtime deps"
      requirement is about the binary, while bash is a dependency of the commands.

    Worker-specific follow-ups that are not epic-level are tracked separately in #173.

    Assisted-By: Claude Code

  2. pdettori commented on Aug 27, 2026

    @pdettori
    MemberAuthor

    ST4 merged — 4 of 5 tracks done, #88 is the only one left

    PR #172 merged to main at 84118c9. #87 closed. Checklist above updated.

    ST1 → ST2 → ST3 → ST4 shipped. ST5 (#88) is unblocked, and specifically unblocked in the
    sense that mattered: the stated blocker was "no leaf can complete through the remote path
    until the worker actually runs commands."
    It does now.

    What the epic gained

    The worker is no longer a connectivity stub. On main it spawns bash -c per exec in its
    own process group, streams stdout and stderr as 32 KiB Chunk frames on distinct stream
    enums, enforces timeout_s locally by killing the group, dedups redelivered req_ids
    behind a fingerprint over command + stdin + timeout_s + streaming, reconnects with
    jittered backoff while preserving its dedup cache, and advertises capabilities probed
    from PATH rather than a hardcoded list. 56 tests, -race clean, go test -race ./...
    wired into CI for the module.

    Driver #2 — the seam is not secretly TS-shaped — now has its evidence: a non-TypeScript
    worker satisfies the contract, built only against sandbox/v1.

    What ST5 inherits, stated honestly

    Detail is on #88; the two things worth surfacing at epic level:

    1. The acceptance battery's relay is self-authored. It is a real gRPC Attach with a
      real bash, and it is the only way to reach the redelivery path (the production relay
      cannot redeliver a req_id) — but it encodes this repo's reading of the contract, so its
      agreement is not independent. The gated interop test against the real relay exists and
      has never run. That is ST5's cheapest first step.
    2. Cross-transport equivalence is untested. ST4 exercised only the worker side of
      GrpcRelayTransport. §11's conformance battery against both transports is what
      actually discharges driver M5: Compaction-checkpoint fast path + budget voter #2's swappability claim.

    Four findings that belong to the epic, not the worker

    1. req_id is not unique per worker. grpc-relay-transport.ts seeds its counter at
      module scope — per process — while select-sandbox deliberately shares sandboxes, so two
      harness replicas both send 1, 2, 3… to one worker. The worker ships a fingerprint guard
      as defense-in-depth (widened during review after a probe showed a redelivery with a
      larger timeout_s being failed off a stale cache entry in ~650 µs without running), but
      the real fix is a globally unique req_id and it belongs in ST1/ST3. ST5 will hit
      this the moment more than one replica shares a sandbox.
    2. §7's non-streaming shape is not expressible in sandbox/v1. "A single End carrying
      full stdout" cannot be built — End has no data field. The worker buffers and emits
      ChunkSize-capped frames at exit. The spec prose wants correcting.
    3. A cache hit re-emits only the terminal frame, never the output chunks, so a
      redelivered streaming cat file returns exit 0 with empty content. The worker is
      spec-compliant; the gap is in the contract. Unreachable today because nothing redelivers
      a req_id — which is why it is worth settling before something does. Note the two
      transports will differ here: KubectlTransport has no dedup cache, so it re-runs and
      returns output. ST5's conformance battery has to pick the correct behavior.
    4. gRPC MaxCallRecvMsgSize is unconfigured, so a base64 write payload above the
      4 MiB default kills the whole stream rather than one exec. Needs a decision on both ends
      and a documented max write size.

    Worker-specific follow-ups deliberately not fixed: #173, audited against shipped code.

    Deferred by design, unchanged

    mTLS/SPIFFE (§9) is still the bearer token's successor and slots into the same Attach
    endpoint with no wire change; additional-language workers (§13.4) remain out of scope.

    Assisted-By: Claude Code

  3. pdettori commented on Aug 27, 2026

    @pdettori
    MemberAuthor

    Live gate validated manually; laptop demo filed as #174

    I ran the remote path end-to-end in a local kind cluster today. It works, with no
    kubectl exec anywhere in the path
    :

    leaf (Knative) → select-sandbox leases the grpc presence record → GrpcRelayTransport
      → sandbox-relay (in-cluster) → SandboxWorker.Attach (worker dialed OUT)
      → Go worker pod (uid 1001, RHEL 9.8) → bash -c 'cat /etc/os-release' → verdict
    

    The proof is an A/B on a file that differs between backends. The in-cluster sandbox-N
    pods are Alpine; the worker image is RHEL. Same leaf, same file path:

    Backend pattern Alpine model's reason
    kubectl sandbox pod FLAGGED "…running Alpine Linux"
    remote gRPC worker CLEAR "…this system is running Red Hat Enterprise Linux 9.8"

    The model can only name RHEL 9.8 by having read the worker's own filesystem. Mirror control
    (pattern: "Red Hat" → FLAGGED on the worker) confirms it from the other direction.

    Also validated today, below the leaf: the gated interop test against the real TypeScript
    relay
    passes (SH_LIVE_RELAY=1 — it had never been run), and the real
    GrpcRelayTransport drives the real relay and real worker with stdout/stderr split, stdin
    round-trip, and timeout:1 in ~1s.

    Two traps worth recording at epic level

    1. SH_REMOTE_SANDBOX=1 alone does not route to a remote worker. select-sandbox
      builds candidates = [...pods, ...grpcRecs] and picks least-loaded-first, so idle
      in-cluster pods win. The remote worker is a pool peer, not a replacement. My first
      remote run silently used a pod and looked successful. Anyone demoing or gating on this
      must remove local candidates (or use a dedicated pool selector) — and ST5: integration & live gate — cross-transport conformance + end-to-end leaf (Kind → OCP) #88's conformance
      work should assert which backend served, not merely that a run succeeded.
    2. deploy/knative/relay-deployment.yaml omits SH_RELAY_TOKEN. Relay auth is
      fail-closed, so the manifest as shipped produces a relay that rejects every Attach.

    Neither is a code defect; both are documentation/manifest gaps that cost a failed run each.

    The cluster has been reverted to its prior state. #174 tracks turning this into a
    one-command laptop demo (kind + worker as a plain docker run, which is the configuration
    that actually demonstrates driver #1 — a pod-based worker proves the plumbing but not the
    inverted connectivity).

    Assisted-By: Claude Code

  4. pdettori commented on Aug 28, 2026

    @pdettori
    MemberAuthor

    Epic complete — ST1 through ST5 shipped

    ST5 (#88) closed; the checklist above is now fully ticked. The closing work is 12 commits with make typecheck, make test (605 passed / 13 skipped) and go test -race ./... green.

    What has evidence

    • Driver harness: tsc fails on cli.ts gateway-header cast (x-api-key: null → Record<string, string>) #1 — untrusted BYO sandboxes. The sandbox dials out; there is no kubectl exec anywhere in the remote path; the Pi loop and the LLM key never leave the harness. Proven end to end by a leaf whose tool calls demonstrably executed on the remote worker's own filesystem — an A/B on /etc/os-release that gives opposite verdicts per backend — on Kind (twice) and on OpenShift.
    • Driver M5: Compaction-checkpoint fast path + budget voter #2 — the seam is not TypeScript-shaped. A Go worker built only against sandbox/v1, and one conformance battery that both per-call transports pass identically, including the output cap and the abort/SIGKILL that enforces it.

    What this epic does NOT establish

    Recorded deliberately, because a closed epic is what future work builds on — and this branch exists precisely because the spec had claimed more than the code delivered.

    1. "Every SandboxTransport enforces the cap" was false when written. persistentExecInPod is a third transport, uncapped, serving the file-reading tools, and absent from the battery. Spec §8, ADR-0024 and transport.ts now name the exception. → persistentExecInPod is an uncapped third SandboxTransport, and it serves the file-reading tools #180
    2. The transports are not observably identical. KubectlTransport applies no default deadline; the gRPC path always applies 120 s. The battery cannot see it: its timeout case always passes an explicit timeout, so neither default is ever exercised. → KubectlTransport has no default deadline while GrpcRelayTransport always applies 120s, and the battery cannot see it #182
    3. A bash flood is killed but reported to the model as success. Pi treats a null exit code as non-failing and createPodBashOps discards stdout, so the cap protects nothing on that path and misreports the kill. → A bash flood is SIGKILLed at the output cap but reported to the model as success #181
    4. The live gate's worker is an in-cluster pod. It proves the inverted-connectivity plumbing, not traversal of a real NAT boundary. → Demo: one-command laptop showcase — harness on kind, remote worker as a docker container #174 is the configuration that would.
    5. The production external path is deferred — relay Attach on :443 behind a Route with TLS, plus a NetworkPolicy locking SandboxExec to in-cluster callers per §9. The gate runs plaintext h2c on the relay ClusterIP, as §13.4 anticipated.

    Two defects the closing work found and fixed

    • A truncated read could be written back into a file. Adding the cap to KubectlTransport made it persistentExecInPod's fallback on channel death; readFile discarded exitCode; Pi's Edit is read-whole-file → write-whole-file. A >8 MiB Edit plus a channel death wrote 8 MiB and the truncation marker into the source — nondeterministically, depending on whether the persistent channel happened to survive. readFile now refuses to return content it cannot vouch for.
    • req_id was not unique across replicas (req_id is not globally unique: colliding ids from multiple harness replicas misroute frames at the relay #179, fixed). Worse than the worker-side dedup problem it was first reported as: the relay keys sinks by req_id per sandbox, so a collision replaced one caller's sink — that exec hung to its deadline while the other received both execs' output interleaved. Silently. The relay now refuses a duplicate in-flight req_id.

    Also corrected in the spec: §7 and §8 both promised "a single End carrying full stdout", which sandbox/v1 cannot express — End has no data field — and §8 omitted that a dedup cache hit returns an exit code with no output, which differs from KubectlTransport's re-run.

    Remaining follow-ups

    #173 (worker), #174 (laptop demo), #177 (ghcr paths after the org rename), #178 (setup-ocp.sh exit code), #180, #181, #182. §13.4's deferred items — mTLS/SPIFFE, multi-replica relay HA, private mesh, extra-language workers, HTTP/1.1 traversal — remain unscheduled by design.

    Assisted-By: Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions