Repository navigation
feat(coderd/x/chatd): cap chat wake-ups per day and add notify_user - #115
Conversation
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.
…oder into mike/chat-wakeups-2-worker
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.
… mike/chat-wakeups-3-loop
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.
… mike/chat-wakeups-3-loop
…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.
… mike/chat-wakeups-3-loop
…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.
…ike/chat-wakeups-4-events
…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.
# Conflicts: # coderd/database/forkdb/chat_wakeups.sql.go
…ait_for_events watches
# Conflicts: # coderd/x/chatd/fork_wait_for_events.go
# 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
|
@codex review
|
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
There was a problem hiding this comment.
💡 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".
…ain on a new UTC day
|
@codex review
|
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
Closing and reopening only to make GitHub recompute the merge ref against current main ( |
The merge ref now points at current main ( |
Merge evidence for head
|
…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
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_usertool, behindfork-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:daily_run_caporg_daily_run_capdaily_spend_caporg_daily_spend_capeventswake-ups it runs only when a child is about to be sent, so a wake-up with nothing pending is never paused.pausedwith the reason above. It records no run and sends no message.total_cost_microsof 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.New forkdb queries
SumChatCostMicrosSince,SumOrganizationWakeupChatCostMicrosSinceandCountChatUserNotificationsSinceget dbauthz and dbmetrics wrappers andTestForkQuerierentries.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 existinghook_denied,invalid_cronandinvalid_eventspauses. The PR2 TODO forhook_deniedis 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_usertoolappendForkToolsaddsnotify_usernext toschedule_wakeupandwait_for_events. It takes amessageand an optionaltitle(the chat title by default), validates them likePOST /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 withchat_idin 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 implementsSerialToolCalls, so parallel calls in one step each see the calls before them.Known
chat_id, so they count toward a chat'snotify_userlimit. A chat can have at most seven pause reasons a day, so the effect is small.notify_usercount scansnotification_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.notify_usercalls with the same title and message in the same minute hit the enqueuer dedupe. The second call still returnssent: truebut stores nothing.Validation
go build ./...,go vet ./coderd/x/chatd/ ./coderd/database/..., forkdbgenerate.shwith no drift,go test -run 'Wakeup|WaitForEvents|ScheduleWakeup|Loop|NotifyUser|TestAppendForkTools' ./coderd/x/chatd/,TestForkQuerier, and the forkdb and dbmetrics packages.>=changed to>, the 24-hour window removed, the org sum counting human-only chats,COALESCEdropped, each pause notification removed, the rate limit removed, dbauthz actions changed, the default title not cut,SerialToolCallsoff)./loopafter 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_cronnotified,notify_usersent 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_deniednotification andeventswake-ups at a cap (unit tests only), the limit reset after an hour, the system-owner refusal, and email, webhook or push delivery.