Commit Graph
5 Commits
Author SHA1 Message Date
Michael Suchacz 39c4bd6ced refactor(coderd/x/chatd): drop the unused runnerCtx from the runner debug turn (#31010)
Deletes `runnerDebugTurn.runnerCtx` and the context parameter of
`newRunnerDebugTurn`. The field's only reader was the
`LaunchRunHeartbeat` call in `ensureLocked`, which #30988 deleted with
the run heartbeats, so nothing has read it since.

**Why it is safe:** the constructor set the field and no code read it.
The debug turn still uses the context of each call to `Ensure`,
`Context` and `Finalize`, which this PR does not change. `runner.go` and
10 tests stop passing a context, and four of those tests drop the
`context.WithCancel` that they created only for this parameter.

Validation:
- `go build ./coderd/x/chatd/...` and `go vet ./coderd/x/chatd/...`
pass.
- The 25 chatd debug-run tests, `TestRecordGenerationFinishFailure`,
`TestSessionStartDispatchFailureFinishesGeneration` and
`TestStartGeneration_CancelsDeletedToolCallsOnAgent` pass under `-race`.
- `golangci-lint run --fix=false ./coderd/x/chatd/` reports 0 issues,
and the pre-commit hook passed.

## Stack

This stack deletes the stale debug-run sweep, then simplifies the
chatdebug debug-run, stream wrapper and step numbering code, drops the
indexes the sweep used, and last deletes a runner debug field that lost
its only reader with the heartbeats. The debug-run and stream wrapper
refactors each sit on a test-only layer that pins the behavior they
keep.

1. #30988 Delete the chat debug run and step heartbeats
2. #30989 Delete `FinalizeStale` and the stale threshold
3. #30995 Delete the `FinalizeStaleChatDebugRows` query
4. #30933 Pin the debug runs that turns, titles and status labels record
5. #30934 Create and finalize debug runs through one helper
6. #30980 Table the stream wrapper tests and cover their status rules
7. #30981 Share one finalize-once lifecycle between the stream wrappers
8. #31007 Number chat debug steps in the database
9. #31008 Delete the process-global step counters
10. #31009 Drop the chat debug stale-sweep indexes
11. This PR: Drop the unused `runnerCtx` from the runner debug turn

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-22 07:55:42 +00:00
Michael Suchacz e8882b6b51 refactor(coderd/x/chatd): create and finalize debug runs through one helper (#30934)
Chat turns, manual titles, automatic titles and turn status labels each
created a debug run on a detached, time-bounded context, rebuilt the run
context from the row, and finalized the run by hand. This PR adds
`chatdebug.Service.BeginRun` and `StartRun` and routes all four through
them. It deletes `prepareQuickgenDebugCandidate`, `shortTextCandidate`,
`chatdebugRunContext`, `debugCreateRunTimeout` and a literal 5 second
insert timeout.

- `BeginRun` inserts the run on a context that ignores the caller's
cancellation, with a 5 second limit, and builds the `RunContext` from
its parameters. Chat turns call it and still finalize in
`runnerDebugTurn`.
- `StartRun` wraps `BeginRun` for one model call and returns a context
that carries the run plus a function that finalizes it from the call's
error. Titles and status labels use it.
- New `TestService_StartRun` covers a finalized run, a failed insert and
a failed finalize with a mock store, including the seed summary that
each finalize keeps and the warning that each failure logs.

**Why it is safe:** #30933 pins the insert parameters, the run context,
the finalize status and summary, and the failed insert for all four call
sites. Those tests and the other debug-run, title and quickgen tests
pass before and after. `CreateRun` stores its parameters unchanged, so a
`RunContext` built from the parameters equals one built from the row. A
repo-wide search finds no reference to the deleted symbols. Of 14
mutants of `BeginRun` and `StartRun`, 13 fail `TestService_StartRun`.
They drop either failure warning, report a failed insert as success, let
the insert inherit the caller's cancellation or lose its deadline, drop
the parent chat or the history tip from the run context, drop the seed
summary from the insert or the finalize, ignore the call error or the
finalize timeout, leave the run out of the returned context, or finalize
the wrong run. The survivor shortens the insert limit from 5 seconds to
1.

**Review focus:** log output. Create and finalize failures now log
through the chatdebug logger as `failed to create debug run` and `failed
to finalize debug run`. Before, each call site used its own logger and
message. Compaction still creates its debug run by hand, because #30766
changes that code; it can move to `StartRun` after that PR merges.

**Moved onto the deletion stack:** a merge commit moved this layer onto
the updated #30933 without a force push. It carries one forced change:
#30989 removed the `database/sql` import from
`chatdebug/service_test.go` with the last test that used it, and
`TestService_StartRun` here still uses `sql.NullString`, so the merge
adds the import back. The rest of the diff is unchanged.

Validation:
- `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/ -run
'^(TestActiveServer_ChatTurnDebugRun.*|TestRunnerDebugTurn.*|TestProposeChatTitle_DebugRun|TestArchiveChatDeletesDebugRuns|TestEditMessageDebugCleanup.*|TestQuickgen.*|TestMaybeGenerateChatTitle.*|TestPrepareManualTitleDebugRunCreateFailure)$'`:
the same 25 tests pass before and after, and again after the move.
- `go test -race -count=1 -p 4 -parallel 4
./coderd/x/chatd/chatdebug/...` passes.
- `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...
./coderd/x/chatd/` reports 0 issues, and the pre-commit hook passed.

## Stack

This stack deletes the stale debug-run sweep, then simplifies the
chatdebug debug-run, stream wrapper and step numbering code, drops the
indexes the sweep used, and last deletes a runner debug field that lost
its only reader with the heartbeats. The debug-run and stream wrapper
refactors each sit on a test-only layer that pins the behavior they
keep.

1. #30988 Delete the chat debug run and step heartbeats
2. #30989 Delete `FinalizeStale` and the stale threshold
3. #30995 Delete the `FinalizeStaleChatDebugRows` query
4. #30933 Pin the debug runs that turns, titles and status labels record
5. This PR: Create and finalize debug runs through one helper
6. #30980 Table the stream wrapper tests and cover their status rules
7. #30981 Share one finalize-once lifecycle between the stream wrappers
8. #31007 Number chat debug steps in the database
9. #31008 Delete the process-global step counters
10. #31009 Drop the chat debug stale-sweep indexes
11. #31010 Drop the unused `runnerCtx` from the runner debug turn

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-20 22:11:25 +00:00
Michael Suchacz 2397f3953a refactor(coderd): delete the chat debug run and step heartbeats (#30988)
Deletes the chat debug heartbeats. Model calls and streams started a
goroutine that touched the step and its run on a ticker, and runner
debug turns started a second one that touched the run. Both existed so
that `FinalizeStale` would not mark a live run as interrupted, but
nothing in production calls `FinalizeStale` since #26270. Mike chose to
delete the stale sweep as dead code. This PR is the first of three that
do it.

- `chatdebug/model.go`: `Generate`, `GenerateObject` and both stream
wrappers no longer start `launchHeartbeat`.
- `active_turn_debug.go`: the runner debug turn no longer starts
`LaunchRunHeartbeat`.
- `chatdebug/service.go`: deletes `TouchStep`, `TouchRun`,
`LaunchRunHeartbeat`, `heartbeatInterval`, and the channel that
`SetStaleAfter` closed to wake the heartbeats. The `WithClock` doc no
longer names the heartbeat tickers.
- Deletes the `TouchChatDebugStepAndRun` and
`TouchChatDebugRunUpdatedAt` queries with their dbauthz wrappers and
tests, and `TestLaunchHeartbeat`. `TestFinalizeStaleChatDebugRows` now
backdates its run with `UpdateChatDebugRun` instead of the deleted
test-only query.

**Why it is safe:** the heartbeats wrote only `updated_at` on
`chat_debug_runs` and `chat_debug_steps`. These read it:

| Reader | Why it does not need the heartbeat |
|---|---|
| `FinalizeStaleChatDebugRows` and the partial indexes
`idx_chat_debug_runs_stale` and `idx_chat_debug_steps_stale` | No
production caller. The next two PRs delete the query, and #31009 drops
the indexes in a migration. |
| `DeleteOldChatDebugRuns` (dbpurge) | See the next paragraph. |
| `DebugPanel.tsx` run sort | Sorts by `started_at \|\| updated_at`, and
`started_at` is `NOT NULL`, so it never falls back to `updated_at`. |
| Debug run and step API responses | Return `updated_at` as data.
Nothing uses it to decide whether a run is alive. |

dbpurge deletes runs whose `updated_at` is older than the debug
retention window, whatever their status, and their steps cascade. The
window is `agents_chat_debug_retention_days`: 30 days by default, and 0
turns the purge off, so dbpurge never deletes a run that was written in
the last day. A run's `updated_at` still moves when the run is created,
when each step is inserted (the `InsertChatDebugStep` CTE), and on every
run update and finalize. So dbpurge could only delete a live run if one
model call plus the tool calls after it ran for more than a day. The
runner finalizes its debug run when the runner context ends, a
`requires_action` wait times out after 5 minutes (the case `TouchRun`
covered), and chatloop aborts a stream that is silent for
`--chat-stream-silence-timeout`, 10 minutes by default (0 turns that
guard off).

Mike accepted the cost: a run or step orphaned by a crashed replica
stays `in_progress` until dbpurge deletes it. That is already true on
`main`, because nothing runs the sweep.

This does not touch the chat worker's `chat_heartbeats` loop that
ARCHITECTURE.md describes, and no ARCHITECTURE.md sentence about debug
runs becomes false.

**Review focus:** nothing uses `WithClock` after this PR, but deleting
it here would take this PR past 500 changed lines, so it goes with
`FinalizeStale` in the next PR.

Validation: `make gen/db`, `go build ./coderd/...`, and `golangci-lint
run` on the touched packages (0 issues). `go test -count=1` passes for
`./coderd/x/chatd/chatdebug/...`, `./coderd/database/dbauthz/ -run
TestMethodTestSuite`, `./coderd/database/ -run ChatDebug`,
`./coderd/x/chatd/ -run Debug` and `./coderd/database/dbpurge/`. The
pre-commit hook passed.

## Stack

This stack deletes the stale debug-run sweep, then simplifies the
chatdebug debug-run, stream wrapper and step numbering code, drops the
indexes the sweep used, and last deletes a runner debug field that lost
its only reader with the heartbeats. The debug-run and stream wrapper
refactors each sit on a test-only layer that pins the behavior they
keep.

1. This PR: Delete the chat debug run and step heartbeats
2. #30989 Delete `FinalizeStale` and the stale threshold
3. #30995 Delete the `FinalizeStaleChatDebugRows` query
4. #30933 Pin the debug runs that turns, titles and status labels record
5. #30934 Create and finalize debug runs through one helper
6. #30980 Table the stream wrapper tests and cover their status rules
7. #30981 Share one finalize-once lifecycle between the stream wrappers
8. #31007 Number chat debug steps in the database
9. #31008 Delete the process-global step counters
10. #31009 Drop the chat debug stale-sweep indexes
11. #31010 Drop the unused `runnerCtx` from the runner debug turn

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-20 20:32:25 +00:00
Michael Suchacz 5cc2f2c103 feat: add MCP connect and generation-prep observability (#28402)
## Stack context

Follow-up to the MCP connect-stall incident (chats on dev.coder.com
stalled ~15 min/turn while a configured MCP server black-holed
requests). The stack: #28400 makes the 10s MCP connect budget actually
hold; this PR makes connect and preparation slowness observable so the
next incident shows up in logs and the chat debug UI instead of as a
silent timeline gap.

## Why

During the incident, each stalled turn looked like a silent gap before
the first debug step: no per-server connect durations anywhere, no
warning that preparation was slow, and the only signal was a generic
"connection failure" log without timing.

## Changes

- `mcpclient.ConnectAll` now returns per-server `ConnectSummary` values
(config ID, slug, outcome `connected`/`timeout`/`error`/`no_tools`,
duration, tool count, redacted error). Failure logs include the
duration, and successful connects slower than 5s log a `slow MCP server
connect` warning.
- Connect summaries are seeded into the chat debug run summary under an
`mcp_connect` key (seeded keys survive `FinalizeRun`'s aggregation), and
the debug panel's run card renders them as a per-server list with
outcome badges, durations, tool counts, and errors.
- `prepareGeneration` logs a `slow generation preparation` warning when
a turn's preparation exceeds 30s.

## Tests

- Go: connect summary assertions added to the budget tests
(outcome/duration/tool count for black-holed vs healthy servers); `go
test ./coderd/x/chatd/...` green.
- Frontend: new `coerceRunSummary` unit tests for `mcp_connect` coercion
(malformed entries dropped, non-array ignored) and a
`RunWithMCPConnectSummary` story whose play function expands the run and
asserts the rendered outcomes, durations, tool counts, and error text.
`pnpm check`, `lint:types`, unit and storybook projects green.

> 🤖 Mux authored this PR on Mike's behalf.

<!-- mux-attribution: model=anthropic:claude-opus-4-6 thinking=high -->
2026-08-27 10:22:33 +02:00
Hugo Dutka 4debd23cbb fix: chatd refactor (#26270)
Implements the chatd stabilization RFC.

Combines:
- https://github.com/coder/coder/pull/25908
- https://github.com/coder/coder/pull/25923
- https://github.com/coder/coder/pull/26109
- https://github.com/coder/coder/pull/26110
- https://github.com/coder/coder/pull/26111
- https://github.com/coder/coder/pull/26112
2026-06-12 13:33:12 +02:00