<!-- task=m-iop-hot-path-one-shot-execution/17+14,15,16_endpoint_error_matrix plan=2 tag=REVIEW_API milestone-task=error-cancel -->

# Classify progressive endpoint write failures as caller cancellation

## For the Implementing Agent

Implement the scoped fix, run every verification command, and fill the implementation-owned sections of `CODE_REVIEW-cloud-G09.md` with actual notes and raw command output. Keep both active files in place and report ready for review. If blocked, record only the exact blocker, attempted commands/output, and resume condition in implementation-owned evidence fields. Do not ask the user, call user-input tools, create control-plane stop files, classify the next state, archive logs, or write `complete.log`; those actions belong to the review agent.

## Background

The endpoint terminal matrix added coverage for disconnect-during-write, but that test manually selects caller cancellation after bypassing the production stage runtime. In production, the callback error remains untyped and `runHotPathRequestRuntime` classifies it as `provider_error`, which can expose provider-error cleanup semantics after the caller has disconnected. The fix must preserve S13's wire-silent caller-cancel invariant and exact active-stage cancellation for both Anthropic Messages and Chat Completions.

## Archive Evidence Snapshot

- `agent-task/m-iop-hot-path-one-shot-execution/17+14,15,16_endpoint_error_matrix/code_review_cloud_G10_1.log`: FAIL. Required finding: a real stage-runtime endpoint writer failure selected `provider_error`; the disconnect test masked the defect by manually invoking caller cancellation. Fresh reviewer reproduction reported `Kind:provider_error`, `Source:stage_runtime`, `StageID:local`, while expecting `caller_cancel`.
- `agent-task/m-iop-hot-path-one-shot-execution/17+14,15,16_endpoint_error_matrix/plan_cloud_G09_1.log`: original `error-cancel` endpoint matrix plan. Its targeted race suite, isolated common regression, full Edge suite, `go vet`, and diff checks passed; preserve the S13 two-endpoint, silent-cancel, exact-active-stage scope.

## Analysis

### Files Read

- `agent-task/m-iop-hot-path-one-shot-execution/17+14,15,16_endpoint_error_matrix/PLAN-cloud-G09.md`
- `agent-task/m-iop-hot-path-one-shot-execution/17+14,15,16_endpoint_error_matrix/CODE_REVIEW-cloud-G10.md`
- `agent-roadmap/phase/knowledge-tool-optimization-extension/milestones/iop-hot-path-one-shot-execution.md`
- `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`
- `agent-spec/runtime/stream-evidence-gate.md`
- `agent-spec/input/openai-compatible-surface.md`
- `agent-contract/outer/anthropic-compatible-api.md`
- `agent-contract/outer/openai-compatible-api.md`
- `agent-contract/inner/edge-node-runtime-wire.md`
- `apps/edge/internal/openai/hot_path_terminal_control.go`
- `apps/edge/internal/openai/cancellation_routes_test.go`
- `agent-test/local/rules.md`
- `agent-test/local/edge-smoke.md`

### SDD Criteria

- SDD: `agent-roadmap/sdd/knowledge-tool-optimization-extension/iop-hot-path-one-shot-execution/SDD.md`, status `approved`, implementation lock released.
- Milestone task metadata: `error-cancel`.
- Targeted acceptance scenario: S13, the endpoint × commit-state × disposition-source × active-stage error/cancel/length matrix.
- Evidence Map driver: the `error-cancel` row requires an endpoint error/cancel/length table test. That row shapes the checklist around production-path caller-write classification, exact active-stage `CANCEL_RUN`, two endpoint variants, and no cleanup, terminal, or post-failure wire output.

### Verification Context

- No separate verification handoff was supplied. Repository-native evidence came from the local testing rules, Edge smoke guide, related tests, contracts, and fresh reviewer execution.
- Local preflight: workspace `/config/workspace/iop-s0`; Go `/config/.local/bin/go`; `go version go1.26.2 linux/arm64`; HEAD `f79fe3c7`; shared worktree dirty with 60 entries, so unrelated changes must be preserved.
- Fresh targeted race command passed in `2.569s`. The common race command passed in isolation (`streamgate 2.494s`, `config 4.232s`, `openai 26.454s`, `service 8.781s`). A prior parallel run caused only the known service timing-window test to fail under contention, so final verification runs the common suite in isolation.
- `TMPDIR=/config/workspace/iop-s0 go test -count=1 ./apps/edge/...`, `go vet ./apps/edge/...`, `gofmt -d` for the scoped files, and `git diff --check` all passed during review.
- Reviewer production-path reproduction: a progressive writer error through `runHotPathCollectedStage` returned a typed outer disposition of `provider_error` instead of `caller_cancel`; the temporary reproducer file was removed after execution.
- Fresh execution is required; Go test-cache output is not acceptable, so every test command uses `-count=1`.
- External verification preflight is not applicable. This deterministic internal runtime/codec defect does not require a live provider, field Edge node, Docker runtime, or browser E2E cycle.

### Test Coverage Gaps

- Existing `TestHotPathEndpointDisconnectDuringWriteCancelsActiveStage` covers endpoint and stage labels, exact cancel shape, and silent wire assertions, but it manually registers/releases/cancels and never exercises `hotPathStageReleaseSink` plus `runHotPathRequestRuntime`.
- No current regression proves that a callback write error is tagged as caller-owned at the release boundary, remains `caller_cancel` through runtime classification, aborts only the real active stage once, and suppresses cleanup/terminal/post-failure writes for both endpoints.

### Symbol References

- None. No symbol is renamed or removed.

### Split Judgment

- Keep one plan: typed callback-error propagation, runtime cancellation election, exact transport abort, and endpoint silence form one indivisible correctness invariant with one table-driven regression oracle.
- Directory predecessor `14` is satisfied by `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/14+13_anthropic_gate/complete.log`.
- Directory predecessor `15` is satisfied by `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/15+13_chat_gate/complete.log`.
- Directory predecessor `16` is satisfied by `agent-task/archive/2026/08/m-iop-hot-path-one-shot-execution/16+14,15_terminal_disposition/complete.log`.

### Scope Rationale

- Modify only the protocol-neutral stage release/runtime classification and its existing endpoint cancellation regression. Endpoint policy tables, ordinary success/error codecs, `/v1/responses`, provider decoding, cleanup state-machine implementation, contracts, SDD, roadmap state, and dependencies are excluded because fresh evidence isolates the defect before those layers.
- Preserve all unrelated dirty-worktree changes.

### Final Routing

- `evaluation_mode=isolated-reassessment`; `finalizer=finalize-task-policy.sh`; `finalizer_mode=pair`.
- Build closure: scope, context, verification, evidence, ownership, and decision are closed. Scores `1/2/2/2/1` produce `G08`; base `local-fit` is promoted by `recovery-boundary` because `review_rework_count=1` and `evidence_integrity_failure=true`. Canonical file: `PLAN-cloud-G08.md`.
- Positive loop-risk signatures: `temporal_state`, `concurrent_consistency`, `boundary_contract`, `variant_product` (`loop_risk_count=4`); `large_indivisible_context=false`; risk boundary also matches but recovery boundary has priority.
- Review closure is complete. Scores `2/2/2/2/1` produce `G09`; route `official-review`, adapter `codex`, model `gpt-5.6-sol`, reasoning effort `xhigh`. Canonical file: `CODE_REVIEW-cloud-G09.md`.
- Capability gap: none.

## Implementation Checklist

- [ ] [REVIEW_API-1] Carry progressive endpoint write failure through the production stage runtime as wire-silent caller cancellation, abort the exact active stage once, and replace the masking test with real runtime-path evidence for both endpoints and all scoped stage labels.
- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.

### [REVIEW_API-1] Production caller-write cancellation

**Problem:** `apps/edge/internal/openai/hot_path_terminal_control.go:1047` returns the endpoint callback error unchanged, then line 1492 maps the generic error to `provider_error`. `apps/edge/internal/openai/cancellation_routes_test.go:380` manually calls `cancelActiveStage(hotPathDispositionCallerCancel, ...)`, so it proves a fabricated path instead of the runtime behavior.

**Solution:** Tag only endpoint callback failures at the stage release boundary with the existing typed disposition error as `caller_cancel` and source `caller_write`. In `runHotPathRequestRuntime`, extract a typed disposition before falling back to `hotPathDispositionForError`, then elect cancellation through `cancelActiveStage` so the public gate closes and the generation-fenced controller issues at most one abort. Preserve provider errors for identity, decode, gate, and other runtime failures. Rewrite the disconnect test to run a scripted stage source through `runHotPathStreamingStage` or `runHotPathStage` with `newHotPathStageTransportController`; do not directly call `registerActiveStage`, `releaseDelta`, or `cancelActiveStage` to manufacture the result.

Before (`apps/edge/internal/openai/hot_path_terminal_control.go:1047`):

```go
released, err := s.outer.releaseDeltaRecorded(s.stageSeq, ev)
if err != nil {
	return "", err
}
```

After:

```go
released, err := s.outer.releaseDeltaRecorded(s.stageSeq, ev)
if err != nil {
	stageID := ""
	if s.active != nil {
		stageID = s.active.stageID
	}
	return "", newHotPathDispositionError(hotPathDispositionCallerCancel, "caller_write", stageID, err)
}
```

Before (`apps/edge/internal/openai/hot_path_terminal_control.go:1491`):

```go
if runErr != nil {
	kind := hotPathDispositionForError(runErr)
	if kind == hotPathDispositionCallerCancel || kind == hotPathDispositionTimeout {
		outer.cancelActiveStage(kind, "stage_runtime", runErr)
	} else {
		outer.selectDisposition(outer.activeStageDisposition(kind, "stage_runtime", runErr.Error()))
	}
}
```

After:

```go
if runErr != nil {
	kind := hotPathDispositionForError(runErr)
	source := "stage_runtime"
	if disposition, ok := hotPathDispositionFromError(runErr); ok {
		kind = disposition.Kind
		source = disposition.Source
	}
	if kind == hotPathDispositionCallerCancel || kind == hotPathDispositionTimeout {
		outer.cancelActiveStage(kind, source, runErr)
	} else {
		outer.selectDisposition(outer.activeStageDisposition(kind, source, runErr.Error()))
	}
}
```

**Modified Files and Checklist:**

- [ ] Modify `apps/edge/internal/openai/hot_path_terminal_control.go` to type callback write failures and preserve that disposition through runtime error selection without changing unrelated error classification.
- [ ] Modify `apps/edge/internal/openai/cancellation_routes_test.go` so `TestHotPathEndpointDisconnectDuringWriteCancelsActiveStage` drives the real stage runtime for Anthropic/Chat × direct/local/review/repair, uses the real stage transport controller, and asserts typed `caller_cancel`, exact active `CANCEL_RUN` once, no cleanup handoff, no terminal, and no late bytes.
- [ ] Record actual changes, deviations, design decisions, and raw verification output in `agent-task/m-iop-hot-path-one-shot-execution/17+14,15,16_endpoint_error_matrix/CODE_REVIEW-cloud-G09.md`.

**Test Strategy:** Rewrite the existing regression rather than add a parallel synthetic test. Its table fixture must prepare each endpoint's progressive writer, fail the next write, run a normalized event source through the production stage runtime with `newHotPathStageTransportController`, inspect the returned typed disposition, inspect the exact service `CancelRun` request/action, and assert the wire snapshot does not gain cleanup, endpoint terminal, or late bytes. Keep the existing terminal matrix and cancel/complete race as neighboring regressions.

**Verification:** Run the targeted race command first, then the isolated common race suite and full Final Verification. All commands must exit 0; formatting commands must produce no diff.

## Dependencies and Execution Order

1. The archived completion logs for predecessors `14`, `15`, and `16` listed in Split Judgment satisfy the directory dependency.
2. Implement typed release/runtime propagation before rewriting the production-path regression.
3. Run targeted verification before the broader Edge suites and record every actual output in the active review stub.

## Modified Files Summary

| File | Item |
|---|---|
| `apps/edge/internal/openai/hot_path_terminal_control.go` | REVIEW_API-1 |
| `apps/edge/internal/openai/cancellation_routes_test.go` | REVIEW_API-1 |
| `agent-task/m-iop-hot-path-one-shot-execution/17+14,15,16_endpoint_error_matrix/CODE_REVIEW-cloud-G09.md` | REVIEW_API-1 |

## Final Verification

```bash
go test -race -count=1 ./apps/edge/internal/openai -run 'TestHotPath(EndpointTerminalMatrix|EndpointDisconnectDuringWriteCancelsActiveStage|CancelCompleteRace)|Test(ChatStreamSession|AnthropicNative|StreamChatCompletion)'
go test -race -count=1 ./packages/go/streamgate ./packages/go/config ./apps/edge/internal/openai ./apps/edge/internal/service
TMPDIR=/config/workspace/iop-s0 go test -count=1 ./apps/edge/...
go vet ./apps/edge/...
gofmt -d apps/edge/internal/openai/hot_path_terminal_control.go apps/edge/internal/openai/cancellation_routes_test.go
git diff --check
```

Expected: all commands exit 0; both endpoints classify production-path writer disconnect as `caller_cancel`, issue exactly one `CANCEL_RUN` for the active stage, emit no cleanup or endpoint terminal after failure, accept no late bytes, preserve ordinary endpoint behavior, and report no race, vet, formatting, or diff errors. `gofmt -d` must print nothing.

After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`.
