Skip to content

perf: purge old fork rows and bound wake-up and report reads - #368

Merged
ibetitsmike merged 13 commits into
mainfrom
mike/issue-307-purge-bounds
Nov 17, 2026
Merged

ibetitsmike merged 13 commits into
mainfrom
mike/issue-307-purge-bounds

Conversation

@ibetitsmike

@ibetitsmike ibetitsmike commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

Coder Agents opened this PR on behalf of @ibetitsmike.

Closes #307. This PR has items 2, 3 and 6. Item 1 merged in #369. Items 4, 7 and 8 merged in #370. Item 5 is covered by #294.

What changed

  • Item 2. fork_dbpurge.go deletes expired plugin_link_codes (expires_at < now()), at most 1000 per tick.
  • Item 3, purge. fork_dbpurge.go deletes, in batches of 100, completed, failed, stopped and interrupted workflow_runs whose updated_at is older than 30 days (steps cascade; running runs stay). The batch is smaller because a run cascades to up to 50 steps of up to 256 KiB. UpdateWorkflowStep also stamps the run's updated_at, so a step report to an interrupted run restarts its retention clock. Both purge deletes repeat their status and age filter in the outer DELETE, so a row that a resume or a step report updates while the batch waits for its lock is rechecked on its new version and stays. UpdateWorkflowStep touches the run in a CTE and updates the step FROM it, so it locks the run row before the step row, the same order as the purge cascade, and the two cannot deadlock.
  • Item 3, report cap. workflow_report rejects an input over 256 KiB with a tool error before any decode, so a step row cannot grow past it. The run_workflow tool description lists the limit.
  • Item 6, wake-ups. ListChatWakeupsByChatID takes a statuses array (empty means all). GET /api/v2/chats/fork/{chat}/wakeups accepts ?status=active,paused (400 on an unknown status), codersdk.ChatWakeups takes optional statuses, and the wake-ups pill asks for active and paused only. ListChatWakeupWatchesByChatID takes the IDs of the wake-ups the handler listed, so it loads only their watches, and a wake-up that changes status between the two reads keeps its watches. createChatWakeup still lists every status, since a replay must find a completed wake-up. dbpurge deletes completed and canceled wake-ups older than 30 days (watches cascade, runs keep counting with a NULL wakeup_id).
  • chatdmig nodes 01a1e7a0-b608..._chat_wakeups_retention_index and 01a1e7a0-b6c0..._workflow_runs_retention_index: partial indexes on updated_at of the deletable chat_wakeups and workflow_runs rows, so a purge batch does not scan the table. Each is a transaction: none node with CREATE INDEX CONCURRENTLY IF NOT EXISTS, so the build does not block writes.
  • coderd/x/chatd/ARCHITECTURE.md: a new fork-owned "Fork-workflows retention" note in the workflow section: the 30 day window, the 100 per tick batch, the step update that restarts the clock, and what resume_run_id and a late workflow_report do once a run is gone (a fresh run under the same ID reuses the old step chats whose spec matches, as a resume would). No upstream line changes.
  • dbauthz and dbmetrics wrappers for the new queries (ResourceSystem delete), and swagger for the new query parameter.

Tests

All Go commands ran under flock ~/.fork-go.lock, Postgres 16 local.

  • go test -count=1 -v ./coderd/database/dbpurge/: 26 PASS, 0 FAIL. New: TestDeleteExpiredPluginLinkCodes, TestDeleteOldWorkflowRuns (old ended runs and steps deleted; a running run, a recent run and an old interrupted run whose step just reported kept), TestDeleteOldChatWakeups (old completed/canceled deleted, old active and recent kept).
  • go test -count=1 -run TestForkChatWakeups ./coderd/: 3 PASS. New TestForkChatWakeupsStatusFilter checks the filtered list, the unfiltered list and the 400.
  • go test -count=1 -run 'TestForkWorkflowReport$' ./coderd/x/chatd/: PASS, new subtest OversizedValueRejected.
  • go test -count=1 -run 'Fork|Loop|Wakeup|WaitForEvents|ProcessEvents|PullRequestEvents|Workflow' ./coderd/x/chatd/: 146 PASS, 0 FAIL.
  • go test -count=1 -run TestMethodTestSuite ./coderd/database/dbauthz/: ok. ./coderd/database/forkdb/..., ./coderd/database/dbmetrics/: ok.
  • go test -count=1 -run TestChatWakeupWatchRows ./coderd/database/forkdb/: PASS (an active filter returns the watches, completed and canceled return none).
  • go test -count=1 -run TestRetentionDeletePlans ./coderd/database/forkdb/: PASS. With 10,000 ended or open rows in each table, EXPLAIN of both purge deletes has no Seq Scan.
  • go test -count=3 -race -run TestRetentionDeleteRechecksLockedRows ./coderd/database/forkdb/: PASS. An uncommitted update resumes an old ended run (and an old canceled wake-up); the test waits until the batch blocks on the row lock in pg_stat_activity, commits, and expects 0 deleted and the row kept.
  • go test -count=3 -race -run TestUpdateWorkflowStepLocksRunFirst ./coderd/database/forkdb/: PASS. The test holds the run row lock, waits until the step update is lock-waiting, checks the step row is still free (FOR UPDATE NOWAIT), then commits and sees the step reported.
  • After merging main at d310975509: go build ./coderd/..., go vet, go test of forkdb, dbpurge, chatdmig, dbauthz TestForkQuerier, chatd -run 'Workflow|Wakeup|Notify|Plugin|Pack' and coderd -run 'Workflow|Wakeup|Plugin': ok. generate.sh: no diff.
  • go test -count=1 -run 'TestForkQuerier|TestMethodTestSuite' ./coderd/database/dbauthz/: ok. CHATDMIG_TEST_DATABASE_URL=... go test ./coderd/database/migrations/chatdmig/...: ok. chatdmig check: exit 0.
  • pnpm test src/pages/AgentsPage/components/ForkComposerSlot.test.tsx: 19 PASS (asserts the pill requests ["active","paused"]).
  • pnpm check: clean. pnpm lint: types, oxlint and circular deps pass; check-compiler fails on ForkHtmlAttachmentViewer.tsx and knip lists 3 unused exports, all in files this PR does not touch (same on main).
  • golangci-lint run --fix=false --new-from-rev=origin/main on changed packages: 0 issues. gofmt -l: clean.

Negative controls

  • Restored fork_dbpurge.go from main: TestDeleteExpiredPluginLinkCodes, TestDeleteOldWorkflowRuns, TestDeleteOldChatWakeups all FAIL. Restored the fix: PASS.
  • Handler passes statuses[:0] (no filter): TestForkChatWakeupsStatusFilter FAIL.
  • Status filter (w.status = 'active') put back in ListChatWakeupWatchesByChatID: TestChatWakeupWatchRows FAIL at line 273 (a wake-up that changed status after the list lost its watches). Restored: PASS.
  • Size check disabled: OversizedValueRejected FAIL ("Value accepted" instead of the 256 KiB error).
  • Index nodes reduced to SELECT 1 (checked on the earlier single node): TestRetentionDeletePlans FAIL on DeleteOldChatWakeups. Only the workflow_runs index removed: FAIL on DeleteOldWorkflowRuns.
  • UpdateWorkflowStep put back to the plain step update: TestDeleteOldWorkflowRuns FAIL, the reported interrupted run is purged. Restored: PASS.
  • Outer filter removed from DeleteOldWorkflowRuns, then from DeleteOldChatWakeups: TestRetentionDeleteRechecksLockedRows FAIL on each case (1 row deleted). Restored: PASS.
  • UpdateWorkflowStep put back to the step update with an unreferenced run CTE: TestUpdateWorkflowStepLocksRunFirst FAIL ("the step update locked the step row before the run row"). Restored: PASS.
  • Pill query without statuses: ForkComposerSlot.test.tsx 1 FAIL, 18 PASS.

Not verified

  • No run against the deployed server or a real chat; the pill was not checked in a browser.
  • Purge timing on a large production table was not measured. Wake-ups are deleted 1000 per tick and workflow runs 100 per tick.

Part of #307.

- dbpurge deletes expired plugin link codes, completed and canceled
  wake-ups older than 30 days, and ended or interrupted workflow runs
  older than 30 days, in batches.
- workflow_report rejects a value over 256 KiB with a tool error.
- GET /api/v2/chats/fork/{chat}/wakeups takes a status filter, and the
  wake-ups pill asks for active and paused only.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T05:01:59.522408Z ab6546c Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: df540a636a

ℹ️ 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".

Partial indexes on the deletable chat_wakeups and workflow_runs rows, by
updated_at, so a purge batch does not scan the table. The expired plugin
link code delete takes the same batch limit as the others.

Part of #307.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@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: ef2fbb93c9

ℹ️ 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/fork_chat_wakeups.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@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: fdd205742b

ℹ️ 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/fork_chat_wakeups.go Resolved
A wake-up that changed status between the two reads came back with no
watches. The watch list now takes the IDs of the wake-ups the handler
listed.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 9dede1d955

ℹ️ 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".

…bounds

# Conflicts:
#	coderd/database/forkdb/queries/workflow_runs.sql
#	coderd/database/forkdb/sqlc.yaml
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@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: 006d1590b3

ℹ️ 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/fork_chat_wakeups.go Resolved
Comment thread coderd/database/dbpurge/fork_dbpurge.go Resolved
A run cascades to up to 50 steps of up to 256 KiB, so purge 100 runs a
tick instead of 1000. Leave a TODO in the chatd architecture document for
the 30 day retention of workflow runs.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@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: d407bd95bc

ℹ️ 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/database/dbpurge/fork_dbpurge.go Resolved
Comment thread coderd/x/chatd/ARCHITECTURE.md Resolved
…rted runs

Build the two retention indexes with CREATE INDEX CONCURRENTLY in their own
transaction: none nodes, so a rolling upgrade does not block writes to
chat_wakeups and workflow_runs. A step write now stamps its run's
updated_at, so a report to an interrupted run restarts the run's 30 day
retention clock.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

Replace the retention TODO with the final text in the fork-workflows notes.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: c518bc9d8c

ℹ️ 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".

…bounds

# Conflicts:
#	coderd/database/dbpurge/fork_dbpurge.go
#	coderd/database/dbpurge/fork_dbpurge_test.go
#	coderd/database/forkdb/export_test.go
#	coderd/database/forkdb/sqlc.yaml
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged main at 76b39d63c8 (#369) into this branch by merge commit. New head 721334d6cf. Conflicts resolved:

  • sqlc.yaml: 01a1e3cc_chat_user_notifications before the two retention index nodes, as chatdmig check orders them.
  • fork_dbpurge.go: the notify_user purge from perf(coderd/x/chatd): count notify_user sends in a fork table #369 joins the purge loop with its own batch size (1000). Error and log text are unchanged.
  • fork_dbpurge_test.go and forkdb/export_test.go: both sides kept.

forkdb/generate.sh rerun. Build and vet pass. Tests for forkdb, dbpurge (incl. TestDeleteOldChatUserNotifications, TestDeleteOldWorkflowRuns, TestDeleteOldChatWakeups, TestDeleteExpiredPluginLinkCodes), chatdmig, dbauthz TestForkQuerier, and chatd and coderd -run "Workflow|Wakeup|Notify" pass. golangci-lint 0 issues, gofmt clean. The body now says Closes #307, since this PR merges after #370.

@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: 721334d6cf

ℹ️ 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".

A purge batch picks old ended rows from its snapshot. When a resume or a
step report updated a row while the DELETE waited for its lock, the join on
the ID still matched the new row, so the DELETE removed a live run or
wake-up. The DELETE now repeats the status and age filter, which Postgres
rechecks on the updated row.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Pushed f659d595fc for the P2 finding on 721334d6cf. Both purge deletes now repeat their filter in the outer DELETE, so a row resumed while the batch waits for its lock stays. New test TestRetentionDeleteRechecksLockedRows fails on the old SQL for both tables and passes with -race -count=3. forkdb, dbpurge, dbauthz TestForkQuerier, chatd -run "Workflow|Wakeup" pass; golangci-lint 0 issues, gofmt clean.

@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: f659d595fc

ℹ️ 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
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Pushed 3d38cca53e, docs only. Both P2 findings on f659d595fc are declined with reasons in their threads. The retention note in coderd/x/chatd/ARCHITECTURE.md now says that a run recreated after the purge reuses its old step chats. The change stays inside the fork-owned bullet; no upstream line changed.

@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: 3d38cca53e

ℹ️ 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".

…rkflowStep

An unreferenced data-modifying CTE runs after the main query, so the step
update locked the step row before the run row, the reverse of the purge's
cascade. A step report racing the purge could deadlock. The step update
now joins the run update's RETURNING, so the run row is locked first.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged main at d310975509 (#370) into the branch, no conflicts. New head ab6546cfbd.

Also fixed the lock-order finding in 74555ac5a3: UpdateWorkflowStep now updates the step FROM the run CTE, so it locks the run before the step, in the purge cascade order. TestUpdateWorkflowStepLocksRunFirst covers it and fails on the old SQL.

Build, vet, forkdb, dbpurge, chatdmig, dbauthz, chatd and coderd workflow tests, and lint pass on the merged head.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: ab6546cfbd

ℹ️ 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
ibetitsmike merged commit 497bbb6 into main Nov 17, 2026
11 checks passed
@ibetitsmike
ibetitsmike deleted the mike/issue-307-purge-bounds branch November 17, 2026 05:45
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged at head ab6546cfbd330400352a158f4845d8abc5e1faa4 as 497bbb6, on main d310975509529c664aac1b1cc3e33e8b4686c1e5, with the server running that main.

Gates on this exact head:

  1. The head matched the SHA I verified (--match-head-commit).
  2. Every check run passed. fork-ci run 44020746822 passed on this head.
  3. Codex on this head: perf: purge old fork rows and bound wake-up and report reads #368 (comment). The summary state shows code review completed on ab6546cfbd with no findings.
  4. No unresolved review thread.
  5. 0 commits behind main.
  6. I ran the tests below on this exact head.

Tests I ran on ab6546cfbd (detached worktree, under flock ~/.fork-go.lock, Postgres 16 at 127.0.0.1:5432):

  • go test -count=1 -v ./coderd/database/forkdb/... ./coderd/database/dbpurge/ ./coderd/database/dbmetrics/: 151 PASS, 0 FAIL.
  • go test -count=1 -v -run TestForkQuerier ./coderd/database/dbauthz/: 909 PASS, 0 FAIL.
  • go test -count=1 -v ./coderd/database/migrations/chatdmig/... with CHATDMIG_TEST_DATABASE_URL: 79 PASS, 0 FAIL. chatdmig check: exit 0. Both new nodes are listed as "(no transaction)".
  • go test -count=1 -v -run 'Wakeup|Workflow' ./coderd/: 41 PASS, 0 FAIL.
  • go test -count=1 -race -v -run 'Workflow|Wakeup|Loop|WaitForEvents|Schedule' ./coderd/x/chatd/: 346 PASS, 0 FAIL.
  • Negative control: with the 256 KiB cap in workflow_report raised 1000 times, TestForkWorkflowReport/OversizedValueRejected fails. The source was restored after the control. The PR body lists the workstream's other controls, including the run updated_at stamp on a step report.

Review notes:

  • Retention for wake-ups and workflow runs is bounded: dbpurge deletes in batches that read new partial indexes.
  • The two index nodes are transaction: none with CREATE INDEX CONCURRENTLY IF NOT EXISTS, so writes continue during the build. No existing node changed.
  • A step report now stamps its run's updated_at, so a report on day 29 restarts the 30-day window.
  • workflow_report caps one value at 256 KiB.
  • The wake-ups list takes an optional status filter.
  • The ARCHITECTURE.md retention paragraph is final prose. The one TODO left there (workflow phases) was already on main.
  • No experiment: these are coderd-only bounds on reads and deletes of rows that are already past retention.

Not exercised: a concurrent index build on a large table, and a step report racing the purge of its 30-day-old run. Postgres would abort one side of a deadlock, and both sides retry. A failed concurrent build would leave an invalid index that IF NOT EXISTS then skips. That would need a manual REINDEX, and I did not test it.

Closes #307 with this merge.

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.

perf: small query and retention fixes from the fork performance audit

1 participant