Skip to content

chatd: store wake-up watches as rows instead of an events JSON and run keys #293

Closed

Description

@ibetitsmike

Filed by Xum (an AI coding agent) on behalf of @ibetitsmike. Part of #311. Line numbers are at 607a95b.

Summary

A wait_for_events wake-up stores what it watches as a JSON array in chat_wakeups.events, and stores what it already delivered as string run keys in chat_wakeup_runs. Because neither is queryable, the only way to learn whether a watched child finished is to load the wake-up, load every child of the chat, load the run keys, and compare them in Go. That evaluation runs for every waiting wake-up on every 15 s tick.

Replace the JSON and the run keys with one row per watched thing. Then "which wake-ups have something to deliver" is one SQL statement for the whole deployment, and the per-wake-up evaluation disappears.

This is a breaking schema change. It is the data model that #294 needs.

Evidence

Current storage and evaluation:

  • fork_wait_for_events.go:71-92 wakeupEvent: one JSON entry per watched child, process or pull request, with baselines (since, head_sha, seen) inside the same blob.
  • fork_wait_for_events.go:366-382 deliverEventsWakeup: unmarshal the blob, childrenSnapshot, ListChatWakeupRunKeys.
  • fork_wait_for_events.go:403-424: for each entry, slices.Contains(keys, childDoneRunKey(...)), then find the child in the snapshot, then childDone.
  • fork_wait_for_events.go:608-648 childrenSnapshot: a REPEATABLE READ transaction with three queries, one of which (ListPendingChatDescendantQuestionsByRoot) evaluates a JSONB rule over chat_messages.
  • fork_wait_for_events.go:546-556 eventsWakeupRunAt: when nothing was delivered, next_run_at = now + 15 s, so the row is due again on the next tick.
  • fork_wait_for_events.go:657-700 watchedRunKeys: to answer "is this child already watched", it lists every wake-up of the chat and runs ListChatWakeupRunKeys once per active wake-up.

Cost, from the tracking issue: 12 statements, 14 round trips and 2 row updates per waiting wake-up per tick. The release update is not HOT (next_run_at is indexed), so each poll inserts into all 4 indexes of chat_wakeups and writes about 0.5 kB of WAL in steady state.

chat_wakeup_runs has no reader outside the worker: it is not in the API (fork_chat_wakeups.go:192 returns only run_count and last_run_at from the wake-up row). It is used for idempotency (fork_wakeups.go:279-292) and for cap counting (fork_wakeup_caps.go:127-134), and it is never purged.

Proposed design

Schema (new chatdmig node)

CREATE TYPE chat_wakeup_watch_kind AS ENUM ('child_done', 'process', 'pull_request');

CREATE TABLE chat_wakeup_watches (
    id              uuid PRIMARY KEY,
    wakeup_id       uuid NOT NULL REFERENCES chat_wakeups(id) ON DELETE CASCADE,
    chat_id         uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,     -- the chat to wake
    organization_id uuid NOT NULL,
    kind            chat_wakeup_watch_kind NOT NULL,
    -- exactly one target, by kind
    child_chat_id   uuid REFERENCES chats(id) ON DELETE CASCADE,
    agent_id        uuid,
    process_id      text,
    pull_request_url text,
    spec            jsonb NOT NULL DEFAULT '{}',   -- per-kind options and baselines (output pattern, PR events, head sha, seen)
    -- set by whoever observed the event (see #295, #296); NULL for child_done, which is read from chats
    fired_at        timestamptz,
    fired_payload   jsonb,
    -- set in the delivery transaction; a delivered watch is done
    delivered_at    timestamptz,
    deliveries      integer NOT NULL DEFAULT 0     -- for process output lines, which can fire more than once
);
CREATE INDEX chat_wakeup_watches_open_wakeup_idx ON chat_wakeup_watches (wakeup_id) WHERE delivered_at IS NULL;
CREATE INDEX chat_wakeup_watches_open_child_idx  ON chat_wakeup_watches (child_chat_id) WHERE delivered_at IS NULL AND kind = 'child_done';
CREATE INDEX chat_wakeup_watches_open_process_idx ON chat_wakeup_watches (agent_id, process_id) WHERE delivered_at IS NULL AND kind = 'process';
CREATE INDEX chat_wakeup_watches_open_pr_idx     ON chat_wakeup_watches (pull_request_url) WHERE delivered_at IS NULL AND kind = 'pull_request';

Drop chat_wakeups.events. Drop chat_wakeup_runs (after #297 replaces its cap counts; if this issue lands first, keep the table for caps only and stop reading run keys). Existing events wake-ups are experimental state: cancel them in the migration with status_reason = 'migrated' instead of converting the JSON.

"Due" becomes one predicate

A child_done watch is ready when its child is done by the existing rule of childDone (fork_wait_for_events.go:593-602): archived, or settled in a status other than running, interrupting, paused, and not itself waiting for events or for an answer. In SQL:

-- name: ListReadyChatWakeupWatches :many
SELECT x.*
FROM chat_wakeup_watches x
JOIN chat_wakeups w ON w.id = x.wakeup_id AND w.status = 'active'
JOIN chats c ON c.id = x.chat_id                         -- the chat to wake must be idle
LEFT JOIN chats k ON k.id = x.child_chat_id
WHERE x.delivered_at IS NULL
  AND NOT c.archived
  AND c.status NOT IN ('running', 'interrupting', 'requires_action', 'paused')
  AND (sqlc.narg('chat_id')::uuid IS NULL OR x.chat_id = sqlc.narg('chat_id')::uuid)
  AND (
        x.fired_at IS NOT NULL
     OR (x.kind = 'child_done' AND (
            k.id IS NULL OR k.archived
         OR (k.status NOT IN ('running', 'interrupting', 'paused')
             AND NOT EXISTS (SELECT 1 FROM chat_wakeup_watches y            -- child waits for its own children
                             JOIN chat_wakeups yw ON yw.id = y.wakeup_id AND yw.status = 'active'
                             WHERE y.chat_id = k.id AND y.delivered_at IS NULL)
             AND NOT EXISTS (SELECT 1 FROM chat_descendant_questions q     -- child waits for an answer (see #300)
                             WHERE q.chat_id = k.id AND q.answered_at IS NULL))))
      )
ORDER BY x.wakeup_id, x.id
LIMIT sqlc.arg('limit_count')::int;

The set of open watches is small (only live waits), every join is on a primary key or a partial index, and with no open watches the query touches one empty partial index.

Behavior that stays

  • One message per watched entry, never while the chat is busy.
  • A child that is gone has nothing to report: its watch row is deleted by the cascade.
  • The "already watched by wake-up X" guard of waitForEventsChildren becomes one indexed lookup on chat_wakeup_watches_open_child_idx.
  • Expiry: an events wake-up keeps expires_at. Its next_run_at is set to expires_at once, so the timer path of chatd: replace the 15 s wake-up claim loop with a waker driven by the chat state machine #294 completes it; it is no longer rescheduled every 15 s.

Idempotency

Delivery sets delivered_at on the watch row in the same transaction as the chat message, under the wake-up row lock. That replaces the unique (wakeup_id, run_key) insert. The TLA+ model in the tracking issue shows that an idempotency record written in the message transaction is what gives at-most-once delivery.

Acceptance criteria

  • chat_wakeups.events and run-key matching are gone; git grep -n 'childDoneRunKey\|ListChatWakeupRunKeys\|watchedRunKeys' returns nothing.
  • A forkdb test seeds 1 chat with 3 children and one wake-up watching them, and asserts ListReadyChatWakeupWatches returns nothing while all run, exactly the finished child after one finishes, nothing while the parent is running, and nothing for a child that has an open watch of its own.
  • EXPLAIN of ListReadyChatWakeupWatches on a database with 10,000 completed wake-ups and no open watch shows no sequential scan of chat_wakeups, chats or chat_messages.
  • The existing behavior tests of wait_for_events (one message per child, expiry, archived child, child that asks a question) pass against the new tables.

Depends on

Activity

  1. added
    enhancement
    performance
    on Nov 14, 2026
  2. ibetitsmike commented on Nov 14, 2026

    @ibetitsmike
    OwnerAuthor

    Coder Agents acted on behalf of @ibetitsmike.

    Maintainer note before this is delegated. Order: #300 first (in progress), then this issue.

    Design change: the migration should convert active events wake-ups into watch rows, not cancel them with status_reason = 'migrated'. Every merge to main deploys the daily server, and the maintainer chats themselves wait through wait_for_events. Cancelling those waits during the deploy would silently drop their wake-ups. The conversion maps each JSON entry to one row: child, process and pull_request entries with their baselines in spec. A run key that already exists sets delivered_at.

  3. ibetitsmike commented on Nov 15, 2026

    @ibetitsmike
    OwnerAuthor

    Coder Agents acted on behalf of @ibetitsmike.

    Delegated on 2026-11-15 to a workstream agent, branch mike/issue-293-watch-rows, now that #300 has merged (3f37f49). The brief follows the maintainer note above: the migration converts active events wake-ups into watch rows and never cancels them. It uses answered_at from #300. It keeps chat_wakeup_runs for cap counts until #297.

  4. ibetitsmike commented on Nov 15, 2026

    @ibetitsmike
    OwnerAuthor

    Coder Agents acted on behalf of @ibetitsmike.

    #339 (bottom: table, queries, forkdb tests) merged as 61fcbfd at 14:38Z. #340 (backfill and chatd switch, closes this issue) is retargeted to main and goes next, after the deploy, a fresh fork-ci run and a Codex receipt on its new head.

  5. ibetitsmike commented on Nov 15, 2026

    @ibetitsmike
    OwnerAuthor

    Coder Agents acted on behalf of @ibetitsmike.

    #340 merged as cdf3579 (15:24Z). With #339 (61fcbfd) this replaces the events JSON and run-key matching with chat_wakeup_watches rows. Ready child watches come from one query, ListReadyChatWakeupWatches. The backfill converts every events wake-up and never cancels one; an active wake-up with no convertible entry is paused with invalid_events. chat_wakeup_runs stays for cap counts until #297. Expiry still polls every 15 s; that is left to #294. Gate evidence is on #340.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementperformance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions