Skip to content

perf(chatd): count wake-up runs in hourly buckets - #357

Merged
ibetitsmike merged 4 commits into
mainfrom
mike/issue-297-wakeup-cap-counters
Nov 16, 2026
Merged

ibetitsmike merged 4 commits into
mainfrom
mike/issue-297-wakeup-cap-counters

Conversation

@ibetitsmike

@ibetitsmike ibetitsmike commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

Coder Agents opened this PR on behalf of @ibetitsmike.

Part 1 of 2 for #297 (perf plan #311). Part 2, #358, stacked on this branch, adds the organization spend cache and the purge of old counter rows.

What changed

  • New chatdmig node 01a1e197-..._chat_wakeup_run_counts creates chatd.chat_wakeup_run_counts: one row per chat and UTC hour (hour timestamptz, truncated to the hour) with organization_id and runs. Primary key (chat_id, hour), index chat_wakeup_run_counts_org_hour_idx on (organization_id, hour) INCLUDE (runs).
  • The node adds the trigger trigger_count_delivered_chat_wakeup_run, AFTER INSERT ON chat_wakeup_runs FOR EACH ROW WHEN (NEW.status = 'delivered'). It upserts the hour bucket of the run's created_at in the transaction that inserts the run, which is the transaction of the chat message. A delivery that rolls back counts nothing. A replica still on the old code during a rolling upgrade also inserts delivered runs, so its deliveries count too. No Go code writes the counter.
  • The node creates the trigger first and then backfills the buckets from the delivered runs of the last 25 hours, so the caps keep their state across the deploy. CREATE TRIGGER holds a lock that blocks inserts into chat_wakeup_runs until the node commits, so each run is counted once, by the trigger or by the backfill.
  • wakeupCapReached replaces the two COUNT(*) scans of chat_wakeup_runs with one statement, SumChatWakeupRunCountsSince, that sums the chat's buckets on the primary key and the organization's buckets on the new index. The window is still a rolling 24 hours. It starts at since.UTC().Truncate(time.Hour), so it can count up to one hour more than 24 hours and never less.
  • The order of checks is unchanged: caps row, chat runs, org runs, chat spend, org spend, returning on the first cap reached. A delivery under the caps now issues 4 cap statements instead of 5. Part 2 brings it to 3 with the spend cached.
  • dbauthz and dbmetrics wrappers for the new query. CountChatWakeupRunsSince and CountOrganizationChatWakeupRunsSince are removed.
  • coderd/x/chatd/ARCHITECTURE.md describes the counter table and the cap check.

Why chat_wakeup_runs stays

It is still used on main. admitWakeupDelivery inserts the delivered run with ON CONFLICT (wakeup_id, run_key) DO NOTHING, which is the occurrence guard that returns errWakeupOccurrenceRan, and finishWakeupSend records failed and skipped runs there. So this PR does not drop it. The guard looks redundant with lockDueWakeup, so the table could go in a follow-up.

Rollback

The new node adds a table, a function and a trigger and has no down step, like every chatdmig node. A rollback past this PR needs the database snapshot taken before the deploy. Old code that runs against the new schema keeps working; the trigger only fills a table it does not read.

EXPLAIN

Scratch database with 100,800 counter rows (20 organizations, 600 chats, 168 hours each), after VACUUM (ANALYZE, FREEZE). The prepared SumChatWakeupRunCountsSince statement:

 Result (actual time=0.347..0.348 rows=1 loops=1)
   Buffers: shared hit=40
   InitPlan 1 (returns $0)
     ->  Aggregate (actual time=0.156..0.156 rows=1 loops=1)
           Buffers: shared hit=28
           ->  Bitmap Heap Scan on chat_wakeup_run_counts (actual time=0.037..0.150 rows=25 loops=1)
                 Recheck Cond: ((chat_id = '00000000-0000-0000-0001-000000000001'::uuid) AND (hour >= '2026-11-14 23:00:00+00'::timestamp with time zone))
                 Heap Blocks: exact=25
                 Buffers: shared hit=28
                 ->  Bitmap Index Scan on chat_wakeup_run_counts_pkey (actual time=0.028..0.028 rows=25 loops=1)
                       Index Cond: ((chat_id = '00000000-0000-0000-0001-000000000001'::uuid) AND (hour >= '2026-11-14 23:00:00+00'::timestamp with time zone))
                       Buffers: shared hit=3
   InitPlan 2 (returns $1)
     ->  Aggregate (actual time=0.188..0.189 rows=1 loops=1)
           Buffers: shared hit=12
           ->  Index Only Scan using chat_wakeup_run_counts_org_hour_idx on chat_wakeup_run_counts chat_wakeup_run_counts_1 (actual time=0.036..0.138 rows=750 loops=1)
                 Index Cond: ((organization_id = '00000000-0000-0000-0000-000000000002'::uuid) AND (hour >= '2026-11-14 23:00:00+00'::timestamp with time zone))
                 Heap Fetches: 0
                 Buffers: shared hit=12
 Planning Time: 0.605 ms
 Execution Time: 0.376 ms

The org sum is an index-only scan on the new index with no heap fetches. A plain VACUUM left relallvisible at 0 on the fresh table; autovacuum sets it on a live table.

Tests

All run locally against Postgres 16:

  • go test ./coderd/x/chatd/... passed.
  • go test ./coderd/database/forkdb/ ./coderd/database/dbauthz/ ./coderd/database/dbpurge/ passed.
  • CHATDMIG_TEST_DATABASE_URL=... go test ./coderd/database/migrations/chatdmig/... passed, including TestUpgradeMatchesFresh, TestForkNodesOnlyAddToChatd and the new TestWakeupRunCountsBackfill.
  • New TestWakeupRunCounts:
    • EachDeliveryCounts: three deliveries for one chat sum to 3.
    • BusyChatDoesNotCount: a chat that turns busy during the send gets no message and no count.
    • RolledBackAdmissionDoesNotCount: admitWakeupDelivery in a transaction that rolls back leaves no count; the same call committed leaves 1.
    • OrganizationRunCapStopsThirdChat: with the org run cap at 2, three chats deliver in turn and the third pauses with org_daily_run_cap.
  • TestChatWakeupRuns (forkdb) inserts delivered and failed runs in different hours and checks the trigger's buckets and the chat and org sums.
  • TestWakeupRunCountsBackfill (chatdmig) checks the backfill and then that the trigger counts a delivered run after the node and skips a failed one.
  • golangci-lint run --fix=false on the touched packages reports nothing in the changed files. gofmt -l is clean.

Negative control: with the CREATE TRIGGER removed from the node, EachDeliveryCounts, RolledBackAdmissionDoesNotCount, OrganizationRunCapStopsThirdChat, TestWakeupRunCountsBackfill and TestChatWakeupRuns fail. BusyChatDoesNotCount still passes, as expected (see below).

Not verified

  • The busy chat path returns errWakeupChatBusy in forkAdmit before admitWakeupDelivery runs, so BusyChatDoesNotCount proves nothing is counted but does not roll back a counted run. RolledBackAdmissionDoesNotCount covers the rollback directly.
  • Until part 2 lands, counter rows are not purged. That is at most one row per chat and hour.
  • No live deploy test. The backfill ran only in the chatdmig test. A rolling upgrade with an old replica was not run; the trigger test covers an insert that does not go through the new Go code.

Refs #297. #358 closes it.

The daily run caps counted chat_wakeup_runs rows over 24 hours on every
delivery, one scan of a chat and one of a whole organization. A delivery
now upserts a per-chat hourly bucket in chat_wakeup_run_counts in the
send's transaction, and one statement sums at most 25 buckets for the
chat and the organization. A chatdmig node creates the table and
backfills it from the delivered runs of the last 25 hours.

Refs #297
@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-16T01:22:03.669839Z 002eb1e 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.

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

ℹ️ 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 replica that does not know chat_wakeup_run_counts still inserts
delivered runs during a rolling upgrade. A trigger on chat_wakeup_runs
counts each delivered run in the inserting transaction, so those runs
count against the daily caps too. The Go upsert is removed.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

$> Coder Agents acted on behalf of @ibetitsmike.\n\n@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 02cdf37ab5

ℹ️ 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.\n\n@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e06241ff07

ℹ️ 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.\n\n@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 002eb1ed67

ℹ️ 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 2523de1 into main Nov 16, 2026
9 checks passed
@ibetitsmike
ibetitsmike deleted the mike/issue-297-wakeup-cap-counters branch November 16, 2026 02:08
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged at head 002eb1ed673bc4f07998c9e3ffedb7e7a8779593 as 2523de1, on main d4ad70ac152944eeb28930871633186d935cddce, 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 43785582007 passed on this head.
  3. Codex receipt for this head: perf(chatd): count wake-up runs in hourly buckets #357 (comment) ("Didn't find any major issues").
  4. No unresolved review thread.
  5. 0 commits behind main.
  6. The PR commits db5b612a27 and 02cdf37ab5 are unchanged since I tested them (git range-diff shows both identical). The diff of each of the 16 files between the tested head and this head equals main's own delta in that range, so the head only adds main merges.

Tests I ran on the PR commits at 02cdf37ab5 (detached worktree, Postgres 16 at 127.0.0.1:5432, CHATDMIG_TEST_DATABASE_URL set so the chatdmig tests do not skip):

  • go test -count=1 -v -run 'TestWakeupCaps|TestWakeupRunCounts|Wakeup' ./coderd/x/chatd/: 134 PASS, 0 FAIL, 0 SKIP.
  • go test -count=1 -v -run 'Wakeup|TestSumChatCostMicrosSince|TestCountChatUserNotificationsSince' ./coderd/database/forkdb/: 10 PASS, 0 FAIL.
  • go test -count=1 -v -run Fork ./coderd/database/dbauthz/: 824 PASS, 0 FAIL.
  • go test -count=1 -v ./coderd/database/migrations/chatdmig/: 63 PASS, 0 FAIL, 0 SKIP (includes TestWakeupRunCountsBackfill).
  • Negative control: with the CREATE TRIGGER removed from the new node, TestWakeupRunCountsBackfill fails (the run inserted after the node counts 1 instead of 2 in its hour), and TestWakeupRunCounts/EachDeliveryCounts, RolledBackAdmissionDoesNotCount and OrganizationRunCapStopsThirdChat fail. So the tests depend on the trigger.

Rollback: the new chatdmig node adds a table, a function and a trigger and has no down step. A rollback past this PR needs the database snapshot taken before the deploy. Old code keeps working on the new schema; the trigger only fills a table old code does not read.

Not exercised: a live deploy, the backfill on the real database, a rolling upgrade with an old replica, and how long the trigger creation holds its lock on chat_wakeup_runs with real data. Counter rows are not purged until #358 lands (at most one row per chat and hour). #297 stays open for #358.

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.

1 participant