Files
PaperClipAI/packages/db/src
DottaandClaude Opus 5.5 8aaf983151 perf(db): send a transaction's work notifications in one statement at commit (#21436)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server signals queue work with database work signals, and it
sends a PostgreSQL notification for each signal so that another server
can wake during a deploy overlap
> - Each signal sends its own `select pg_notify($1, $2)`, inside the
open transaction, and waits for it
> - On staging this is the most-called statement in the database: 31.8
per second, 15.1 million calls in total against 7.5 million `begin`,
about 3.7 awaits per transaction
> - Every await inside an open transaction holds its locks and its
connection for one more turn of a saturated event loop
> - This pull request collects a transaction's notifications and sends
them in one statement just before commit
> - The benefit is at most one notification round trip per transaction,
with the same payloads delivered at the same commit

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Database work signals send one `pg_notify` statement per signal, inside
the transaction.

**Subsystem affected**
`packages/db` work signals, used by every delivery queue in the server.

**Current behavior**
`signalDatabaseWork` and `notifyDatabaseWorkOnCommit` each run `select
pg_notify(channel, payload)` on the transaction and wait for it.
`notifyIssueRecovery` alone signals 7 queues per call, and a transaction
often calls it several times. A local legacy run (wake, start, 20 output
lines, finish) sends 424 notification statements. Staging measures 31.8
per second, 8.5 `begin` per second.

**Proposed behavior**
A signal inside a transaction records its payload on that transaction.
Before the outermost commit, the transaction sends every distinct
payload in one statement. Payloads and the channel are byte-identical to
today's, and PostgreSQL still delivers them only on commit.

**Reason and benefit**
At most one notification statement per transaction instead of one per
signal. Fewer awaits while a transaction holds its locks and its
connection.

**Breaking changes**
None. The listener protocol and the payload format do not change.

## What Changed

- `packages/db/src/work-signals.ts`: a signal records `(channel,
payload)` on the current transaction level. A released savepoint merges
its records into its parent; a rolled-back savepoint drops them. The
outermost transaction sends all distinct payloads in one statement
(`select pg_notify(channel, payload) from
jsonb_array_elements_text($2::jsonb)`) after its callback returns and
before commit. A transaction that signals nothing sends no extra
statement.
- The record lives on the transaction object only. A retried callback
gets a new transaction object and starts empty.
- `publishDatabaseWorkHint` (outside a transaction) is unchanged and
still sends at once.
- `packages/db/src/work-signals.test.ts`: tests on real PostgreSQL with
a LISTEN client.

## Verification

- `pnpm --filter @paperclipai/db exec vitest run
src/work-signals.test.ts`: 22 pass. 6 of the new tests fail on master.
- New tests (real PostgreSQL, LISTEN client, asserting what is delivered
as well as what is sent):
- Distinct topics in one transaction: one statement at commit. The
payloads delivered are identical to the format on master (`{version,
origin, topic}`), in first-signal order.
  - A transaction that signals nothing: no notification statement.
- Savepoints: a released savepoint two levels deep keeps its topic. A
rolled-back savepoint drops its topic. A topic from a rolled-back
savepoint that the outer level signals again is still delivered.
  - The callback throws: nothing is sent or delivered.
- The commit-time send fails: the transaction fails and rolls back its
write, and nothing is delivered.
  - 500 distinct topics: one statement, all 500 delivered.
  - Sequential, concurrent and retried transactions each start clean.
- Server suites that use notifications pass: `deployment-notifications`,
`run-start-handover`, `heartbeat-run-start-handover`,
`agent-runtime-hooks`, `legacy-controller-lease`,
`heartbeat-run-dispatch-lifecycle` (99 tests). Two of them hit statement
timeouts once on a loaded machine and then passed 41/41 when run alone.
- Before and after, one local legacy run (embedded PostgreSQL, process
adapter, 20 output lines 50 ms apart, uninstrumented pass, alternating
arms):
`TSX_DISABLE_CACHE=1 UNITS=legacy TASKS=50 AGENTS=3
NODE_OPTIONS=--expose-gc pnpm --filter @paperclipai/server exec tsx
scripts/query-cost/drive.ts` (harness from #21413)

  | Per legacy run | Before (2 runs) | After (2 runs) |
  | --- | --- | --- |
  | Statements | 883, 883 | 474, 491 |
  | `pg_notify` statements | 424 | 21 (one per signalling transaction) |
  | Notification round trips per signalling transaction | about 20 | 1 |
  | Transactions (BEGIN plus COMMIT) | 72 | 72 |
  | Allocated | 81.1, 79.3 MB | 76.3, 74.3 MB |
  | Wall time | 5.0, 5.2 s | 4.1, 7.7 s (noisy: loaded machine) |

Statement counts are exact and stable. Allocation fell by about 5 MB per
run (about 6%). Wall time varies too much on this machine to compare.
- Staging, measured by the coordinator (Neon statistics, 64 seconds):
31.8 `pg_notify` per second, 8.5 `begin` per second. At about 44 KB of
allocation per statement, notifications cost about 1.4 MB/s, about 2.4%
of the 57.6 MB/s. The allocation saving is part of that, about 2%, and
it is not the reason for this change. The reason is round trips inside
open transactions: at most one notification statement per transaction
instead of about 3.7. The per-second effect on staging is an estimate
until it is measured after deploy.

## Risks

- A failure of the notification send now surfaces at commit time, not at
the signal call. No caller catches errors around a signal call and
continues: the only `.catch` near a signal (`notifyBudgetStopsSettled`)
wraps a root-level call that is not in a transaction and already fails
before this change.
- Order within a transaction: notifications are sent in first-signal
order. A savepoint's records join its parent when the savepoint is
released, which matches the order of sequential code. Listeners do not
depend on order: each payload is an independent hint, and PostgreSQL
already removes duplicate payloads within a transaction.
- The notification is sent after the transaction's last statement
instead of in the middle. Delivery still happens only at commit, as
before.

Remaining work, not in this pull request: sending stops being useful
when no other server listens. The listener is open only during a startup
handoff, while this process owns a native execution, or during a
run-start handover, and a server drops its own notifications. A later
change could send only while an overlap is possible. It would have to
prove this interleaving: a new server announces itself, the old server
is still outside its own window, and the old server must start sending
before the new server relies on a hint. Otherwise the new server waits
for its next reconciliation pass.

## Model Used

- Claude Opus 5.5 (claude-opus-5-5), Anthropic, with tool use and code
execution in Claude Code.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes (no
documentation describes the send timing)
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:39:36 -06:00
..
…