Skip to content

feat(coderd): track chat execute tool calls in a durable execution ledger - #27100

Closed
ibetitsmike wants to merge 34 commits into
mainfrom
mike/codagt-757-execution-records
Closed

ibetitsmike wants to merge 34 commits into
mainfrom
mike/codagt-757-execution-records

Conversation

@ibetitsmike

@ibetitsmike ibetitsmike commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

This PR was authored by Mux, an AI coding agent, working on behalf of Mike.

Problem

When a chatd task attempt dies mid-execute (attempt timer expiry, retryable error, pod replacement), the retry re-reads history, finds the unresolved tool call, and calls StartProcess again. Each retry cycle spawns another OS process in the workspace and the old ones are never killed, producing the orphaned duplicate-process incident class tracked by CODAGT-757 (for example, duplicate long-running builds racing each other in the same worktree).

What this PR changes

This PR introduces a durable execution ledger that owns the external-process lifecycle of local execute tool calls. ChatMachine keeps owning chat semantics and message commits; the ledger records what actually happened to the process, independently of what the chat history says.

Invariant: one logical local tool call creates at most one external process. Later attempts re-attach, observe, reconcile cancellation, or return a stable unknown-outcome result. They never silently start another process.

Schema (migration 000546)

  • chat_tool_call_executions with a UUID primary key generated when the assistant message intent is persisted. The UUID is the stable external-process identity (and becomes the agent idempotency token in PR 2 of this stack).
  • Lineage unique key (chat_id, assistant_message_id, tool_call_id). Provider tool-call IDs can be reused after history regeneration, so a regenerated assistant message creates an independent row instead of mutating the old process identity.
  • input_sha256 over the raw persisted tool input; claims refuse to dispatch against a row created for different input.
  • Lifecycle enum: reserved, starting, running, exited, detached, cancel_requested, canceled, unknown, no_effect.
  • result_committed_at is a timestamp, not a status: it is set in the same transaction that commits the tool result (real or synthetic), so diagnostic lifecycle states like cancel_requested and unknown stay readable after chat history has moved on.
  • claim_epoch + claimed_at implement claim ownership; cancel_signal_sent_at records a delivered but unconfirmed kill.
  • A CHECK ((process_id IS NULL) = (started_at IS NULL)) makes the process-identity invariant structural: a row either has a dispatched process with its start time or neither. timeout_secs records the clamped foreground deadline and is zero for background executions, which have none.
  • Indexes cover retention (created_at), lineage lookups (assistant_message_id), the workspace_agents foreign key (partial index on workspace_agent_id), and the cancellation sweep (partial index on updated_at for cancel_requested rows).

Atomic companions via the ChatMachine transaction

  • The assistant-message commit inserts one reserved intent per execute call in the same transaction (commitGenerationStep).
  • The tool-result commit sets result_committed_at in the same transaction. The old post-commit delete path is gone; rows are never deleted at resolution time.
  • The interrupt commit maps rows atomically with the synthetic cancellation results: background rows with a recorded process handle become detached, reserved rows become canceled, and everything else in flight (foreground starting/running, plus background starts whose handle has not landed yet, plus foreground rows detached by a timed-out wait whose result never committed) becomes cancel_requested, so no row terminalizes as detached without a recoverable handle. The mapping runs before the synthetic results are built and each result derives from its mapped RETURNING row, so the spare-as-detached decision and the handle in the committed result are one observation.
  • Every other transition that resolves outstanding local tool calls with synthetic cancellations (new user message during a run, queued-message promotion, requires-action cancellation/completion, invalid-state reconciliation) runs the same ledger mapping and result_committed_at stamp in its own committing transaction; the periodic sweep converges the cancel_requested rows they leave. Message edit soft-deletes every message from the edited one onward, so before the delete it maps the outstanding executions with background sparing disabled (no surviving result can carry a handle, so every dispatched row becomes cancel_requested for the sweep to kill) and also routes process-bearing rows (running or detached) anchored in the deleted suffix to cancel_requested, because the committed results that carried their process handles are deleted with it; that mapping re-stamps result_committed_at so the sweep's give-up clock restarts at the edit. Abandon and archive deliberately do not map; the turn's calls stay re-attachable. The post-interrupt reconciliation runs after the interruption is published so interrupts stay responsive. A ledger claim that fails on infrastructure aborts the whole local tool batch instead of committing an error result, so the task retry re-claims the intent.

Execute tool flow

  • Before dispatch the tool claims the row: a compare-and-set that takes a reserved intent or a stale (>60s) starting claim, advancing claim_epoch. A fresh starting claim is polled until its owner records a process; a stale one resolves to unknown in this PR (PR 2 upgrades this to a token probe).
  • running/exited/detached rows re-attach via an output snapshot: an exited process commits its real result even past the deadline; a running process with time left is block-waited for the remainder; past the deadline the graceful timed-out result with background_process_id is returned and the row marked detached. Background rows return the process handle directly.
  • Only a definite HTTP 404 (agent reached, process unknown) marks unknown and produces an is_error result saying the command may have run, and only when the probed connection targets the recorded owning agent. When the turn's connection targets a different agent, re-attach dials the recorded owner directly; if that dial fails, the attempt aborts instead of committing a result that would end re-attachment. Transport errors, cancellations, and 5xx keep the lifecycle state unchanged and the process retrievable.
  • Validation failures before dispatch mark no_effect; ID-less tool calls are refused before claiming, since the ledger keys rows by tool call ID. Safety-net resolutions (unknown-state rows, stale-claim expiries, failed re-attach probes) are logged so operators can observe the idempotency net firing. Process identity is recorded on a bounded uncanceled context so an interrupt landing mid-start cannot lose the handle, and lifecycle writes are skipped once the interrupt has canceled the generation context. Foreground wait outcomes (exited/detached) are recorded only when the identity write landed, so a failed write leaves the row starting for claim recovery instead of stranding a terminal row with no handle.
  • Rows the ledger already resolved (unknown, canceled, cancel_requested, no_effect) return their stable results even when the workspace connection cannot be established, and background rows with a recorded handle likewise resolve without a connection (their durable result is the handle itself); only calls that actually need the agent surface connection errors.

Interrupt reconciliation

After the interrupt commit, a reconciler kills recorded processes best-effort: confirmed termination resolves cancel_requested to canceled; a delivered but unconfirmed kill keeps the row cancel_requested with full process identity and cancel_signal_sent_at, so nothing about the process is forgotten just because the kill could not be confirmed. Rows without recorded process identity are polled through a grace window first, because an interrupted in-flight StartProcess can still land its handle via the uncanceled record write: a handle that arrives gets the kill flow (background rows included: their committed synthetic result carries no handle, so sparing them would strand a running process), and only after the window closes does the row resolve to unknown in this PR.

The immediate pass is best-effort, so a periodic per-replica sweep guarantees convergence: every minute it claims cancel_requested rows with process identity whose updated_at is older than a 3-minute retry age (FOR UPDATE SKIP LOCKED; the claim bumps updated_at as a cross-replica lease) and re-runs the kill flow until a terminal outcome is recorded. An interrupted process is eventually killed even when its agent was unreachable at interrupt time or the server died mid-reconciliation. Every pass is deadline-bounded so unreachable agents cannot collapse the retry cadence, and the immediate pass aborts promptly on server shutdown (the sweep backstops it). Rows whose kill can never be confirmed still terminalize: a deleted agent (including the FK nulling workspace_agent_id) resolves to canceled since the process died with its workspace, and a row whose agent merely stays unreachable resolves to unknown a day after its cancellation (anchored on the cancellation commit, so a long-lived call interrupted a day after its dispatch still gets its full kill budget).

Retention

dbpurge deletes ledger rows older than 7 days in bounded batches of 10000 (this is the highest-volume chat table: one row per execute call), but only rows whose tool result was committed: an uncommitted row still guards dedup for a call a future retry may re-execute. Uncommitted rows idle past 30 days are reaped on a separate horizon (a row that old belongs to a turn that will never rerun; without this, deployments without chat retention would grow the table unboundedly). cancel_requested rows are retained regardless of age, since they carry the only stored identity of a process the sweep must kill. Deletion only discards diagnostic history; a still-running detached process stays addressable through the process handle in its committed tool result.

  • dbauthz policies follow the parent-chat pattern (chat ActionUpdate/ActionRead; ResourceSystem + ActionDelete for the purge query). coderd/x/chatd/ARCHITECTURE.md documents the full lifecycle.

What this PR deliberately does not change

  • No agent-side idempotency token; that is PR 2. Without it, a StartProcess response lost in transit can still leak one process; the ledger bounds it to at most one per tool call thereafter.
  • No attempt-idle-timer changes; the resettable watchdog plus 24h absolute cap is PR 3.
  • enterprise/audit/table.go is untouched: this is an operational child table and the audited Chat model is unchanged.
  • Legacy behavior is preserved when no recorder is configured (ExecuteOptions.Recorder == nil), keeping existing chattool unit tests valid.

Test plan

Ran locally against Postgres:

  • go test ./coderd/x/chatd/... (full tree: recorder claim/reattach/terminal-status suites, intent and result-commit atomicity, interrupt mapping with failed-kill retention, late-handle interrupt races, periodic sweep convergence and lease retry, lineage collision after history regeneration, owning-agent-scoped 404 handling)
  • go test ./coderd/database/dbauthz/ -run 'TestMethodTestSuite/TestChats'
  • go test ./coderd/database/dbpurge/ (batched ledger purge; uncommitted rows retained)
  • go test ./coderd/database/migrations/ (new migration + fixture)
  • make fmt, make lint, and make gen with a clean diff after.

Stack

PR 1 of 3 for CODAGT-757 (base: main). PR 2 (#27102, agent-side idempotency token) and PR 3 (#27103, attempt watchdog) build on this branch.

@linear-code

linear-code Bot commented Jul 8, 2026

Copy link
Copy Markdown

CODAGT-757

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 195dde9c71

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/chattool/execute.go Resolved
Comment thread coderd/x/chatd/execution_recorder.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7f08dd6941

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/chattool/execute.go Resolved
Comment thread coderd/x/chatd/execution_recorder.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: a82f75ed7f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mafredri

Copy link
Copy Markdown
Member

/coder-agents-review

@coder-agents-review

coder-agents-review Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Chat: Spend limit reached | View chat
Requested: 2026-07-17 16:20 UTC by @ibetitsmike
Spend: $468.96 / $450.00 (limit reached)

Review history
  • R1 (2026-07-14): 24 reviewers, 4 Nit, 8 Note, 1 P1, 2 P2, 8 P3, REQUEST_CHANGES. Review
  • R2 (2026-07-16): 23 reviewers, 9 Nit, 16 Note, 2 P1, 5 P2, 10 P3, REQUEST_CHANGES. Review
  • R3 (2026-07-16), 9 Nit, 16 Note, 2 P1, 5 P2, 10 P3, COMMENT. Review
  • R4 (2026-07-16), 9 Nit, 16 Note, 2 P1, 5 P2, 10 P3, COMMENT. Review
  • R5 (2026-07-16): 21 reviewers, 10 Nit, 18 Note, 3 P1, 6 P2, 13 P3, REQUEST_CHANGES. Review
  • R6 (2026-07-16): 20 reviewers, 12 Nit, 21 Note, 3 P1, 7 P2, 15 P3, REQUEST_CHANGES. Review
  • R7 (2026-07-16): 18 reviewers, 13 Nit, 23 Note, 3 P1, 8 P2, 16 P3, COMMENT. Review
  • R8 (2026-07-16): 14 reviewers, 13 Nit, 25 Note, 3 P1, 8 P2, 17 P3, COMMENT. Review
  • R9 (2026-07-17): 14 reviewers, 14 Nit, 25 Note, 3 P1, 9 P2, 18 P3, COMMENT. Review
  • R10 (2026-07-17): 13 reviewers, 17 Nit, 26 Note, 3 P1, 9 P2, 18 P3, COMMENT. Review

deep-review v0.9.0 | Round 10 | e489092..260e700

Last posted: Round 10, 73 findings (3 P1, 9 P2, 18 P3, 17 Nit, 26 Note), COMMENT. Review

Finding inventory

Finding inventory - PR #27100

Findings

# Sev Status Location Summary Round Reviewer Posted
CRF-1 P3 Author fixed (reshape: grace poll uses Get, no INSERT) chattool/execute.go:299 awaitRecordedProcess polls via Reserve, issuing a doomed INSERT (PK conflict) each poll R1 Netero Yes
CRF-2 Note Author accepted R2 (test-only field removed; DB column kept as diagnostics-only) execution_recorder.go:109 ExecutionRecord.Command populated but read only by tests R1 Netero Yes
CRF-3 Note Author accepted R2 (unknown is honest; logged, bounded; PR2 token probe) chattool/execute.go:456 RecordStart failure after StartProcess leaves NULL-handle record, burns full 60s grace R1 Netero Yes
CRF-4 P1 Author fixed (reshape: CAS accepts late handle on cancel_requested/detached/starting; reconciler waits identity window; rows not deleted) tasks.go:759 Interrupt races the handle write: NULL-handle reservation is skipped for kill then deleted, so a foreground process started in the StartProcess->RecordStart window is orphaned and unreapable (CODAGT-757 class, via interrupt path) R1 Takumi P1, Mafuuu P2, Komugi P2, Meruem P2, Melody P2, Hisoka P3, Razor P3 Yes
CRF-5 P2 Author fixed (reconcile deferred after publishWatchAndRoute) tasks.go:324 Interrupt kill runs synchronously (serial 5s agent dials) before publishWatchAndRoute, delaying the interrupt's client-visible ack on a slow/unreachable agent, contradicting the stated design goal R1 Kite P2, Killua P3 Yes
CRF-6 P2 Author fixed (Warn logs at recorder+reconciler; rows retained not deleted; no metric) chattool/execute.go:336 Idempotency safety-net failure outcomes (404 unknown-state, transport error, grace expiry) emit only to the model: no log, no metric, and the DB row is deleted after commit, so operators cannot observe or measure the fix firing R1 Chopper Yes
CRF-7 P3 Author fixed (both tool descriptions state 4h clamp) chattool/execute.go:164 4h maxExecuteTimeout clamp on execute timeout and process_output wait_timeout is silent and undocumented in both tool descriptions R1 Leorio P3, Pen-Botter P3, Mafuuu Nit, Ryosuke Nit, Chopper/Kite/Melody/Razor/Luffy Note Yes
CRF-8 P3 Author fixed (batched CTE LIMIT; only result-committed rows) dbpurge/dbpurge.go:297 DeleteOldChatToolCallExecutions runs one unbounded DELETE inside the shared purgeTick transaction, unlike every batched sibling R1 Knuckle P3, Killua Note, Knov Note Yes
CRF-9 P3 Author fixed (DialAgent dials recorded owner; dial failure aborts) chattool/execute.go:268 Re-attach reads process output from the turn's latest agent, not the recorded pinned agent, so a still-running process on a non-latest agent 404s and is declared lost (orphan in multi-agent case) R1 Kurapika P3, Pariston Note Yes
CRF-10 P3 Author fixed (agent captured with conn, per-call options) execution_recorder.go:85 RecordStart attributes the process to the currently-cached agent via connAgentID(), not the agent that served this call's StartProcess, so a mid-turn agent switch with concurrent execute calls records the wrong agent and the interrupt kill 404s R1 Knov Yes
CRF-11 P3 Author fixed (TestProcessOutputToolWaitTimeoutClamp) chattool/execute.go:703 process_output wait_timeout clamp has zero test coverage; deleting the clamp keeps every test green R1 Bisky Yes
CRF-12 P3 Author fixed (grace-window Get failures logged) chattool/execute.go:301 awaitRecordedProcess swallows every Reserve error during the grace poll (no log) then reports the handle as "lost", conflating a transient DB outage with a genuinely-lost process R1 Chopper Yes
CRF-13 P3 Author fixed (completedResult extracted, 4 sites) chattool/execute.go:351 reattachProcess adds a 4th inlined copy of the completed-process ExecuteResult builder (already at 3 sites), inviting drift R1 Robin Yes
CRF-14 Nit Author fixed (negative wait_timeout rejected) chattool/execute.go:707 process_output accepts a negative wait_timeout and silently treats it as an immediate snapshot, while execute rejects non-positive; tools disagree on bad-duration handling R1 Melody Nit, Pen-Botter Note Yes
CRF-15 Nit Author fixed (named constant) generation.go:685 Bare 10*time.Second cleanup bound duplicates a value already named elsewhere (postCommitWatchPublishTimeout); name it R1 Gon Yes
CRF-16 Nit Author fixed (interruptKillDialTimeout/interruptRecordGrace) tasks.go:743 Bare time.Minute interrupt-kill bound sits beside named interruptKillDialTimeout; name it R1 Gon Yes
CRF-17 Nit Author fixed (comment removed) chattool/execute.go:629 marshalResult doc comment restates the signature and carries no information R1 Gon, Leorio Yes
CRF-18 Note Author accepted R2 (unknown honest; PR2 token probe) chattool/execute.go:456 A StartProcess failure whose error result never commits leaves a NULL-handle row that later reports "may have run" for a command that provably never started (distinct root cause from CRF-3) R1 Mafuuu Yes
CRF-19 Note Author fixed (CHECK constraint added to migration) migrations/000544_...up.sql:9 The "process_id and started_at set together or both NULL" invariant lives only in code; a CHECK ((process_id IS NULL) = (started_at IS NULL)) would make it structural R1 Meruem Yes
CRF-20 Note Author accepted R2 (bounded skew, degrades toward more waiting) chattool/execute.go:293 NULL-handle grace and re-attach deadline compare a DB-written CreatedAt/StartedAt against local time.Now(), so effective grace depends on cross-host clock skew (bounded, degrades safely) R1 Hisoka, Meruem, Komugi Yes
CRF-21 Note Author fixed (empty IDs refused; lineage key + input_sha256 guard) execution_recorder.go:39 Reserve does not guard empty/duplicate tool_call_id; two execute calls sharing an ID would silently re-attach to the first's process (package already guards empty IDs elsewhere) R1 Hisoka Yes
CRF-22 Note Author fixed (background timeout_secs=0 + column comment) chattool/execute.go:250 Background execute persists an inert timeout_secs the re-attach never reads; the NOT NULL column reads as "deadline used" but is false for background rows R1 Ryosuke Yes
CRF-23 Note Author fixed (background rows -> cancel_requested, killed not deleted) tasks.go:762 Interrupt deletes a background execution record while intentionally leaving the process running; if the model never received background_process_id (attempt died pre-commit) the process becomes an unmanageable orphan. Document the deliberate orphan in ARCHITECTURE.md R1 Pariston Yes
CRF-24 Note Deferred (CODAGT-811); do not re-evaluate tasks.go:880 Poll loops (awaitInterruptedIdentity tasks.go:880; awaitRecordedProcess execute.go:600; staleStartingClaim execute.go:572; re-attach deadline execute.go:711) read raw time.Now()/time.After instead of the worker's quartz.Clock; ExecuteOptions carries no clock, so correctness-critical race guards are timing-dependent and the sweep-loop ticker is untested end-to-end R2 Netero, Komugi, Bisky, Gon Yes
CRF-25 P1 Author fixed R3 (migration renumbered to 000545, rebased on main) migrations/000544_...up.sql:1 Migration 000544 collides with 000544_mcp_token_refresh_failure already on origin/main; two files at version 544 break golang-migrate load, which is the root cause of the red CI (gen, sqlc-vet, test-go-pg[*], test-go-race, test-e2e all boot the migration set) and would fail coderd at startup. Test plan claims green CI, undisclosed R2 Kite P1, Mafu-san P1 Yes
CRF-26 P2 Author fixed R3 (agent-gone -> canceled; unreachable gives up to unknown after 24h) tasks.go:1099 A cancel_requested row whose owning agent is permanently gone (soft-deleted/stopped, or hard-deleted -> workspace_agent_id NULL) never reaches a terminal status: the dial fails forever, or the RequireMissingProcess guard can't match a process-bearing row. Retention excludes cancel_requested unconditionally, so the row is immortal and re-swept every 3m per replica forever. Falsifies the documented convergence guarantee; unbounded ledger growth at fleet scale R2 Meruem P2, Hisoka P2, Pariston P2, Knov P2, Ryosuke P2, Razor P2, Killua P3 Yes
CRF-27 P2 Author fixed R6 (abort registers on worker ctx, canceled at start of shutdown) tasks.go:817 Deferred reconcileInterruptedExecutions runs on context.WithoutCancel with a 2m bound and is awaited by StartInterrupt->waitForTasks, so server shutdown cannot cancel it; graceful drain blocks up to 2m per in-flight interrupt and the pod is SIGKILLed mid-reconcile. The sweep already backstops convergence, so the block buys nothing R2 Takumi P2, Mafuuu P2, Knov Note, Killua Note Yes
CRF-28 P2 Author fixed R3 (batch size 10000) dbpurge/dbpurge.go:58 Ledger purge drains 1000 rows/10min tick (~144k/day), sized like low-volume chat tables, but this is the highest-volume table (one row per execute call); high-frequency siblings use 10000. Sustained execute traffic above ~1.67 committed-aged rows/sec grows the table and its 4 indexes without bound (distinct from CRF-8) R2 Killua P2 Yes
CRF-29 P3 Author fixed R3 (bounded sweep pass + shared reconcile) tasks.go:1093 sweepOnce reconciles up to 100 rows serially with up to two 5s agent dials each and no per-pass deadline, so a pass over unreachable agents runs ~8-16min while the interval is 1m; the retry cadence collapses under the exact condition (agents down) it exists for. Cap the pass or dial concurrently R2 Knov P3 Yes
CRF-30 P3 Author fixed R3 (schema comment no longer claims an agent token) migrations/000544_...up.sql:42 The id column comment (baked into dump.sql) states it is "the opaque idempotency token sent to the workspace agent", but this PR sends no token to the agent (that is PR 2). Schema asserts present-tense a duplicate-safety mechanism that does not exist, misleading operators. Also the migration/PR "one process" invariant is stated as absolute but is only bounded in PR 1 R2 Leorio P3, Pariston Note Yes
CRF-31 Nit Author fixed R3 (named interruptReconcileTimeout) tasks.go:817 Bare 2time.Minute reconcile timeout literal beside named siblings; it is hand-derived (interruptRecordGrace + 2interruptKillDialTimeout) and drifts silently if a constant changes. Name it or derive it R2 Gon Yes
CRF-32 Nit Author fixed R3 (both plural) dbpurge/dbpurge.go:58 dbpurge constants pluralization mismatch: chatToolCallExecutionRetention (singular) vs chatToolCallExecutionsBatchSize (plural) for the same table R2 Gon Yes
CRF-33 Nit Author fixed R3 (errors.AsType, both sites) chattool/execute.go:671 Predeclared var + xerrors.As should be errors.AsType[*codersdk.Error] (Go 1.26), already the local convention; 2 sites (execute.go:671,962) R2 Ging-Go Yes
CRF-34 Nit Author fixed R3 (tool_call_id in reconciler logs) tasks.go:921 reconcileCancelRequested dial/kill-failure Warn logs omit tool_call_id, the ledger's primary correlation key that every sibling log carries R2 Chopper Yes
CRF-35 Nit Author fixed R3 (receiver p) execution_recorder.go:40 newExecutionRecorder receiver server *Server against the package's dominant p *Server (126 vs 9); the PR's other new method uses p R2 Ryosuke, Zoro Yes
CRF-36 Note Author fixed R3 (enum mirror test + stricter fake) chattool/execute.go:123 chattool.ExecutionStatus enum hand-mirrors the generated database enum and fakeTerminalSources hand-copies production terminalObservationSources; both cross via unchecked string casts with no test/compiler drift guard, so a new value or typo compiles clean and fails only at a live Postgres commit. Add a table test asserting the value sets match R2 Robin, Bisky Yes
CRF-37 Note Author accepted R3 (re-attach skips large-output advisory; small loss accepted) chattool/execute.go:891 detectFileDump advisory (result.Note) is set only on the fresh foreground path, not on re-attach (completedResult) or background resolution, so a retried call loses the large-output nudge; ExecutionRecord lacks command to recompute R2 Melody Yes
CRF-38 Note Author fixed R3 (iterative wait with processWaitRetryDelay + test) chattool/execute.go:1006 waitForProcess re-issues blocking ProcessOutput(Wait:true) via unbounded zero-backoff recursion when the agent returns Running:true with time left; predates the PR but re-attach now routes through it and the retry branch is untested. Could spin for the full remaining timeout and grow the stack R2 Komugi Yes
CRF-39 Note Author fixed R3 (hash round-trip test + HashToolInput contract doc) generation.go:1043 input_sha256 lineage guard is load-bearing but implicit: intent-writer hashes string(part.Args), claim hashes call.Input; any byte divergence fails every execute call closed. Verified consistent today; add a round-trip test and document that HashToolInput callers must pass the persisted bytes R2 Knov (verified Kurapika, Razor, Kite) Yes
CRF-40 Note Author fixed R3 (single shared reconcile dispatch) tasks.go:1054 executionReconciler construction and the "no identity -> wait else kill" dispatch branch are duplicated between the immediate pass (tasks.go:824) and the sweep (tasks.go:1099); the CRF-26 fix must change both in lockstep. Consolidate into one reconcile() method R2 Zoro Yes
CRF-41 Note Author contested R3 (no_effect kept as distinct diagnostic label) execution_recorder.go:203 no_effect is a distinct 9th enum value but terminalRowResponse treats it identically to canceled/cancel_requested; it only buys a diagnostic label. Confirm the distinction is deliberately queried or fold it R2 Luffy Yes
CRF-42 Note Author fixed R3 (documented zero StaleBefore scaffolding) execution_recorder.go:99 The stale-starting-claim takeover arm of the claim CAS (StaleBefore) is never exercised in production (always time.Time{}); it is forward-scaffolding for PR 2's token probe. Add a call-site comment so a future reader does not "fix" the CAS to self-compute staleness and re-enable double dispatch R2 Pariston Yes
CRF-43 P1 Author fixed R7 (mapOutstandingExecutionsForHistoryDelete before soft-delete in EditMessage) chatd/chatstate/transitions.go:557 EditMessage and 7 sibling transitions (new-message-during-run, queued-message promotion, requires-action message, abandon/archive) resolve outstanding execute calls via synthesizePendingToolCancellations but never map/reconcile/commit the ledger row or kill the process; only StartInterrupt (tasks.go) and generation.go:982 touch the ledger. Verified: synthesize is called from 8 transitions.go sites, none touching the ledger. Consequence: an in-flight execute process is orphaned (CODAGT-757 class, reachable by common actions; a regenerated turn can spawn a concurrent duplicate), and the ledger row stays uncommitted/non-terminal so retention cannot reap it R5 Hisoka Yes
CRF-44 P2 Author fixed R6 (map first, derive payload from RETURNING row) tasks.go:304 Interrupt background-payload TOCTOU: interruptedToolResultPayload's process_id GET (tasks.go:304 -> :762) runs before MarkChatToolCallExecutionsInterrupted's mapping (:318) in a READ COMMITTED tx (machine.Update InTx nil TxOptions); a background recordProcessStart committing between them yields a detached (spared, never-killed) row whose committed synthetic result lacks background_process_id -> unaddressable orphan. Fix: map first (RETURNING), build payload from that. Verified ordering + isolation R5 Kite P2, Ryosuke P2 Yes
CRF-45 P3 Author fixed R6 (anchor on cancellation commit; agent-gone check first) tasks.go:884 resolveExpiredCancel anchors the 24h give-up on claimed_at (dispatch time), not the cancellation time, and runs before the kill flow; a cancel_requested row whose call was claimed >24h ago resolves to unknown with zero kill attempts on the first pass -> orphaned live process. Also runs before the agent-gone check, so a >24h + agent-gone row mislabels unknown instead of canceled (diagnostic). Fix: anchor on cancel_signal_sent_at / interrupt updated_at. Verified R5 Mafuuu P3, Knov Note, Kite Note, Bisky Note, Hisoka Note Yes
CRF-46 P3 Author fixed R6 (30-day abandoned-row purge) queries/chattoolcallexecutions.sql:216 The 7-day ledger purge only reaps result_committed_at IS NOT NULL rows, so uncommitted rows (turn abandoned mid-execute, terminal failure with no synthetic result, unclaimed reserved intents, and the CRF-43 transitions) have no time bound; the only other reaper is chat/message CASCADE, gated on chat retention being configured (purgeChats false if GetChatRetentionDays errors, no-op if <=0). Deployments without chat retention grow the table unbounded. Distinct from CRF-28/CRF-26 R5 Killua P3 Yes
CRF-47 P3 Author fixed R6 (timedOutRunningResult helper) chattool/execute.go:723 reattachProcess inlines a 4th copy of the timed-out-still-running ExecuteResult builder (also execute.go:1041 and near-identical :1026); CRF-13 extracted completedResult but left this sibling. New re-attach copy invites drift (message/fields diverge between fresh and re-attach timeout). Extract timedOutRunningResult R5 Robin P3, Zoro Nit Yes
CRF-48 Nit Author fixed R6 (errors.AsType at remaining sites) tasks.go:1012 errors.AsType[*codersdk.Error] convention (CRF-33) missed 3 new sites this PR added: tasks.go:1012 and :1033 (predeclared var + xerrors.As on *codersdk.Error), and the *chattool.AbortToolExecutionError matches at chatloop.go:1130 (xerrors.As) and generation.go:697 (errors.As). Convert to errors.AsType R5 Netero, Meruem, Ging-Go, Pariston, Razor, Robin Yes
CRF-49 Note Author fixed R6 (workspace_agent_id in kill-path logs) tasks.go:999 reconcileCancelRequested dial-failure/kill-failure Warn logs (tasks.go:999,1018) carry chat_id/tool_call_id/process_id but omit workspace_agent_id, the field an operator needs to inspect agent reachability; record.WorkspaceAgentID is in scope. Extends CRF-34 to the kill-path logs R5 Chopper Yes
CRF-50 Note Author fixed R6 (batch-cap + ordering test) dbpurge/dbpurge_test.go:2954 The CRF-8/CRF-28 batch cap (LIMIT @limit_count + ORDER BY created_at ASC) has no test exercising the bound; deleting the LIMIT keeps TestDeleteOldChatToolCallExecutions green. Seed 2 old-committed rows, call with LimitCount:1, assert 1 deleted and the older created_at is gone R5 Bisky Yes
CRF-51 P2 Author fixed R7 (partial index idx_chat_tool_call_executions_uncommitted, migration 000546) queries/chattoolcallexecutions.sql:238 The CRF-46 fix (DeleteAbandonedChatToolCallExecutions) filters/orders on updated_at WHERE result_committed_at IS NULL AND status <> 'cancel_requested' but no index serves it (the only updated_at index is partial WHERE status='cancel_requested', which this excludes). Postgres seq-scans + top-N sorts the highest-volume chat table every 10m inside the shared purgeTick tx. Two EXPLAINs confirm (Killua: 500k rows scanned for 20; Mafu-san: 200k). Fix: partial index (updated_at) WHERE result_committed_at IS NULL. Distinct from CRF-46 (missing time bound, fixed) R6 Meruem P2, Knuckle P2, Mafuuu P2, Killua P2, Ryosuke P2, Chopper P2, Mafu-san P2, Melody P2, Kite P3, Pariston P3, Razor P3 Yes
CRF-52 P3 Author fixed R7 (TestDeleteAbandonedChatToolCallExecutionsBatchLimit) queries/chattoolcallexecutions.sql:225 DeleteAbandonedChatToolCallExecutions's LIMIT+ORDER BY updated_at batch cap has no test; TestDeleteAbandonedChatToolCallExecutions uses LimitCount:1000 with one eligible row, so removing LIMIT/ORDER BY keeps the suite green. Same class as CRF-50, on the new query the CRF-46 fix added. It runs in the shared purgeTick tx, so an uncapped DELETE reintroduces the CRF-8/28 large locking DELETE R6 Netero Yes
CRF-53 P3 Author fixed R7 (production-shaped seeds; agent-gone ordering proven past give-up) execution_sweep_internal_test.go:439 The CRF-45 reorder (agent-gone check before the give-up bound) is untested: AgentFKNulledResolvesCanceled seeds staleAgo=10m so resolveExpiredCancel never fires; reverting the reorder keeps tests green. Also seedCancelRequestedExecution builds cancel_requested with result_committed_at NULL, a shape production never creates, so the give-up test anchors on the claimed_at fallback not the real ResultCommittedAt anchor. Seed past executionCancelGiveUpAfter with result_committed_at stamped old R6 Bisky Yes
CRF-54 Note Author fixed R7 (give-up log logs workspace_agent_id) tasks.go:917 The CRF-49 fix added workspace_agent_id to the two reconcileCancelRequested logs but skipped the resolveExpiredCancel give-up log (fires once at the verdict, the log an operator greps when unknown executions leak); the agent ID is in scope and valid there (agent-gone rows already returned at :866). Add slog.F("workspace_agent_id", ...) R6 Leorio Yes
CRF-55 Nit Author fixed R7 (resolveProcessWait timeout branch uses timedOutRunningResult) chattool/execute.go:1051 The CRF-47 timedOutRunningResult extraction missed the byte-identical timedOut arm in resolveProcessWait (execute.go:1051): it inlines the same Success:false/ExitCode:-1/Error:"command timed out after %s"/Truncated/BackgroundProcessID builder that :1065 now routes through the helper. Convert the timedOut branch to timedOutRunningResult R6 Zoro, Netero Yes
CRF-56 Note Author fixed R7 (unified chatstate.SparedBackgroundResult predicate) chatstate/synthetics.go:140 The map-and-spare decision (Status==detached && ProcessID.Valid -> SparedBackgroundInterruptResult, else generic) is duplicated between mapCanceledExecutions/synthetics.go:140 and committedPendingLocalToolCancellationMessages/interruptedToolResultPayload (tasks.go:787); the payload shape is shared but the spare-detection branch and the two-Mark sequence are not. Drift hazard on the load-bearing Detached contract (same class as CRF-40). Extract InterruptResultForRow(row, genericErr) R6 Zoro, Ryosuke, Netero, Melody Yes
CRF-57 Note Author fixed R7 (renamed SparedBackgroundCancellationResult, reason-neutral note) chattool/execute.go:135 SparedBackgroundInterruptResult hardcodes "the turn was interrupted" for every cancellation transition, discarding the transition-specific reason its non-background siblings carry ("...by message edit", "...by queued message promotion"). Harmless (handle + poll nudge still delivered), but the spared-process note never names the actual cause R6 Gon Yes
CRF-58 Nit Author fixed R7 (dropped doubled doc preamble) chattool/execute.go:958 waitForProcess has a doubled doc-comment preamble: a stale first sentence ("waits for process completion using the blocking process output API instead of polling") restates the mechanism the second sentence already covers. Cut the stale preamble R6 Leorio Yes
CRF-59 P2 Author fixed R8 (SpareBackground param: history-delete passes false -> bg becomes cancel_requested, sweep kills) chatstate/synthetics.go:255 EditMessage's mapOutstandingExecutionsForHistoryDelete spares an in-flight BACKGROUND execute to detached (via MarkChatToolCallExecutionsInterrupted: background AND process_id IS NOT NULL -> detached) but discards the RETURNING rows and commits no synthetic result (the turn is deleted), so the background_process_id is surfaced nowhere. detached is terminal (sweep claims only cancel_requested), so the process runs orphaned/unaddressable; the row is reaped by the 7-day committed purge, losing the handle. CODAGT-757 orphan class via a common action (edit during a background execute); the fix's foreground arm (-> cancel_requested -> killed) is correct. Not a regression (pre-ledger also orphaned) but the ledger has the handle and deliberately spares with no carrier. Fix: on history-delete, route background rows to cancel_requested (kill) not detached. Verified: discard + bg->detached mapping + no result R7 Mafuuu P2, Takumi P2, Hisoka P3, Pariston P3, Razor P3 Yes
CRF-60 P3 Author fixed R8 (ARCHITECTURE.md rewritten: edit own bullet, abandon/archive not-mapping, ordering invariant) ARCHITECTURE.md:911 ARCHITECTURE.md:911 lists "message edit" among transitions that "resolve outstanding local tool calls with synthetic cancellation results" and claims "Spared background rows keep their handle in the committed synthetic result, exactly as at interrupt": false for edit, which deletes the turn and commits no synthetic result (see CRF-59; the new test asserts CancellationMessages empty). It also lists abandon/archive as running the same mapping, but neither maps the ledger (correct behavior; doc overclaims). The load-bearing map-before-delete ordering invariant that made CRF-43 recur 3x is undocumented, so a maintainer consolidating EditMessage into the shared synthesize path could reintroduce the orphan. AGENTS.md requires ARCHITECTURE.md to track chatd architecture changes R7 Leorio P3, Razor P3, Mafuuu Note Yes
CRF-61 Nit Author fixed R8 (callsite comment trimmed to ordering guard) chatstate/transitions.go:547 The callsite comment above mapOutstandingExecutionsForHistoryDelete restates the callee's doc verbatim (same orphan-behind-uncommitted-row rationale); two copies of a load-bearing ordering rationale drift independently. Keep a one-line ordering guard at the callsite ("must run before the soft-deletes") and move the mechanism explanation to the callee doc only. (Gon rated P2; orchestrator downgraded to Nit: comment duplication, not a code defect; the substantive undocumented-invariant concern is CRF-60) R7 Gon Yes
CRF-62 Note Author fixed R8 (outstandingToolCallIDs returns the assistant id; single read) chatstate/synthetics.go:234 mapOutstandingExecutionsForHistoryDelete reads the last assistant message twice (GetLastChatMessageByRole at :234 for the id, then pendingAllToolCallIDs->outstandingToolCallIDs re-runs the identical query). Safe (same tx, chat FOR UPDATE lock, no intervening write) but a redundant round-trip; have outstandingToolCallIDs return the assistant id. Separately, synthesizePendingToolCancellations inlines the same outstanding-call walk outstandingToolCallIDs implements (two mechanisms side by side, drift hazard) R7 Meruem, Takumi, Ryosuke, Zoro, Razor Yes
CRF-63 Note Author fixed R8 (PR description says 000546) ARCHITECTURE.md/PR description The PR description still says the schema is migration 000545; the actual (and only) migration is 000546 (000545 unused). Description-vs-tree mismatch; harmless but may confuse a reader R7 Knov Yes
CRF-64 P3 Author fixed R9 (MarkDetachedChatToolCallExecutionsCancelRequested before soft-deletes; kills detached rows anchored >= edited message) chatstate/synthetics.go:240 The CRF-59 fix kills OUTSTANDING edited-away background executes, but an already-detached background execute (spared by a PRIOR interrupt in the same edited-away turn) is excluded from mapOutstandingExecutionsForHistoryDelete: outstandingToolCallIDs skips handled[] calls (those with a committed tool-result, synthetics.go:348), and the interrupt's synthetic result made it handled. EditMessage then soft-deletes that result (the handle carrier); the detached row survives, the sweep claims only cancel_requested, and the 7-day committed purge reaps it -> orphaned unaddressable process. Violates the PR's own "kill when no committed result carries the handle" invariant for this row. Milder than CRF-59 (handle surfaced once at interrupt; detached is deliberately-alive), so P3. Verified handled-filter mechanism. Fix: kill it (route to cancel_requested) to match the invariant, OR refine the invariant so surfaced-detached processes deliberately survive edits and document it (human decision) R8 Melody Yes
CRF-65 Note Author acknowledged R9 (accepts caller-supplied bool for this PR; safe default; structural hardening queued for planned recomposition) queries/chattoolcallexecutions.sql:150 The spare/kill split now rides a caller-supplied @spare_background bool on the shared MarkChatToolCallExecutionsInterrupted query; the invariant "spare iff a committed synthetic result carries the handle back" lives in the caller's head, not the structure. Both current callers are correct (synthesize/interrupt=true, history-delete=false) and tested. Zero value is false (kill), so a forgotten flag defaults to safe-but-possibly-wrong (kills a carried process); a future history-deleting transition routing through a spare-true path would re-open the orphan. This bool is the surface the next sibling arm would slip through R8 Meruem, Mafu-san, Knov, Bisky, Melody Yes
CRF-66 Note Author fixed R9 (ARCHITECTURE.md edit bullet rewritten) ARCHITECTURE.md:912 The doc bullet says message edit "commits no synthetic results," but EditMessage still calls synthesizePendingToolCancellations + insertMessages after the soft-deletes (transitions.go:563-570); the call returns empty only by construction (delete-then-scan + GetLastChatMessageByRole's deleted=false filter), not because edit skips the path. A future change making the post-delete scan see the deleted turn would silently re-enable the spare=true map and undo CRF-59. Add a one-clause note; behavior is correct today R8 Leorio, Mafu-san Yes
CRF-67 P2 Author fixed R10 (renamed query re-stamps result_committed_at = @updated_at; give-up clock restarts at edit) tasks.go:911, chattoolcallexecutions.sql:173 The CRF-64 fix routes edit-detached rows to cancel_requested but MarkDetachedChatToolCallExecutionsCancelRequested sets only status+updated_at, never result_committed_at. resolveExpiredCancel anchors its 24h give-up bound on result_committed_at (tasks.go:911-912), which for a detached row still carries its ORIGINAL result-commit time (stamped at turn time via generation.go:985). A backgrounded long-running process (the run_in_background dev-server case) edited >24h after its turn is mapped cancel_requested, then reconcile runs resolveExpiredCancel BEFORE the kill flow (tasks.go:866) and resolves it unknown with ZERO kill attempts. unknown is terminal and ClaimStaleChatToolCallExecutionCancels claims only cancel_requested, so the killable, reachable process is orphaned forever: the CODAGT-757 class the PR exists to close, via the edit path CRF-59/CRF-64 hardened. Sibling of CRF-45 (give-up anchor). Not a pre-ledger regression (edited-away bg always orphaned before this PR), capping below P1. Verified: the give-up doc comment's invariant (result_committed_at stamped in the same tx that maps cancel_requested) holds for mapCanceledExecutions (synthetics.go:197) but is FALSE for the new detached path. Fix: stamp result_committed_at = @updated_at in the new query (or a dedicated cancel anchor). R9 Kite Yes
CRF-68 P3 Author fixed R10 (query widened to status IN ('running','detached'), mirroring the interrupt map's process-bearing coverage) chattoolcallexecutions.sql:178 The edit-path rescue MarkDetachedChatToolCallExecutionsCancelRequested matches only status = 'detached'. A background dispatch records its handle (recordProcessStart moves the row starting->running with process_id, execute.go:794) and then calls best-effort markTerminal(Detached) (execute.go:795), whose write is logged and swallowed on failure (execute.go:844). If that write fails, the row stays running with process_id set while its committed result carries background_process_id. Generation advances (the result is committed), so the row lands on a non-last assistant message. On a later edit at/before that turn, mapCanceledExecutions scans only the last assistant message's outstanding calls (miss: this row has a committed result), and the detached query skips it (status != 'detached'). The carrier result is deleted and the process orphans. Distinct from the accepted CRF-3/CRF-18 NULL-handle class: here process_id IS recorded, so the row is killable if mapped. The interrupt path MarkChatToolCallExecutionsInterrupted already matches status IN ('reserved','starting','running','detached'); only the edit path is narrower. Requires a best-effort write failure, so low-probability, single-orphan: P3, matching CRF-64. Fix: widen the query to the process-bearing set the interrupt map uses (status IN ('running','detached')). R9 Takumi Yes
CRF-69 Nit Author fixed R10 (renamed to from_message_id / FromMessageID; query renamed MarkChatToolCallExecutionsCancelRequestedForHistoryDelete) chattoolcallexecutions.sql:177 The query param min_assistant_message_id is compared against assistant_message_id but EditMessage passes target.ID, a USER message id (transitions.go:549). The comparison is correct because chat message ids are a single monotonic sequence across roles, so "assistant_message_id >= edited user message id" selects exactly the suffix turns. But the param name asserts the value is an assistant message id; a maintainer wiring a second caller could pass an actual assistant message id (off by a turn) trusting the name. Rename to from_message_id / MinMessageID. R9 Kite Yes
CRF-70 Nit New R10 migrations/000546_chat_tool_call_executions.up.sql:51 The result_committed_at column COMMENT (baked into dump.sql, shown by \d+ to operators) still says it is only "Set in the transaction that commits the tool result message (real or synthetic). Orthogonal to status." The CRF-67 fix now re-stamps result_committed_at on the history-delete path (MarkChatToolCallExecutionsCancelRequestedForHistoryDelete) where NO tool result message is committed (EditMessage soft-deletes the suffix). So for an edited-away running/detached row the column is stamped with no committed result, contradicting the operator-facing comment. The query comment, synthetics.go, and ARCHITECTURE.md:912 document the dual meaning, but the schema comment still asserts the narrow one. Fix: append a clause (e.g. "History-delete transitions also re-stamp it to the edit time to restart the sweep's give-up bound") and regenerate dump.sql. R10 Knuckle Yes
CRF-71 Nit New R10 ARCHITECTURE.md:933 The give-up paragraph still asserts result_committed_at is "anchored on result_committed_at, which the cancelling transaction stamps and nothing bumps afterwards," which this same commit's edit-path re-stamp contradicts: for an edited-away detached row the original turn-time stamp IS bumped forward by the edit. The commit updated the edit bullet at :912 to document the re-stamp but left the invariant claim 21 lines later at :933 untouched, so the file contradicts itself. A maintainer reading :933 could treat result_committed_at as immutable after first stamp (e.g. as a stable anchor/dedup key). AGENTS.md requires ARCHITECTURE.md to track chatd changes. Fix: reword :933 to note the edit path deliberately re-stamps forward (which only extends the budget, so the conclusion still holds). R10 Meruem Yes
CRF-72 Nit New R10 chatstate/synthetic_cancellation_ledger_test.go:400 TestEditMessage_KillsRunningRowWhoseDetachWriteFailed never asserts its precondition (row is running) before the edit, unlike its detached sibling which guards with require.Equal(..., StatusDetached, "precondition..."). Today the row is genuinely running (mutation-confirmed: reverting to status='detached' fails the test), but if a future setup change let the row reach detached before the edit, the test would keep passing through the detached arm and silently stop guarding CRF-68, the exact regression it exists to catch. Fix: assert require.Equal(..., ChatToolCallExecutionStatusRunning, pre.Status, "precondition: the detach write failed so the row is still running") before the edit. R10 Bisky Yes
CRF-73 Note New R10 chatstate/synthetics.go:251 Give-up-clock freshness for edit-mapped rows depends on two different mechanisms across the two arms: mapCanceledExecutions's NULL-only MarkChatToolCallExecutionsResultCommitted stamp (arm 1, outstanding rows) and the unconditional re-stamp in the widened query (arm 2, already-committed rows), and only arm 2's SQL comment explains the give-up-budget rationale. Behavior is correct today (arm 1 rows are always result_committed_at IS NULL so the conditional stamp freshens them; the two arms are complementary), but a maintainer consolidating the arms or dropping arm 1's ResultCommitted call could silently reopen the zero-kill orphan for outstanding >24h-old running rows with no edit-suite test catching it. Informational; coupling is implicit. R10 Razor, Ryosuke, Meruem Yes

Law analysis

  • R1: Effective LOC +1948 -52 (17 files); 730 production, 1218 test, 399 generated. Head eaf092d. Verdict: Don't split. Enforcement: Advisory.
  • R2: Effective LOC +5493 -150 (28 files); 2224 production, 3269 test, 1261 generated. Test density 59.5%. Head 80aeae9. Verdict: Don't split. Enforcement: Advisory. Crosses the 3000 mandatory trigger, but the eight concerns (schema, generated queries, dbauthz, retention, recorder+execute, interrupt+sweep, docs, tests) are one atomic feature with no separable concern; every cut leaves a dangling stub. Author already split the epic into a 3-PR stack (feat(coderd): track chat execute tool calls in a durable execution ledger #27100/feat: add idempotent start tokens to the workspace agent process API #27102/fix(coderd/x/chatd): keep task attempts alive while execute tools make progress #27103).
  • R10: Effective LOC +7047 -205 (33 files); 2678 production, 4369 test, 1470 generated. Test density 62.0%. Head 260e700. Verdict: Don't split. Enforcement: Advisory. Reran because cumulative growth since the R6 Law run is +668 (>500 threshold). All growth is intra-feature bug-fix depth in the interrupt/edit/sweep reconciliation of one invariant; no new file class, no separable concern, every horizontal/vertical cut leaves a dangling stub or ships a half-invariant. Consistent with R1/R2.

Contested and acknowledged

CRF-2 (Note, execution_recorder.go) - Command written-never-read

  • Finding: ExecutionRecord.Command struct field was populated but consumed only by tests.
  • Author accepted (R2): Removed the test-only struct field; kept the DB command column documented as diagnostics-only. Substantive engagement.

CRF-3 / CRF-18 (Note, chattool/execute.go) - failed/lost start reports "may have run"

  • Finding: A RecordStart failure after a successful StartProcess (CRF-3), or a StartProcess failure whose error result never commits (CRF-18), leaves a row that later reports the command "may have run" when it may not have.
  • Author accepted (R2): A failed StartProcess may or may not have reached the agent, so unknown is the honest outcome; distinguishing local validation failures would need brittle error-string matching. The RecordStart-failure path logs and is bounded by the claim window. PR 2 (feat: add idempotent start tokens to the workspace agent process API #27102) replaces both paths with agent-token probing.

CRF-20 (Note, chattool/execute.go) - cross-host clock skew on grace deadline

  • Finding: The grace/re-attach deadlines compare a DB-written timestamp against the reader's local clock, so effective grace depends on cross-host skew.
  • Author accepted (R2): Skew shifts the window boundedly and degrades safely (toward more waiting, not double dispatch), matching the panel's own note. Correctness rides on CAS by claim_epoch and (PR2) the agent-side token, which compares durations on a single clock.

CRF-37 (Note, chattool/execute.go:891) - large-output advisory lost on re-attach

  • Finding: detectFileDump sets result.Note only on the fresh foreground path; a retried call completing through re-attach or background resolution loses the large-output nudge. ExecutionRecord lacks command to recompute.
  • Author accepted (R3): "re-attach results skip the large-output advisory; accepted small loss." Engages the consequence (retried call loses the nudge) and accepts it with a stated rationale.

CRF-41 (Note, execution_recorder.go:203) - no_effect distinct 9th enum value

  • Finding: no_effect never branches differently from canceled/cancel_requested in terminalRowResponse; it only buys a distinct DB diagnostic label.
  • Author contested (R3): Kept deliberately as a distinct diagnostic label. Panel accepts: a distinct terminal label for "validation failed before dispatch" is a reasonable diagnostic distinction and costs nothing at runtime.

CRF-65 (Note, chattoolcallexecutions.sql) - spare/kill split rides a caller-supplied bool

  • Finding: The @spare_background bool on the shared MarkChatToolCallExecutionsInterrupted query encodes the spare-iff-carrier invariant in the caller's head, not the structure; it is the surface the next sibling arm would slip through.
  • Author acknowledged (R9): Accepts shipping the caller-supplied bool as-is for this PR: both callers are correct and tested, and the zero value is the safe kill direction, so a forgotten flag orphans nothing. Making the split structural is queued for a planned stack recomposition into smaller PRs after this review loop (no linked ticket). Panel accepts: this is an acceptance-with-rationale for this PR, not a bare deferral, and the safe default bounds the risk.

Round log

Round 10 panel

Netero + 14-reviewer panel + Law on head 260e700 (one commit: "restart the kill budget and widen coverage for edit-mapped executions"). Churn guard: PROCEED (CRF-67/68/69 all addressed). All three Round-9 findings verified genuinely fixed and MUTATION-TESTED by multiple reviewers (Netero, Hisoka, Takumi, Kite, Meruem, Melody, Pariston, Mafuuu, Mafu-san, Razor, Ryosuke, Bisky, Knov all ran the two new tests and reverted the fix to confirm they bite): CRF-67 re-stamps result_committed_at = @updated_at so resolveExpiredCancel restarts the 24h give-up clock at the edit (retention-safe: both purges exclude cancel_requested and age on created_at; sole value-consumer is the give-up bound; dual meaning contained); CRF-68 widens to status IN ('running','detached') with NO over-kill (every matched row is in the deleted suffix whose carrier is soft-deleted; a running row always carries process_id via UpdateChatToolCallExecutionProcess + the CHECK, so none is stranded; the two arms are mutually exclusive, not double-writing, because arm 1 moves outstanding rows out of the (running,detached) set first); CRF-69 rename cascade complete across all six layers. Law: Don't split / Advisory (reran, +668 since R6). 11 of 15 reviewers no findings. New: 3 Nits + 1 Note, all doc/test hardening, no bug: CRF-70 (migration column comment for result_committed_at still asserts the narrow "set when result commits" meaning, now contradicted by the re-stamp; operator-facing via dump.sql; Knuckle), CRF-71 (ARCHITECTURE.md:933 still says result_committed_at "nothing bumps afterwards", contradicted by the same commit's :912 re-stamp; Meruem), CRF-72 (the new running-row test lacks a pre-edit precondition assertion, so a future setup drift could silently pass it through the detached arm and stop guarding CRF-68; Bisky), CRF-73 Note (give-up-clock freshness rides two different mechanisms across the two arms; implicit coupling; Razor/Ryosuke/Meruem). One factual disagreement, immaterial to findings: Ryosuke claimed EditMessage cannot run mid-generation (only from R0), while 5 reviewers (Hisoka, Takumi, Melody, Bisky, Knov) cited transition.go allowing edit from R1/running; the over-kill conclusion is identical either way (killing deleted-suffix rows is correct), so no finding turns on it. Event COMMENT (max severity Nit). Reviewed against e489092..260e700.

Round 9 panel

Netero + 14-reviewer panel on head 5c74d97 (Law skipped, +484 since R6 < 500). CRF-64 (P3) and CRF-66 (Note) verified genuinely fixed by the whole panel: the new MarkDetachedChatToolCallExecutionsCancelRequested query routes every detached row anchored >= the edited user message to cancel_requested before the soft-deletes; boundary is off-by-one-free (target is always a user message, assistant ids strictly greater; >= == >), chat-scoped, dbauthz via parent-chat ActionUpdate; TestEditMessage_KillsPriorDetachedExecutions covers both arms (kill-on-deleted-carrier, spare-on-surviving-carrier) and fails under a neutered query (Bisky/knov mutation-tested). 11 of 15 reviewers no findings. New: 1 P2 (CRF-67: the edit-detached path never refreshes result_committed_at, so resolveExpiredCancel's 24h give-up bound resolves a >24h-old backgrounded process to unknown with zero kill attempts, orphaning it; Kite, orchestrator-verified against tasks.go:911 + generation.go:985 + synthetics.go:262), 1 P3 (CRF-68: the status='detached'-only edit query misses a running-with-committed-handle row left by a failed best-effort markTerminal(Detached); the interrupt map covers running, the edit map does not; Takumi, orchestrator-verified against execute.go:794-795,844 + query text), 1 Nit (CRF-69: min_assistant_message_id param name vs passed user-message id; Kite). Note the disagreement on CRF-68: 6 reviewers (Meruem, Melody, Pariston, Knuckle, knov, Razor) asserted "running never carries a committed result"; that holds only on the happy path. Takumi traced the best-effort-write-failure exception, which the orchestrator confirmed reachable with process_id recorded. Event COMMENT (max severity P2). Reviewed against e489092..5c74d97.

Round 9 update

Churn guard: PROCEED. New head 5c74d97 (one commit: "kill prior-detached background executes when an edit deletes their handle carrier"). CRF-64 addressed (Mike's decision: option A/kill), CRF-66 addressed (doc), CRF-65 acknowledged (caller-supplied bool accepted for this PR + safe default; structural fix queued for planned stack recomposition, no ticket but a real acceptance rationale, not a bare deferral). Effective additions 6652 -> 6863 (+211; Law does not re-run, +484 since R6 < 500). CI green. Key verification: the new MarkDetachedChatToolCallExecutionsCancelRequested query + mapExecutionsForHistoryDelete(fromMessageID) boundary - detached rows anchored at/after the edited message must go to cancel_requested (killed), rows anchored BEFORE must keep their carriers (untouched); check the boundary (>= assistant_message_id) for off-by-one, chat-scoping, and whether ANY detached shape is not anchored by assistant_message_id (the next sibling). Reviewed against e489092..5c74d97.

Round 8 panel

Netero + 14-reviewer panel on head 57579ad (Law skipped, +30). All 5 round-7 findings (CRF-59..CRF-63) verified genuinely fixed: CRF-59 via the SpareBackground split (all 3 callers pass the correct value, CASE correct, edited-away bg -> cancel_requested -> sweep kills, no 4th caller; safe default is false/kill), CRF-60 doc rewrite accurate, CRF-61/62/63. 12 of 15 reviewers no findings; Hisoka explicitly hunted the sibling and cleared it on the outstanding path. New: 1 P3 (CRF-64: the recurring sibling for the ALREADY-detached case - a background execute spared by a prior interrupt then edited-away has its handle carrier deleted but is not swept, orphaning it; violates the PR's own kill-when-no-carrier invariant; Melody, verified), 2 Note (CRF-65 spare_background caller-dependency, CRF-66 doc-vs-structure). Event COMMENT (max P3). Reviewed against e489092..57579ad.

Round 8 update

Churn guard: PROCEED. New head 57579ad (one commit: "kill edited-away background executes instead of sparing them"). All 5 round-7 findings (CRF-59..CRF-63) have code changes; panel verifies. Effective additions 6622 -> 6652 (+30; Law does not re-run). CI green. Key verification: the new SpareBackground param on MarkChatToolCallExecutionsInterrupted (a shared mapping query) - every caller must pass the correct value (synthetic-result transitions + interrupt = true/spare; history-delete = false/kill), the CASE must branch correctly, and edited-away background rows must become cancel_requested and actually be killed by the sweep. Also verify the ARCHITECTURE.md rewrite is accurate and no new sibling arm bypasses the mapping. Reviewed against e489092..57579ad.

Round 7 panel

Netero + 18-reviewer panel on head 43be9cf (Law skipped, +243 < 500). All round-6 findings verified genuinely fixed: CRF-43 foreground arm (mapOutstandingExecutionsForHistoryDelete before soft-delete, only EditMessage deletes history, no sibling bypass, orchestrator-verified), CRF-51 (partial index idx_..._uncommitted, migration renumbered 000546 no collision), CRF-52/53/54/55/56/57/58. New findings: 1 P2 (CRF-59: the CRF-43 fix spares in-flight BACKGROUND executes to detached but drops the handle since the edited turn commits no result -> orphaned unaddressable process; 5-reviewer convergence, orchestrator-verified; the foreground sibling the round-5/6/7 pattern predicts), 1 P3 (CRF-60 ARCHITECTURE.md:911 falsely claims edit preserves the spared handle + undocumented ordering invariant), 1 Nit (CRF-61), 2 Note (CRF-62 double-fetch, CRF-63 stale migration number in description). Event COMMENT (max severity P2). Reviewed against e489092..43be9cf.

Round 7 update

Churn guard: PROCEED. New head 43be9cf (one commit: "map edited-away executions and index the abandoned purge"). All round-6 findings (CRF-43 P1 re-raise + CRF-51..CRF-58) have code changes; panel verifies. Effective additions 6379 -> 6622 (+243, Law does not re-run). CI green. Key verification targets: the CRF-43 fix (mapOutstandingExecutionsForHistoryDelete before EditMessage's soft-delete; third attempt at this P1) and whether any sibling history-deleting transition still bypasses it; new index migration 000546 (no collision). Reviewed against e489092..43be9cf.

Round 6 panel

Netero + Law + 20-reviewer panel on head 3e73ff1 (first panel on the R5 fixes). Verified genuine: CRF-27 (worker-ctx abort now fires before the drain, R5 re-raise resolved), CRF-44 (map-first, TOCTOU closed), CRF-45 (anchor on result_committed_at + agent-gone-first), CRF-48/49/50 and mostly CRF-47. New findings: 1 P1 re-raise (CRF-43: mapCanceledExecutions is inert on EditMessage, which soft-deletes the in-flight assistant message before synthesize; 5-reviewer convergence + orchestrator-verified), 1 P2 (CRF-51: CRF-46's abandoned-purge query is unindexed -> seq-scan of the highest-volume table every 10m, 2 EXPLAINs), 2 P3 (CRF-52 batch-cap untested, CRF-53 CRF-45 reorder untested), 4 Nit/Note (CRF-54..CRF-58). Event REQUEST_CHANGES. Reviewed against e489092..3e73ff1.

Round 6 update

Churn guard: PROCEED. New head 3e73ff1 (one commit: "map the execution ledger in every cancellation transition and fix interrupt races"). All 8 round-5 findings (CRF-43..CRF-50) plus the CRF-27 re-raise have code changes; panel verifies. Effective additions 5845 -> 6379. CI green. This is the first panel pass on the round-5 fixes, notably the CRF-43 P1 fix (mapCanceledExecutions wired into 8 cancellation transitions) and the CRF-27/CRF-44/CRF-45 concurrency reorders. Reviewed against e489092..3e73ff1.

Round 5 panel

First panel pass on head aa4a05f (R3/R4 were BLOCKED). Netero + 21-reviewer panel (Law skipped: +352 LOC since R2, under 500). All round-3 fixes (CRF-25/26/28/29/30/33/34/36/38/39/40/42) verified genuine by multiple reviewers. New findings: 1 P1 (CRF-43 ledger not wired into edit/promotion/archive cancellation transitions), 1 P2 re-raise (CRF-27 shutdown-abort inert: AfterFunc on s.server.ctx fires only after chatWorker.Close(), which blocks on the reconcile; verified via chatd.go:4697/4707 + worker/runner drain), 1 new P2 (CRF-44 background-interrupt payload TOCTOU under READ COMMITTED), 3 P3 (CRF-45 give-up anchored on claim time; CRF-46 uncommitted rows escape purge; CRF-47 timed-out result builder 4th copy), 1 Nit (CRF-48 errors.AsType missed 3 sites), 2 Note. Event REQUEST_CHANGES. Reviewed against e489092..aa4a05f.

Round 5 update

Churn guard: PROCEED. CRF-24 now deferred with linked ticket CODAGT-811 (quartz.Clock threading + mock-clock/sweep-ticker tests); do not re-evaluate. Head aa4a05f has never been panel-reviewed (R3/R4 were BLOCKED), so the round-3 fix commits (CRF-25 renumber, CRF-26 terminal give-up, CRF-27 AfterFunc shutdown, CRF-28 batch 10000, CRF-29 bounded sweep, CRF-33/34/36/38/39/40/42) get their first panel pass this round. Reviewed against e489092..aa4a05f.

Round 4 update

Churn guard: BLOCKED. Head unchanged since round 3 (aa4a05f); no new commit. Author re-triggered /coder-agents-review without addressing CRF-24 and marked the CRF-24 thread Resolved with no code change, no linked ticket, and no substantive acceptance, so it is still silent. Re-posted the COMMENT block: marking the thread Resolved does not satisfy the gate; the finding needs a fix, a tracked ticket, or an explicit human accept. No panel spawned. Reviewed against e489092..aa4a05f.

Round 2 update

Churn guard: PROCEED (18 addressed, 5 acknowledged, 0 contested/deferred/silent). PR substantially reworked into a durable execution ledger (effective additions +1948 -> +5493). CI is currently red (gen, lint, sqlc-vet, test-go-pg, test-go-race-pg, test-e2e). Panel re-runs against the reshaped code. Base 21d0824..head 80aeae9.

Round 3 update

Churn guard: BLOCKED. New head aa4a05f (base rebased onto main, e489092). Of 19 round-2 findings: 16 addressed, 1 acknowledged (CRF-37), 1 contested (CRF-41), 1 silent (CRF-24). CI now green. No panel spawned this round: CRF-24 (Note) was deferred as "follow-up testability work" with no linked ticket and no code change, which blocks under the no-follow-up-without-ticket rule. Posted COMMENT (not REQUEST_CHANGES) asking the author to fix CRF-24, file a tracked ticket, or explicitly accept the gap, then re-request review. All P0-P3 findings from R1/R2 are resolved. Reviewed against e489092..aa4a05f.

Round 2 panel

Netero + Law + 23-reviewer panel. Root cause of the red CI found: CRF-25 (P1) migration 000544 collides with 000544_mcp_token_refresh_failure now on main (verified via git ls-tree origin/main). New findings: 1 P1, 3 P2 (CRF-26 seven-reviewer convergence on non-converging cancel_requested rows; CRF-27 shutdown-drain block; CRF-28 purge batch under-sized), 2 P3, 5 Nit, 8 Note. Event REQUEST_CHANGES. Reviewed against 21d0824..80aeae9.

Round 1

Netero + Law infrastructure pass, then 24-reviewer panel. Netero: 1 P3 + 2 Notes (mechanical floor clean). Law: Don't split (advisory). Panel: 1 P1 (CRF-4, 7-reviewer convergence), 2 P2 (CRF-5, CRF-6), 10 P3, 4 Nit, 6 Note. Event REQUEST_CHANGES on the P1. Reviewed against 344a977..eaf092d.

About deep-review

CRF = Coder Review Finding (P0-P4, Nit, Note)

Reviewer Focus
Bisky tests
Chopper ops/errors
Churn-guard change verification
Ging language modernization
Gon naming
Hisoka edge cases
Killua perf
Kite change integrity
Knov contracts
Knuckle SQL
Komugi flake/determinism
Kurapika security
Law decomposition
Leorio docs
Luffy product
Mafu-san process
Mafuuu contracts
Melody dispatch/pairing
Meruem structural
Nami frontend
Netero mechanical checks
Pariston premise testing
Pen-botter product gaps
Razor verification
Robin duplication
Ryosuke Go arch
Takumi concurrency
Zoro shape

🤖 Managed by Coder Agents.

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a well-scoped, well-tested fix for a real incident class (CODAGT-757). The reserve-then-start compare-and-set on (chat_id, tool_call_id) is the right primitive for electing exactly one creator across retries and coderd instances, the timeout round-up correctly stops a sub-second timeout from reconstructing as an instant 0s on re-attach, the 404-only unknown-state synthesis has exactly the right blast radius, the dbauthz policies follow the parent-chat pattern, and 62.5% test density with real negative assertions (background-survival, timed-out-spare) is strong. Law's verdict: don't split, this is one reviewable idea.

The panel found one blocker. CRF-4 (P1, seven reviewers converging) is the incident class this PR exists to eliminate, reintroduced through the interrupt path. An interrupt landing in the StartProcess->RecordStart window reads a NULL-handle reservation, skips the kill, then deletes the row, so the just-started foreground process is never signaled and the handle write fails with sql.ErrNoRows. The process runs orphaned for the life of the workspace with no record left to reap it. The interrupt tests only fire after the handle is recorded, so this window is uncovered. This is distinct from the PR-2 transport-loss gap: here the process started and coderd had the handle, and the interrupt path itself destroyed the reservation.

Two P2s: the interrupt kill runs synchronously (serial per-agent 5s dials) before the status-change publish, so a slow or unreachable agent delays the interrupt's client-visible ack, contradicting the stated "a slow or unreachable agent never delays the interrupt" goal (CRF-5); and the idempotency safety net is invisible to operators (no log, no metric, row deleted after commit) for a change whose entire justification is operational (CRF-6).

The rest are P3 and below: two independent agent-identity mismatches that can defeat the interrupt kill and re-attach in the multi-agent case (CRF-9, CRF-10), an unbounded purge DELETE that diverges from every batched sibling (CRF-8), a silent and undocumented 4h timeout clamp the model cannot see (CRF-7, the widest convergence in the panel), a missing test for that clamp (CRF-11), plus assorted correctness edges, duplication, and schema-hardening notes.

Process note: two intermediate commit subjects exceed 72 chars (record process starts on an uncanceled context... at 99, scope timeout validation to foreground... at 87). Both bodies are excellent; harmless if this squash-merges under the 70-char PR title.

Hisoka summed up the panel's read: "You built something that holds up under most of what I threw at it. A good fight."

No finding here has a follow-up owner assumed. Please fix CRF-4 in this PR or state explicitly why the orphan window is acceptable.


coderd/x/chatd/chattool/execute.go:707

Nit [CRF-14] process_output accepts a negative wait_timeout and silently treats it as an immediate snapshot, while execute rejects a non-positive timeout. (Melody Nit, Pen-Botter Note)

execute rejects parsed <= 0 with "timeout must be positive"; process_output applies min(parsed, maxExecuteTimeout) then guards if timeout > 0, so -5s falls through to a non-blocking snapshot with no error, and the description documents only 0s as the snapshot sentinel. Reject parsed < 0 (or document that any non-positive value means snapshot) so the two tools agree on what a bad duration is.

🤖

🤖 This review was automatically generated with Coder Agents.

Comment thread coderd/x/chatd/tasks.go Resolved
Comment thread coderd/x/chatd/tasks.go Resolved
Comment thread coderd/x/chatd/chattool/execute.go Resolved
Comment thread coderd/x/chatd/chattool/execute.go Resolved
Comment thread coderd/database/dbpurge/dbpurge.go Resolved
Comment thread coderd/x/chatd/execution_recorder.go Resolved
Comment thread coderd/x/chatd/chattool/execute.go Resolved
Comment thread coderd/x/chatd/tasks.go Resolved
Comment thread coderd/x/chatd/chattool/execute.go Resolved
@ibetitsmike ibetitsmike changed the title fix(coderd): make chat execute tool starts idempotent under task retry feat(coderd): track chat execute tool calls in a durable execution ledger Jul 15, 2026
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

1 similar comment
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 621accc3d7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a5d02fd7d7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/execution_recorder.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 82e924ca69

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/tasks.go Resolved
Comment thread coderd/x/chatd/chattool/execute.go Resolved
Comment thread coderd/x/chatd/chattool/execute.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8a6621e801

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/tasks.go Resolved
Comment thread coderd/x/chatd/chattool/execute.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0769f2f6a5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/chattool/execute.go Resolved
Comment thread coderd/x/chatd/chattool/execute.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6eaf2dc23d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/tasks.go Resolved
Comment thread coderd/x/chatd/chattool/execute.go Resolved
Comment thread coderd/x/chatd/chattool/execute.go Resolved
Comment thread coderd/x/chatd/tasks.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 552a7e0d0b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3b3eb34a04

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/chatd.go Resolved

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 9. The CRF-64 prior-detached-carrier orphan (P3) and the CRF-66 doc mismatch (Note) are both genuinely fixed, and CRF-64 is fixed with the right shape: instead of squeezing the kill decision back through the last-assistant outstanding scan that let the sibling slip for five rounds, the new MarkDetachedChatToolCallExecutionsCancelRequested anchors on durable ledger state and routes every detached row anchored at or after the edited message to cancel_requested before the soft-deletes. Eleven of fifteen reviewers found nothing. The panel verified the boundary is off-by-one-free (the edit target is always a user message, so assistant_message_id >= target.ID equals > target.ID and equals "the carrier is in the deleted suffix"), chat-scoped, and authorized via the parent-chat ActionUpdate pattern; TestEditMessage_KillsPriorDetachedExecutions exercises both directions and was mutation-tested (it fails when the new query or its >= predicate is neutered).

The recurring "fix the named arm, leave a sibling" class has narrowed but not fully closed. Two new gaps surfaced on the paths this fix touches:

  • CRF-67 (P2): the edit-detached mapping never refreshes result_committed_at, so the sweep's 24h give-up bound gives up on a long-lived backgrounded process with zero kill attempts and resolves it unknown, orphaning exactly the process this PR exists to reap.
  • CRF-68 (P3): the edit query matches only status = 'detached', while the interrupt map it mirrors also covers running; a running row that kept a committed handle after a failed best-effort terminal write is missed on edit.

One Nit on parameter naming (CRF-69). CRF-65 (caller-supplied @spare_background bool) remains acknowledged for this PR with a stated rationale and a safe default; not re-raised.

🤖 This review was automatically generated with Coder Agents.

Comment thread coderd/x/chatd/tasks.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

Round 9 disposition

All Round 9 findings are addressed in 260e700 (fix(coderd): restart the kill budget and widen coverage for edit-mapped executions).

CRF-67 (P2): edit-mapped rows kept a stale give-up anchor. Fixed. The history-delete mapping re-stamps result_committed_at = updated_at in the same UPDATE, so the sweep's 24h give-up bound starts at the edit and a long-detached process gets its full kill-retry budget instead of resolving unknown with zero attempts. resolveExpiredCancel's documented invariant (stamped in the same transaction that maps the row cancel_requested) holds for this path again. Test: TestExecutionSweep/EditOfOldDetachedRowStillKills (fails without the restamp: the mocked kill is never attempted).

CRF-68 (P3): edit rescue narrower than the interrupt map. Fixed. The query (renamed to MarkChatToolCallExecutionsCancelRequestedForHistoryDelete) now matches status IN ('running', 'detached'), covering a running row whose best-effort detach write failed but whose committed result carries the handle. Test: TestEditMessage_KillsRunningRowWhoseDetachWriteFailed.

CRF-69 (Nit): misleading parameter name. Fixed. min_assistant_message_id renamed to from_message_id, with a comment stating the value is the edited message's own ID (any role) and why comparing it against assistant_message_id is correct.

Validation: make gen clean, go build ./coderd/... ./agent/..., full chatstate package, chatd sweep/reconcile tests, and the dbauthz method suite, all green locally. PR2/PR3 restacked and pushed; PR1 description updated.

This comment was written by Mux, an AI coding agent, acting on Mike's behalf.

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

@coder-agents-review

Copy link
Copy Markdown
Contributor

@ibetitsmike ⛔ This review has reached its per-chat spend limit ($426.41 / $400.00). Further review rounds are paused.

To raise the limit and continue, comment:

/coder-agents-review set-spend-limit:450

This is a per-chat budget, separate from any account-level usage limit.

🤖 Managed by Coder Agents.

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review set-spend-limit:450

@coder-agents-review

Copy link
Copy Markdown
Contributor

OK fine, @ibetitsmike, $450.00 it is... but I'm telling finance about this. 💸

🤖 Managed by Coder Agents.

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 10. The three open Round-9 findings are all genuinely fixed by one surgical commit, and the panel verified each with mutation tests rather than admiration: reverting the result_committed_at re-stamp flips the sweep test to unknown with zero kill attempts, and narrowing the status set back to detached leaves the failed-detach-write row orphaned. CRF-67 (re-stamp restarts the 24h give-up clock at the edit) is retention-safe: both purge queries exclude cancel_requested and age on created_at, and the only value-consumer of the column is the give-up bound, which wants the cancellation time. CRF-68 (widen to status IN ('running','detached')) does not over-kill: every matched row is anchored in the deleted suffix whose carrier is soft-deleted, a running row always carries process_id (so none is stranded), and the outstanding arm moves last-message rows out of the set before the widened query runs, so the two arms are mutually exclusive rather than double-writing. CRF-69's rename cascade is complete across all six layers. Law reran (growth since Round 6 crossed the split threshold) and holds Don't split / Advisory: the growth is intra-feature bug-fix depth, not new scope.

Eleven of fifteen reviewers found nothing. What remains is documentation and test hardening, no behavioral defect: two stale doc assertions that this same commit's re-stamp now contradicts (CRF-70, CRF-71), a missing test precondition (CRF-72), and one note on an implicit cross-arm coupling (CRF-73).

🤖 This review was automatically generated with Coder Agents.

Comment thread coderd/x/chatd/ARCHITECTURE.md Resolved
Comment thread coderd/x/chatd/chatstate/synthetics.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

Round 10 disposition

All Round 10 items are addressed in 07140fe (docs(coderd): document the edit-path give-up re-stamp and guard the running-row test precondition). No behavioral changes; the round found no defects.

CRF-70 (Nit): migration column comment for result_committed_at now documents the history-delete re-stamp; dump.sql regenerated.
CRF-71 (Nit): ARCHITECTURE.md give-up paragraph no longer claims nothing bumps the anchor; it documents the deliberate edit-path re-stamp and why the budget conclusion holds.
CRF-72 (Nit): the running-row test asserts its precondition before the edit, matching the detached sibling's guard.
CRF-73 (Note): the complementary anchor-freshening mechanisms of the two mapping arms are documented on mapExecutionsForHistoryDelete, including the consolidation hazard.

Validation: make gen clean, targeted chatstate test green, pre-commit hook (lint/go) passed. PR2/PR3 restacked and pushed.

This comment was written by Mux, an AI coding agent, acting on Mike's behalf.

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

@coder-agents-review

Copy link
Copy Markdown
Contributor

@ibetitsmike ⛔ This review has reached its per-chat spend limit ($468.96 / $450.00). Further review rounds are paused.

To raise the limit and continue, comment:

/coder-agents-review set-spend-limit:500

This is a per-chat budget, separate from any account-level usage limit.

🤖 Managed by Coder Agents.

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

Superseded by the recomposed CODAGT-757 stack: #27317, #27318, #27319, #27320, #27321, #27322, #27323, #27324, #27325. The combined final tree of the new stack is byte-identical to the reviewed heads of this stack (minus an accidental workflow orchestration file); the recomposition splits the work into reviewable pieces.

This comment was posted by Mux, an AI coding agent, on Mike's behalf.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants