Skip to content

feat(coderd/x/chatd): cap chat wake-ups per day and add notify_user - #115

Merged
ibetitsmike merged 56 commits into
mainfrom
mike/chat-wakeups-5-caps
Nov 10, 2026
Merged

ibetitsmike merged 56 commits into
mainfrom
mike/chat-wakeups-5-caps

Conversation

@ibetitsmike

@ibetitsmike ibetitsmike commented Nov 10, 2026 •

Copy link
Copy Markdown
Owner

Xum opened this PR on behalf of @ibetitsmike.

Part of #11. Stacked on #106 (base mike/chat-wakeups-4-events). It retargets when #106 merges.

Puts daily budget caps on chat wake-ups and adds a notify_user tool, behind fork-chat-wakeups. When a cap stops a wake-up, the chat owner gets a Coder notification instead of a silent stop.

Caps

The worker checks four caps right before each send, over the rolling 24 hours before it. The limits are named constants in fork_wakeup_caps.go:

Cap Limit Pause reason
Wake-up runs of the chat 288 (a 5-minute loop around the clock) daily_run_cap
Wake-up runs of the organization 2880 org_daily_run_cap
Spend of the chat $20 daily_spend_cap
Spend of the organization's wake-up chats $200 org_daily_spend_cap
  • The check runs after the archived, expired and busy checks, so a busy chat at a cap stays due and is not paused. For events wake-ups it runs only when a child is about to be sent, so a wake-up with nothing pending is never paused.
  • At a cap the claim ends paused with the reason above. It records no run and sends no message.
  • Spend sums total_cost_micros of chat messages, including deleted ones. That column is NULL for models without prices and counts as zero, so the spend caps only bind when the model has prices.
  • The organization spend counts only chats that have at least one wake-up row, so human-only chats never pause a loop.
  • The check does not hold the chat lock, so replicas working at the same time can overshoot the organization caps by a few runs.

New forkdb queries SumChatCostMicrosSince, SumOrganizationWakeupChatCostMicrosSince and CountChatUserNotificationsSince get dbauthz and dbmetrics wrappers and TestForkQuerier entries.

Pause notifications

Every pause the worker commits notifies the chat owner through TemplateCustomNotification ("Chat wake-up paused", with a sentence per reason). This covers the four caps and the existing hook_denied, invalid_cron and invalid_events pauses. The PR2 TODO for hook_denied is gone. The data is {chat_id, reason} without a dedupe bypass, so the enqueuer's daily dedupe of identical payloads sends one notification per chat and reason a day, however many wake-ups pause. A claim that another replica took over does not notify. A failed enqueue only logs.

Resuming a paused wake-up comes with the wake-up API in PR6.

notify_user tool

appendForkTools adds notify_user next to schedule_wakeup and wait_for_events. It takes a message and an optional title (the chat title by default), validates them like POST /api/v2/notifications/custom (a default title longer than 120 bytes is cut on a rune boundary), refuses chats owned by a system user, and enqueues a custom notification to the chat owner with chat_id in its data.

The limit is 10 per chat per rolling hour. It counts stored notifications (COUNT(DISTINCT payload), since one enqueue stores one row per delivery method), so it holds across replicas and restarts. The tool implements SerialToolCalls, so parallel calls in one step each see the calls before them.

Known

  • Pause notifications carry the same template and chat_id, so they count toward a chat's notify_user limit. A chat can have at most seven pause reasons a day, so the effect is small.
  • The pause notice names the chat title, and the payload also carries the owner's name, so a pause after a rename or a name change on the same day sends another notice.
  • The notify_user count scans notification_messages, which has no index on user or chat. Fork migrations may not index core tables, and dbpurge deletes notifications after 7 days, which bounds the scan.
  • Two notify_user calls with the same title and message in the same minute hit the enqueuer dedupe. The second call still returns sent: true but stores nothing.

Validation

  • Colima on dc437d4, and the chatd tests again on ca0eb14: go build ./..., go vet ./coderd/x/chatd/ ./coderd/database/..., forkdb generate.sh with no drift, go test -run 'Wakeup|WaitForEvents|ScheduleWakeup|Loop|NotifyUser|TestAppendForkTools' ./coderd/x/chatd/, TestForkQuerier, and the forkdb and dbmetrics packages.
  • Negative controls: every new test fails when the behavior it names is broken (cap check removed or moved before the busy check, >= changed to >, the 24-hour window removed, the org sum counting human-only chats, COALESCE dropped, each pause notification removed, the rate limit removed, dbauthz actions changed, the default title not cut, SerialToolCalls off).
  • UAT on 9e5c739 (later commits change only tests or merge feat(coderd/x/chatd): wake a chat when its child agents finish #106), against a containerized server with a local model: the run cap paused a /loop after exactly one more run with one notification, a second wake-up on the capped chat paused without a second notification, the spend cap paused, NULL-cost chats kept running, the org run and spend caps paused, invalid_cron notified, notify_user sent with the default and a custom title and refused the 11th call in an hour, and with the experiment off none of the wake-up tools are offered.

Not tested end to end: the hook_denied notification and events wake-ups at a cap (unit tests only), the limit reset after an hour, the system-owner refusal, and email, webhook or push delivery.

Adds the fork-chat-wakeups experiment and the storage for chat wake-ups: a
chatdmig node with chatd.chat_wakeups and chatd.chat_wakeup_runs, forkdb
queries to create, list, pause, cancel and claim due wake-ups with a lease
(FOR UPDATE SKIP LOCKED), run records unique per occurrence and daily run
counts, with their dbauthz and dbmetrics wrappers.

Refs #11.
…ke-up

InsertChatWakeupRun now selects chat_id and organization_id from the
wake-up and authorizes on the wake-up's chat, so a caller cannot record
a run of one chat's wake-up against another chat. Adds the chatd
architecture TODO for the new state.
chat_wakeups gets organization_id, copied from the chat by
InsertChatWakeup, so organization-scoped lists and caps need no join.
A wake-up run now takes its organization from the wake-up.
…chema

# Conflicts:
#	coderd/database/dbauthz/fork_forkdb.go
#	coderd/database/dbmetrics/fork_forkdb.go
#	coderd/database/forkdb/forkdbmock/forkdbmock.go
#	coderd/database/forkdb/querier.go
#	coderd/database/forkdb/sqlc.yaml
… hook denial

Start the worker to prove the hook line runs the wake-up loop on start and
on each poll tick, cover all three busy statuses, an expired wake-up, a
hook denial that pauses the schedule, and assert that concurrent workers
never queue a duplicate prompt behind the turn the first delivery starts.
Insert the delivered run and end the claim inside SendMessage's
transaction, so a chat that turned busy, an occurrence that already ran,
or a canceled or taken-over claim rolls the message back. Hook dispatch
failures no longer pause the wake-up, and each claimed row uses the time
it is processed.
… mike/chat-wakeups-3-loop

# Conflicts:
#	coderd/x/chatd/chat_mutations.go
…occurrences

Busy chats are no longer claimed, so their rows cannot fill the claim batch.
A full queue keeps the occurrence due like any other busy race, and a failed
send records its run only after the worker proves it still holds the lease.
…wake-up

The wake-up ID derives from the tool call, so a call replayed after a worker
restart finds the wake-up it created instead of adding a second one.
A paused chat, or an errored chat with a non-empty queue, would queue the
wake-up prompt, so its due rows filled the claim batch on every poll.
Delivery times now also count the time the claim query took.
…mpossible cron

- schedule_wakeup takes the ID of the tool-call occurrence, since providers
  can reuse a call ID in a later step.
- A replayed call returns its wake-up before the first run is recomputed.
- A cron schedule that never occurs is refused.
- user_prompt_submit hooks see the /loop command as submitted.
- A /loop wake-up is attributed to the user who sent it.
…s to the loop

A /loop command as the first message of a new root chat now creates its
wake-up in the transaction that inserts the chat, through a ForkAfterInsert
hook on chatstate.CreateChatInput. A subagent first message is never parsed,
since its parent model wrote it. When a user_prompt_submit hook replaces the
prompt, the loop runs the replacement.
…orker

# Conflicts:
#	coderd/database/forkdb/chat_wakeups.sql.go
#	coderd/database/forkdb/querier.go
#	coderd/database/forkdb/queries/chat_wakeups.sql
…NoKeyUpdate

The busy-chat filter in ClaimDueChatWakeups skipped an archived errored
chat with a queued message forever, so the worker never canceled its
wake-up. Archived chats are now always claimed.

Also restores the LockChatForNoKeyUpdate querier method that the merge
with main dropped.
…flake the per-child tick

Add TestWakeupEventsUnknownAndInvalidEvents: an event type the worker does not know sends nothing and does not hold the wake-up open, and events that are not a JSON array pause it with reason invalid_events.

TestWakeupEventsDeliversOncePerChild advanced its clock by exactly the poll interval, but the worker adds the time it spent since the claim to the next poll, so under load a tick came microseconds before the wake-up was due and skipped a delivery. Tick one second past the interval.
…nd schedule from admission

A wake-up that resumes a finished child now carries the message_agent
resume marker, so the family live subagent limit applies. The next run is
computed from the admission time, so a hook that delays admission past
the next slot does not leave an already-due schedule. A failed run is
recorded in the transaction that ends the claim.
Base automatically changed from mike/chat-wakeups-4-events to main November 10, 2026 15:20
# Conflicts:
#	coderd/database/forkdb/chat_wakeups.sql.go
#	coderd/x/chatd/fork_tools.go
#	coderd/x/chatd/fork_wait_for_events.go
#	coderd/x/chatd/fork_wait_for_events_internal_test.go
#	coderd/x/chatd/fork_wakeups.go
@ibetitsmike

Copy link
Copy Markdown
Owner Author

@codex review

Xum posted this on behalf of @ibetitsmike.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: fb6f5b528c

ℹ️ 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 marked this pull request as ready for review November 10, 2026 16:00

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

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

@codex review

Xum posted this on behalf of @ibetitsmike.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 952c0e4b7a

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

# Conflicts:
#	coderd/database/dbauthz/fork_forkdb.go
#	coderd/database/dbmetrics/fork_forkdb.go
#	coderd/database/forkdb/forkdbmock/forkdbmock.go
#	coderd/database/forkdb/querier.go
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Xum (AI agent) closed and reopened this on behalf of @ibetitsmike.

Closing and reopening only to make GitHub recompute the merge ref against current main (af6e27501e) and run fork-ci on it. The head is unchanged.

@ibetitsmike ibetitsmike reopened this Nov 10, 2026
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Xum (AI agent) closed and reopened this again on behalf of @ibetitsmike.

The merge ref now points at current main (af6e27501e), but the run started by the first reopen was queued against the old merge ref. This second reopen starts fork-ci on the recomputed merge. The head is unchanged.

@ibetitsmike ibetitsmike reopened this Nov 10, 2026
@ibetitsmike
ibetitsmike merged commit 271acf9 into main Nov 10, 2026
20 of 27 checks passed
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Xum (AI agent) merged this on behalf of @ibetitsmike.

Merge evidence for head 531fafaecd29d321c98487dac607b5de19241ce9:

  • fork-ci pull_request run 42873771661 passed; its build job checked out Merge 531fafaecd into af6e27501e (current main). Run 42863630070 had also passed on this head against 5f6b636911. All checks green.
  • Codex: no major issues on 952c0e4b7a (comment 6772726811). This head only merges main and regenerates the forkdb wrappers; its changed lines are identical to 952c0e4b7a's. 0 of 5 review threads unresolved. The ready-for-review round's P2 (the notify_user hourly limit counted a payload once across UTC midnight) was fixed with a DB test that fails without it.
  • UAT on 9e5c739 against a containerized server with a local model passed: the run and spend caps paused (per chat and per organization) with one notification, NULL-cost chats kept running, invalid_cron notified, notify_user refused the 11th call in an hour, and with the experiment off no wake-up tools are offered. Later commits are review fixes with tests and main merges.
  • No migration; new forkdb queries in chat_wakeups.sql. fork-chat-wakeups stays off on the daily server.

@ibetitsmike
ibetitsmike deleted the mike/chat-wakeups-5-caps branch November 10, 2026 19:22
ibetitsmike added a commit that referenced this pull request Nov 10, 2026
…space stop in the pstack adapter (#154)

* docs: map notify_user and the daily wake-up limits in the pstack adapter

* docs: check the pstack adapter against main at d1bb658

* docs: re-pin pstack adapter cites that #115 and #136 moved

* docs: re-pin pstack adapter cites that #136 moved

* docs: say that a root archive stops the workspaces of workspace subagents

* docs: re-pin pstack adapter cites that #147 moved

* docs: qualify the wake-up limits, pause notices, inbox, and workspace autostop

* docs: condition the archive cleanup of isolated subagents on the experiment

* docs(docs/fork): qualify notification limits and the archive workspace stop

* docs(docs/fork): qualify notify_user availability, limit, and silent drops
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