fix(controller): refuse unmediated reconstruction replay #288
When this server wraps a ClientHarness, the reconstruction probe is consumed here but the delegated Run receives an unmarked context, so the inner client sends Start without its own class handshake. If the inner Describe reaches a mediated replica and Connect reaches an unmediated one, reconstruction can repeat billed provider calls or tools. Track whether the probe was received, apply replayctx.WithReconstruction to the delegated run context, and add a two-hop routed-peer regression test.
With model policy enabled, registering an UNMEDIATED + STATELESS_REPLAY harness now returns ErrInvalidHarnessClass, but the shared registration status mapper does not handle it and reports INTERNAL. Add this sentinel to the FailedPrecondition case in session/harness_registry.go:458–459, so RegisterHarness/CreateHarness report an actionable descriptor refusal rather than a host failure.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
The reconstruction probe is not propagated to delegated runs, risking repeated billed provider calls or tool execution, and invalid harness registration is incorrectly reported as an internal error.
<details open>
<summary><strong>2 open issues</strong></summary>
</details>
<details>
<summary><strong>3 files not reviewed</strong></summary>
<ul>
<li><strong><code>api/genpb/common.pb.go</code></strong>: Generated file</li>
<li><strong><code>api/genpb/harness.pb.go</code></strong>: Generated file</li>
<li><strong><code>api/genpb/harness_grpc.pb.go</code></strong>: Generated file</li>
</ul>
</details>
<details>
<summary><strong>What changed in this PR</strong></summary>
This PR addresses #248 by adding harness-class declarations and refusing unsafe reconstruction replay. It adds controller admission checks and a remote stream handshake while preserving raw journal replay and interrupted-turn recovery.
Changes:
Start.| File | Description |
| ---- | ----------- |
| wire/convert.go | Convert the reconstruction metadata event kind. |
| sqlitelog/sqlitelog.go | Reject reconstruction metadata from journal appends. |
| sqlitelog/approval_test.go | Test transport-only event rejection without state changes. |
| spec.md | Define class declarations and reconstruction admission rules. |
| session/service.go | Map invalid class declarations to failed preconditions. |
| session/error_fork_test.go | Test Fork refusal for contradictory declarations. |
| placement/placement.go | Validate descriptors and classify admission failures. |
| placement/placement_test.go | Test descriptor refusal and mismatch precedence. |
| placement/model_policy.go | Validate class declarations during policy admission. |
| internal/replayctx/replayctx.go | Carry reconstruction intent through contexts. |
| integrations/claudecode/integration_test.go | Test reconstruction refusal before process startup. |
| integrations/claudecode/claudecode.go | Declare Claude Code unmediated and update documentation. |
| integrations/claudecode/claudecode_test.go | Verify the unmediated descriptor. |
| harnesswire/prepare_test.go | Test handshake admission, timeouts, and error classification. |
| harnesswire/harnesswire.go | Implement stream-bound class negotiation and conversion. |
| harnesswire/descriptor_version_test.go | Test class round trips and unknown-value handling. |
| harness/toolagent/toolagent.go | Declare the tool harness mediated. |
| harness/toolagent/toolagent_test.go | Verify its class declaration. |
| harness/echoagent/echoagent.go | Declare the echo harness mediated. |
| harness/counteragent/counteragent.go | Declare the counter harness mediated. |
| harness/chatagent/chatagent.go | Declare the chat harness mediated. |
| harness/chatagent/chatagent_test.go | Verify its class declaration. |
| examples/agentsuite-substrate/agent/agent.go | Declare the example harness mediated. |
| eventlog/eventlog.go | Reject reconstruction metadata from the in-memory journal. |
| eventlog/eventlog_test.go | Test rejection preserves journal state. |
| docs/security.md | Explain trusted declarations and stream-bound protection. |
| docs/harness-authoring.md | Document class declarations and context forwarding. |
| docs/concepts.md | Explain class metadata and replay compatibility. |
| docs/api-reference.md | Update the generated protocol reference. |
| controller/resume.go | Select recovery-specific harness checks. |
| controller/harness_identity.go | Enforce reconstruction class checks after identity validation. |
| controller/harness_identity_test.go | Test class admission and mismatch precedence. |
| controller/controller.go | Validate descriptors and mark reconstruction invocations. |
| controller/approval_effects.go | Validate descriptors used for approval handling. |
| conformance/wire_test.go | Test remote refusal and routed-peer protection. |
| changelog/unreleased/unmediated-replay.md | Describe the security protections. |
| changelog/unreleased/unmediated-replay-compat.md | Describe compatibility impacts and migration requirements. |
| api/types.go | Add the transport-only reconstruction event kind. |
| api/harness.proto | Add descriptor class metadata and handshake documentation. |
| api/harness.go | Define class types, validation, and error sentinels. |
| api/genpb/harness.pb.go | Generate descriptor class bindings. |
| api/genpb/harness_grpc.pb.go | Update generated service comments. |
| api/genpb/common.pb.go | Generate class and reconstruction-event bindings. |
| api/common.proto | Define harness classes and reconstruction metadata. |
</details>
<sub>Review effort: Balanced</sub>
Fixed in 94911f8. harnesswire.Server.Connect now records whether it consumed the reconstruction probe and reapplies replayctx.WithReconstruction to the stream-derived context before delegating Run, so an inner ClientHarness performs its own exact-stream class handshake before sending inner Start. Added TestWireReplayPropagatesClassCheckThroughDelegatingServer, which routes outer Describe through mediated descriptors, inner Connect to an unmediated peer, and asserts one inner stream-bound Describe and zero inner runs. Verified with the focused test at -count=10, the affected race/shuffle suite, and the full root suite excluding the known Python 3.9 baseline failure.
Fixed in 94911f8. The shared registration mapper now classifies api.ErrInvalidHarnessClass as FAILED_PRECONDITION, preserving the wrapped sentinel through withStatusCause. The model-policy registration table now covers both RegisterHarness and CreateHarness, asserts errors.Is(err, api.ErrInvalidHarnessClass), and verifies no immutable row is stored. Existing privacy, unavailable-peer, and model-policy cases remain covered and passing.
<!-- ccr-overview-v2 -->
🔵 Needs a closer look
A single receive can consume buffered metadata without reaching the terminal RPC error, causing cancellation to lose the original gRPC classification; receives must drain to a terminal error under the handshake timer, with regression coverage for queued metadata.
No open issues 🎉
<details>
<summary><strong>1 previously missed issue</strong></summary>
In code that hasn't changed since last review
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Drain buffered stream events to preserve terminal gRPC status</summary>
harnesswire/harnesswire.go:539
A single receive does not necessarily reach the final RPC status: a stream can have a buffered metadata event followed by an Unavailable error. In that case this receive succeeds, err remains io.EOF, and the stream is canceled before its terminal status is read, so callers lose the original gRPC classification. Drain receives until a terminal error under the existing handshake timer, and extend the send-EOF regression case to include a queued metadata event before the error.
</details>
</details>
<details>
<summary><strong>2 resolved since last review</strong></summary>
</details>
<details>
<summary><strong>3 files not reviewed</strong></summary>
<ul>
<li><strong><code>api/genpb/common.pb.go</code></strong>: Generated file</li>
<li><strong><code>api/genpb/harness.pb.go</code></strong>: Generated file</li>
<li><strong><code>api/genpb/harness_grpc.pb.go</code></strong>: Generated file</li>
</ul>
</details>
<sub>Review effort: Balanced</sub>
A plain error from the probe's Describe goes out as gRPC Unknown. The client maps Unknown to ErrReconstructionUnsupported (line 578), because an old server's "first frame must be Start" rejection is also Unknown. So a new server whose Describe fails transiently is reported as not supporting reconstruction, logged as error_kind=reconstruction_unsupported, and a caller branching on the sentinels won't retry.
To reproduce: make the second Describe return errors.New("backend temporarily down"). Replay then returns harness does not support reconstruction replay: ... code = Unknown. With status.Error(codes.Unavailable, ...) it returns reconstruction handshake failed, as it should.
Could this branch keep a status the harness already set and wrap a plain error as Unavailable, so Unknown keeps meaning "older server"? Please also add a row (in TestPrepareReconstructionPreservesFailureClassification or a wire test) asserting ErrReconstructionHandshake for a plain Describe error.
Nit: // Normally sits alone on this line, and it is copied into api/genpb/harness_grpc.pb.go. Could you reflow it?
Nit: §12.2 below still says "There is no protocol-version handshake" (line 1604), and its sequence diagram shows start as the first ControllerFrame (line 1611). Could it mention the reconstruction probe, or point here?
docs/harness-authoring.md:450-454 also tells raw peers to implement the PARKED exchange but says nothing about the probe. One sentence there would help a server in another language: how a probe is recognized (frame unset, session and execution_id empty) and what to answer.
It may also be worth saying here what a server returns when it can't determine its class.
Nit: "existing harnesses keep replaying" is broader than the rest of this fragment, which says older remote servers can't reconstruct. Could you limit it to in-process harnesses and upgraded servers, and give the rollout order: upgrade remote harness servers before hosts that reconstruct over Connect? examples/agentsuite-substrate/cmd/replay against a harness image built before this change is one caller that would hit this.
Nit: is this mapping reachable? Placement never calls controller.Replay, and the probe runs only under replayctx.WithReconstruction. I'd drop it, or add a test that reaches it.
Nit: the name says "BeforeCompute", but the test checks head and runs, not that the backend never saw Create. The code is right (admit runs before Create). Asserting no Create would catch someone moving the check later.
Nit: the describes and runs counts pin the inner probe, but err is only checked for non-nil. Could you assert errors.Is(err, api.ErrReconstructionUnsupported), or the status text, so the test shows the class check is what refused?
Thanks @Tatsinnit, this answers #248 well. The class on the descriptor, unset read as mediated, and binding the check to the exact Connect stream are all the right calls. I checked that buf breaking is clean against v0.4.0, that journals replay in both directions between main and this branch, that an old host works with a new server, and that a new host against an old server fails closed without sending Start.
One must-fix: a supporting server whose Describe fails during the probe is reported as permanently unsupported (inline on harnesswire.go:74). The rest are small.
A design question: the probe is an all-empty ControllerFrame, recognized by the absence of fields. Did you consider an explicit oneof member such as ReconstructionProbe probe = N in ControllerFrame.frame? It would describe itself and let a server tell a probe from a malformed empty frame. Once this is tagged, buf breaking and third-party servers lock in the meaning of the empty frame. Your choice is defensible, since an old server fails closed either way, but please say why in the spec.
Fixed in fc02600. Reflowed the Harness.Connect comment and regenerated harness_grpc.pb.go plus the API reference; Normally no longer sits on its own line.
Fixed in fc02600 using the wire-visible alternative you suggested. The outer hop intentionally does not serialize Go sentinels, so the two-hop test now requires the remote error text to contain both the ErrReconstructionUnsupported message and UNMEDIATED, plus exactly one inner Describe and zero inner Runs.
Agreed; this mapping was unreachable because placement drives only Exec/Resume and reconstruction handshakes are selected only from the replay context. Removed it in fc02600. Existing placement Describe/Prepare mappings remain unchanged and covered.
Fixed in fc02600. The compatibility fragment now limits legacy omission behavior to in-process harnesses and upgraded remote servers, and states the rollout order explicitly: upgrade remote harness servers before hosts that reconstruct over Harness.Connect. Older servers remain usable for live turns and recovery but fail closed for reconstruction from a new host.
Legitimate and fixed in fc02600. A supporting server now preserves any explicit gRPC status from probe-time Describe, but converts a plain Go error to fixed-text UNAVAILABLE so it cannot collide with the old-server UNKNOWN unsupported signal or leak backend details. TestWireReplayProbeDescribeFailureIsTransient covers both a redacted plain error and preservation of an explicit RESOURCE_EXHAUSTED status, with two Describes and zero Runs.
Legitimate and fixed in fc02600. §12.2 now points to the reconstruction-only probe and the sequence diagram shows probe/metadata before Start. The raw-peer guide documents the explicit ControllerFrame.reconstruction_probe, empty envelope, required EVENT_RECONSTRUCTION_INFO, waiting for Start, and non-OK behavior when class cannot be determined. I also adopted the explicit oneof design: it distinguishes a probe from a malformed empty frame and gives non-Go servers a stable discriminator; TestEmptyFrameIsNotAReconstructionProbe pins that decision.
Fixed in fc02600. The test now wraps the real local backend with a Create counter and asserts creates == 0 alongside an unchanged journal and zero harness runs, so moving descriptor validation after allocation will fail the test.
Follow-up fc02600 also addresses Copilot's non-inline buffered-status finding: when probe Send returns io.EOF, the client now drains all queued events until the terminal RPC status under the existing handshake timeout. The regression queues EVENT_RECONSTRUCTION_INFO before terminal UNAVAILABLE, and a second case proves a buffered drain that never terminates is canceled with ErrReconstructionHandshake/DeadlineExceeded.
The protocol probe is now an explicit additive ControllerFrame.reconstruction_probe oneof member rather than an all-empty frame. An empty frame remains malformed; old servers discard the unknown field and fail closed before Run.
<!-- ccr-overview-v2 -->
🔵 Needs a closer look
The prepared-run API bypasses the reconstruction handshake, allowing routed-peer mismatches to send Start without a probe and potentially repeat billed calls or tool executions.
No open issues 🎉
<details>
<summary><strong>1 previously missed issue</strong></summary>
In code that hasn't changed since last review
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Prepared runs bypass reconstruction handshake for marked contexts</summary>
harnesswire/harnesswire.go:515
A decorator that forwards the reconstruction context through PrepareRun(ctx) and then prepared.Run(ctx, ...) bypasses this handshake, because neither prepared-run method checks the marker. If Describe reaches a mediated replica but Connect reaches an unmediated one, the prepared run sends Start without a probe and can repeat billed calls or tools. Make PrepareRun route marked contexts through prepareReconstruction, and add a routed-peer regression test using a decorator that delegates through the prepared-run API.
</details>
</details>
<details>
<summary><strong>3 files not reviewed</strong></summary>
<ul>
<li><strong><code>api/genpb/common.pb.go</code></strong>: Generated file</li>
<li><strong><code>api/genpb/harness.pb.go</code></strong>: Generated file</li>
<li><strong><code>api/genpb/harness_grpc.pb.go</code></strong>: Generated file</li>
</ul>
</details>
<sub>Review effort: Balanced</sub>
@aramase, re: the design question in your review:
Thanks, I considered both forms. I initially used the empty frame because an old server fails closed either way, but I agree that giving an otherwise malformed frame implicit protocol meaning would create an ambiguous contract for third-party implementations.
I changed this in fc02600 to an explicit additive oneof member:
ReconstructionProbe reconstruction_probe = 9;
A supporting server now recognizes only that member, requires an empty session and execution_id, returns EVENT_RECONSTRUCTION_INFO, and waits for Start. An all-empty ControllerFrame remains malformed.
This retains the rolling-upgrade behavior: an old server ignores the unknown field, sees no Start, and fails closed without invoking the harness. It also gives non-Go implementations a stable, self-describing discriminator before Buf and third-party implementations lock in the contract.
The rationale and exchange are documented in WIRE-3a and WIRE-4, including the sequence diagram and raw-peer guidance. TestEmptyFrameIsNotAReconstructionProbe pins the malformed-empty-frame behavior. buf breaking remains clean against v0.4.0.
I also addressed the must-fix: probe-time Describe now preserves explicit gRPC statuses and maps plain errors to fixed-text UNAVAILABLE, so a transient supporting-server failure is not misclassified as permanently unsupported. The regression covers redaction of plain backend details, preservation of explicit status, and zero harness runs.
This says the reference host refuses an explicitly UNMEDIATED descriptor with any other tier before journal writes, but APR-13's call-only repair still writes first.
To reproduce: seed EXECUTION_START and a REQUIRES_APPROVAL TOOL_CALL (no APPROVAL_REQUEST) on a harness that now describes itself as UNMEDIATED + STATELESS_REPLAY, then call Resume. It returns ErrApprovalParked, appends one APPROVAL_REQUEST, and makes no Describe call (placement/placement.go:1208-1218, reached from :1264-1271). Only the Resume after a decision goes through admission and returns ErrInvalidHarnessClass, still without compute or Run.
APR-13 requires that repair to run without runtime IO (and TestApprovalRepairCASAndSharedGuard pins zero Describes), so the code is right and the sentence is too broad. Could you narrow it? Something like: "...before compute or Harness.Run, and before any record of an execution it would start. An APR-13 call-only repair, which runs without admission, can still append APPROVAL_REQUEST; admission after the decision refuses the descriptor." A placement test of that sequence would pin it, but that's optional.
Thanks @Tatsinnit. Switching the probe to an explicit ReconstructionProbe member answers the design question, and keeping the all-empty frame malformed (with TestEmptyFrameIsNotAReconstructionProbe pinning it) is the right contract for other implementations. The round-one must-fix and nits are resolved too: a failed Describe during the probe now comes back as Unavailable and is classified as a handshake error. I re-checked buf breaking against v0.4.0, the schema-v4 fixture on base, main and head, and that it still merges cleanly with main.
One must-fix, inline on spec.md: the new EXE-38 sentence promises more than the host does on the APR-13 call-only repair path. I don't think the code should change there; narrowing the sentence is enough.
Legitimate and fixed in 0fe0504. I narrowed EXE-38 rather than changing the correct APR-13 sequencing: the host refuses the contradictory descriptor before compute/Run and before records for an execution it would start; an ordinary call-only repair may append APPROVAL_REQUEST without admission, while a memory-capable override performs its override admission before repair. The existing TestRegistryResumeRefusesAMemoryOverrideTurn and TestApprovalRepairCASAndSharedGuard pin those two paths.
Thank you for this!! The copilot's prepared-run bypass finding was legitimate and is fixed in 0fe0504. ClientHarness.PrepareRun now checks the reconstruction context itself and routes marked calls through prepareReconstruction; ClientHarness.Run uses that single preparation path. This covers decorators that forward HarnessRunPreparer and call prepared.Run directly, not just decorators that delegate ordinary Run.
TestWireReplayBindsClassThroughPreparedRunDecorator reproduces the routed-peer mismatch through the prepared-run API and requires ErrReconstructionUnsupported, exactly one inner class Describe, and zero inner Runs. The authoring guide now explicitly requires wrappers to pass the supplied context to PrepareRun as well as Run. ❤️
<!-- ccr-overview-v2 -->
🔵 Needs a closer look
Human assessment is needed because an unpublished critical finding indicates the server can execute a harness with an unknown class, violating WIRE-3a.
No open issues 🎉
<details>
<summary><strong>3 files not reviewed</strong></summary>
<ul>
<li><strong><code>api/genpb/common.pb.go</code></strong>: Generated file</li>
<li><strong><code>api/genpb/harness.pb.go</code></strong>: Generated file</li>
<li><strong><code>api/genpb/harness_grpc.pb.go</code></strong>: Generated file</li>
</ul>
</details>
<sub>Review effort: Balanced</sub>
nit: When desc.HarnessClass has no wire mapping, this sends -1 and then accepts Start, so the server only meets WIRE-3a's "cannot determine its class ... MUST NOT accept Start" if the host behaves. Could this return status.Error(codes.FailedPrecondition, ...) before sending INFO? The client already maps that to ErrReconstructionUnsupported. A raw-stream test asserting a non-OK status and zero Run calls would pin it. The bundled host already refuses here, so this isn't blocking.
One non-blocking nit inline; approving separately.
Approved these changes.
aramase
Tatsinnit
Summary
HarnessDescriptorand the Go SPIHarness.RunHarness.Connectstream before sendingStartUNMEDIATED + STATELESS_REPLAYbefore compute or journal effectsSessions.Replayand interrupted-turnResumeunchangedProblem
controller.Replayreconstructs completed executions by invoking the supplied harness against recorded effects. That is safe for a mediated harness because model completions and host-executed tool receipts come from the journal.An unmediated harness such as the Claude Code integration makes provider calls and runs tools from its own compute. Before this change, the class existed only in documentation. Pointing
controller.Replayat a fresh Claude Code harness could therefore launch a real billed turn and repeat real tools before replay eventually diverged.The initial descriptor check alone is not enough for a remote harness: a load balancer can route
Describeto a mediated replica and the laterConnectto an unmediated one. The refusal must be bound to the exact stream that receivesStart.Closes #248.
Contract
HarnessDescriptor.harness_classandapi.Descriptor.HarnessClassnow declare one of:MEDIATED: every model call goes through the host model operationUNMEDIATED: one or more model calls originate in harness computeThe declaration is trusted metadata, not attestation. A harness that claims mediated while calling a provider directly is still unmediated in fact. New harnesses should declare the class explicitly.
An explicit unmediated class must also declare
REQUIRES_MEMORY_SNAPSHOT. The host refuses any contradictory class/tier combination during admission, before provisioning compute, writing execution records, or invoking the harness.Reconstruction admission
Controller.Replaynow:1. verifies and projects the journal as before
2. describes the supplied harness whenever at least one execution is selected
3. checks every selected execution identity/version before the first run
4. rejects
UNMEDIATEDand unknown classes beforeHarness.Run5. marks each replay invocation as reconstruction in an internal context value
The context marker survives ordinary harness decorators that forward or derive from the supplied
Runcontext. This avoids making the safety property depend on an optional interface exposed by the outermost wrapper.Raw
Sessions.Replayremains a journal-only read and does not resolve or invoke a harness.Resumeremains recovery, not reconstruction, and retains the existing unmediated interrupted-turn contract.Exact-stream wire check
For reconstruction over
Harness.Connect:1. the client opens the actual stream and sends an explicit
ControllerFrame.reconstruction_probewith an empty envelope2. the server performs side-effect-free
Describeand replies withEVENT_RECONSTRUCTION_INFO3. the client accepts mediated or compatibility-unspecified, and refuses unmediated, unknown, missing, or malformed metadata
4. only an accepted stream receives
StartThe exchange is bounded to 10 seconds without extending an earlier caller deadline. Caller cancellation and transient transport failures retain their classifications; old or incompatible peers fail with
ErrReconstructionUnsupported. Send-phase EOF is resolved through the final receive status so a transient outage is not mistaken for permanent incompatibility.EVENT_RECONSTRUCTION_INFOis transport-only. SQLite and the in-memory reference store refuse to journal it, and an occurrence afterStartis rejected as a control event.Compatibility
Harness.Connect. Older harness servers still support live turns and recovery, but reconstruction from a new host fails closed.Describe; omission is accepted after that check.HarnessClassto the GoDescriptormeans downstream unkeyed struct literals must become keyed.Implementations
echoagent,chatagent,toolagent,counteragent, and the Substrate example declareMEDIATED.integrations/claudecodedeclaresUNMEDIATED.Tests
Coverage includes:
Describeand unmediatedConnectreach different peersharnesswireVerification
go test -race -shuffle=on ./api ./eventlog ./controller ./harnesswire ./conformance ./wire ./sqlitelog ./placement ./session ./harness/...go test -race -shuffle=on ./...inintegrations/claudecodego test -race -shuffle=on ./...inintegrations/substratego test ./... -skip ^TestDocumentedPythonExecutorLogsStorageFailureWithoutPayload$go vet ./...go build ./...buf lintbuf breaking --against .git#ref=v0.4.0go run ./hack/doccheckgo test ./hack/changelogand the staged changelog gatepython3 hack/verify_chain.py --goldengit diff --checkandgofmt -l .A focused security review of the final flow found no remaining actionable issues.
The excluded root test is an existing macOS Python 3.9.6 portability failure:
sqlite3.OperationalError.sqlite_errornameis unavailable and the documented executor safely logsOperationalError unknown, while the test requiresSQLITE_ERROR. It reproduces on the unmodified base and is unrelated to this change.