8 Commits
Author SHA1 Message Date
Michael Suchacz eea839ccc4 refactor(coderd): number chat debug steps in the database (#31007)
`InsertChatDebugStep` now numbers a step after the run's highest step
when the caller passes zero, so chatdebug stops numbering steps in
process memory. `CreateStepParams` loses `StepNumber`, `beginStep` no
longer calls `nextStepNumber` or `syncStepCounter`, and `CreateStep`
replaces its collision retry, which listed the run's steps and bumped
the number, with a per-run lock. #31008 deletes the counters, which no
production code reads after this PR.

**Why it is safe:** Postgres takes the insert's snapshot before the
statement waits on the run row, so creates that waited on the same run
read the same highest step. `CreateStep` therefore takes
`pg_advisory_xact_lock(LockIDChatDebugRunSteps(run))` in its own
statement and inserts in the same transaction, so each insert starts
after the previous holder committed. The new
`TestService_CreateStep_NumbersConcurrentSteps` holds the run row,
starts 20 creates, waits until all of them wait on a lock, then commits
and checks the numbers 1 to 20. It passes 10 of 10 runs, and fails 10 of
10 with a 10-attempt collision retry in place of the lock.
`TestService_CreateStep_RetriesDuplicateStepNumbers` becomes
`TestService_CreateStep_NumbersStepsPerRun`, and
`TestService_CreateStep_ListRetryErrorWins` goes with the list call it
covered. Mutants that fail the chatdebug tests: no lock, the lock
outside the transaction, the lock keyed by chat, a constant number,
storing the zero, numbering across runs, a nonzero number from
`CreateStep`, and an unclassified missing run. One mutant survives and
is equivalent: running the insert on `s.db` instead of `tx` inside the
same `InTx` callback, because the insert still commits before the
transaction releases the lock. Running the insert after the transaction
commits fails the new test with a duplicate key. A copy of `service.go`
with garbage in it fails to build.

**Review focus:** `@step_number` stays as an override. Production passes
zero, and the fixtures in `querier_test.go`, `dbauthz_test.go`,
`dbpurge_test.go` and `exp_chats_test.go` keep their explicit numbers.
No test depends on the override (a mutant that ignores it survives),
because every fixture numbers its steps in insert order. Dropping the
parameter would touch about 20 fixtures outside chatdebug.

The PR removes more than it adds: +179/-233 hand-written lines. The
generated `querier.go` and `queries.sql.go` change 15 more.

Validation:
- `make gen/db` changes only `querier.go` and `queries.sql.go`.
- `go test -race -count=1 -p 4 -parallel 4
./coderd/x/chatd/chatdebug/...` passes, and `go test -count=10 -run
TestService_CreateStep ./coderd/x/chatd/chatdebug/` passes all 6 tests
10 of 10 times.
- `go test -count=1 -run ChatDebug ./coderd/database/
./coderd/database/dbpurge/` and `go test -count=1 -run Debug
./coderd/x/chatd/` (19 tests) pass, and the 25 chatd debug-run tests
pass under `-race`.
- `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...
./coderd/database/` 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. This PR: 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-21 08:23:28 +00:00
Michael Suchacz 8b6f209e8f refactor: delete the FinalizeStaleChatDebugRows query (#30995)
Deletes the `FinalizeStaleChatDebugRows` query. #30989 deleted
`chatdebug.Service.FinalizeStale`, its only caller. This is the last of
three PRs that delete the stale debug-run sweep.

- Deletes the query from `chatdebug.sql` and regenerates the querier,
dbmock and dbmetrics code. `make gen/db` leaves the dbmetrics wrapper of
a deleted query behind, so I removed it by hand.
- Deletes the dbauthz wrapper and its `TestMethodTestSuite` case, and
`TestFinalizeStaleChatDebugRows` from `querier_test.go`.
- The `codersdk.ChatDebugStatus` comment no longer names the query.

**Why it is safe:** nothing calls the query after #30989. #30988
explains why no reader of the debug `updated_at` columns needs the sweep
and why dbpurge cannot delete a live run.

**Review focus:** the partial indexes `idx_chat_debug_runs_stale` and
`idx_chat_debug_steps_stale` from migration 000468 served only this
query. They stay in this PR; #31009, at the top of this stack, drops
them in a migration.

Validation: `make gen/db` and `go build ./...`. `go test -count=1`
passes for `./coderd/database/dbauthz/ -run TestMethodTestSuite`,
`./coderd/database/ -run ChatDebug`, `./codersdk/` 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. #30988 Delete the chat debug run and step heartbeats
2. #30989 Delete `FinalizeStale` and the stale threshold
3. This PR: 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 21:10:40 +00:00
Michael Suchacz 367358862b refactor: delete chatdebug FinalizeStale and the stale threshold (#30989)
Deletes `chatdebug.Service.FinalizeStale` and everything that existed
only for it. Nothing in production calls `FinalizeStale` since #26270,
and #30988 removed the heartbeats that kept live runs out of its reach.
This is the second of three PRs that delete the stale debug-run sweep.

- `chatdebug/service.go`: deletes `FinalizeStale`, `SetStaleAfter`,
`DefaultStaleThreshold`, the `staleAfterNanos` field and `WithClock`.
The service keeps its real clock for the timestamps it writes.
- `chatd.go`: the debug service factory no longer calls
`SetStaleAfter(inFlightChatStaleAfter * 3)`. `inFlightChatStaleAfter`
stays, because the chat worker uses it.
- `chatdebug/types.go`: deletes `EventKindFinalize` and
`BroadcastPubsubChannel`. `FinalizeStale` was the only publisher without
a chat ID, so `PubsubChannel` loses its `uuid.Nil` branch. Nothing in
production subscribes to `chat_debug:*` channels.
- Deletes the four `FinalizeStale` service tests, and
`TestFinalizeStaleChatDebugRows_TerminalStatusAlignment` together with
`codersdk.ChatDebugTerminalStatuses`, which only that test used. The
test compared that list with the `NOT IN` lists in
`FinalizeStaleChatDebugRows` and nothing else: no other debug query or
constraint lists the statuses. The next PR deletes that query.
- Comments that named the stale sweep now say what happens instead:
`debugCleanupClockSkew`, `errRunFinalized`, `CreateStep`, `UpdateStep`,
the `InsertChatDebugStep` and `UpdateChatDebugStep` queries, the edit
cleanup in `chat_mutations.go`, the two notes on removed tests in
`chatd_internal_test.go`, and four comments in `chatd_test.go`.

**Why it is safe:** `FinalizeStale` and `SetStaleAfter` had no
production caller other than the factory line this PR removes, and
nothing calls `WithClock` after #30988. `make gen/db` changes only the
regenerated query comments. #30988 explains why no reader of
`updated_at` needs the sweep and why dbpurge cannot delete a live run.

**Review focus:** the `debugCleanupClockSkew` comment in
`chatd_debug.go`. The value stays `30 * time.Second`. Runs that start
inside that buffer survive the fast cleanup; the old comment said the
stale sweep would then finalize them, but dbpurge deletes them once they
age past the debug retention window.

Validation: `make gen/db`, `go build ./...`, and `go vet` on the touched
packages. `go test -count=1` passes for
`./coderd/x/chatd/chatdebug/...`, `./coderd/x/chatd/ -run
'Debug|EditMessage|ArchiveChat'`, `./coderd/database/ -run
'ChatDebug|TestIsAuthorizedQuery|TestInsertChatMessagesOrderContract|ConnectionLogs'`
and `./codersdk/`. 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. This PR: 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:54:18 +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 2874d4b4cd feat: add chat debug retention purge (#24943)
> Mux is acting on Mike's behalf.

Adds configurable retention for chat debug data, including the purge
query, updated_at index, site config, experimental API, SDK types,
frontend lifecycle setting, and docs.

The purge deletes debug runs older than the configured retention window
and relies on existing cascades to delete steps. The default retention
is 30 days, and setting the value to 0 disables the purge.
2026-05-05 22:37:13 +02:00
Thomas Kosiewski df7e838c21 feat(coderd): wire debug logging into chat lifecycle (#23917) 2026-04-20 12:27:16 +02:00
Thomas Kosiewski 91f9de27a1 feat(coderd): add chat debug service and summary aggregation (#23916) 2026-04-17 16:27:53 +02:00
Thomas Kosiewski 6ab30123bf feat: add chat debug log tables, queries, and SDK types (#23913) 2026-04-13 15:06:06 +02:00