Files
PaperClipAI/packages/db/src/work-signals.ts
T
DottaandClaude Opus 5.5 95a6ab31e6 feat(db): attribute work signals by caller behind a debug flag (#21640)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Background queues wake from work signals. A transaction calls
`signalDatabaseWork(topic, hint)`, and the delivery coordinator wakes
the queue for that topic with that hint.
> - On a hosted instance with zero runs, the stranded-assignment
recovery queue re-checks tasks about 7 times a second. About 2.6 hinting
commits per second drive it. HTTP traffic, chat review polls and local
fixtures with all heartbeat workers do not explain the writer.
> - Statement statistics show what runs, but not who signalled it.
Nothing records the caller of a work signal or why a queue woke.
> - This pull request adds an opt-in attribution log for work signals
and recovery-queue wakes, off by default.
> - The benefit is that one short run on an affected instance names the
writer of any idle signal loop, without code changes.

## Linked Issues or Issue Description

No issue exists. This describes the gap with the fields of
`.github/ISSUE_TEMPLATE/enhancement.yml`.

**What existing behavior does this improve?**

Observability of `signalDatabaseWork`
(`packages/db/src/work-signals.ts`) and of the issue recovery queues
(`server/src/services/recovery/work.ts`).

**Current behavior**

A queue that wakes several times a second at idle shows up only as
repeated statements. Nothing tells you which caller published the hint,
whether the wake came from another process, a reconnect, a direct
settled publish or a stored deadline, or which load and check it caused.

**Proposed behavior**

An environment variable, `PAPERCLIP_DEBUG_WORK_SIGNALS`, read once when
the module loads. It holds a comma-separated topic allowlist, and each
topic can carry `:N` for its stack sampling rate. When it is unset or
empty, the signal path only checks one boolean and does nothing else.

**Reason and benefit**

Several idle-load loops this week took hours of statement analysis
before the writer was found. Attribution by caller turns that into one
log query.

## What Changed

- `packages/db/src/work-signal-debug.ts` (new):
- `parseWorkSignalDebugSpec` reads `topic[:N],…`. An optional numeric
suffix is parsed from the right, so topics that contain colons (for
example `live:<companyId>`) work with or without `:N`. N defaults to 20;
malformed entries are ignored.
- `createWorkSignalDebug` returns `enabled`, `allows(topic)`,
`signal(topic, hint, entry)`, `event(topic, name, fields, stack, entry)`
and `flush()`. A disabled instance constructs no `Error`, captures no
stack, builds no line and starts no timer.
- Stack capture (`captureWorkSignalStack(entry)`) raises
`Error.stackTraceLimit` to 40 and restores it in a `finally`. It calls
`Error.captureStackTrace(holder, entry)`, so V8 cuts every frame above
the public entry (`signalDatabaseWork`, `publishDatabaseWorkSettled`, or
the recovery `wake()`).
- Frames are dropped by file (`node_modules`, `node:internal`, the
signal wrapper files) and by function name (`signalDatabaseWork`,
`notifyDeliveryWork`, …), so trimming works on the bundled `index.mjs`.
Positions are kept raw (`index.mjs:L:C`) for offline source-map lookup.
At most 10 frames are kept.
- Each (topic, event) pair has its own budget of 10 lines per second,
checked BEFORE any stack is captured. A `suppressed` line names the
topic, the dropped event and the count. Frequent `check` lines therefore
never drop `signal` or `direct_wake` lines.
- Stack sampling (1 in N) counts per (topic, event), so `check` and
`load` do not shift the phase of `signal` sampling. `direct_wake` always
captures its caller's stack.
- Lines go to an in-memory buffer that an unref'd 1-second timer flushes
to stderr. The signal path does no I/O and no await.
- `workSignalDebug` is the process instance, built from
`process.env.PAPERCLIP_DEBUG_WORK_SIGNALS` once at module load.
- `packages/db/src/work-signals.ts`: when enabled, it records:
  - `signal` in `signalDatabaseWork`;
  - `remote_notification` and `notification_reconnect`;
- `settled_publish` (with a sampled stack) for
`publishDatabaseWorkSettled`;
  - `uncertain_settled` when an uncertain transaction resolves.
- `server/src/services/recovery/work.ts`: under the same flag:
  - each task-queue `load` logs its scope key;
- each `check` logs the issue and company id, `dueAt`, and `wake:
"deadline"` or `"load"`. The marker rides on the queued entry itself,
and only while the flag is on, so nothing is tracked otherwise and
nothing outlives the entry;
- `wake()` logs ONE `direct_wake` line listing the queues it actually
invalidates (assigned-work only when registered), under the first
allowlisted one, with its caller's stack.
- **No request route is logged.** The server has no request async
context to read one synchronously, and this change does not add one.
- `docs/deploy/environment-variables.md`: documents the flag, internal
ids only, raw positions, and that enabling or changing it requires a
restart.
- Tests:
  - `packages/db/src/work-signal-debug.test.ts`, 12 tests:
- strict no-op when unset or empty (no `Error`, no `captureStackTrace`,
no stack capture, no sink);
    - the process instance is disabled without the env;
    - allowlist filtering, and spec parsing including colon topics;
    - per-(topic, event) sampling, and always-on direct-wake stacks;
- source-tree trimming, and a synthetic single-file bundle stack with
raw positions kept and wrappers dropped by name;
    - real capture below the entry with the limit raised and restored;
- checks at about 8/s alongside signals at about 3/s for 5 seconds, with
every signal line kept;
    - suppressed records never capture a stack;
    - buffered, timer-driven output.
- `packages/db/src/work-signals.test.ts`: on real PostgreSQL, the signal
and settled-publish paths never call the debug log while the flag is
off.
- `server/src/__tests__/issue-recovery-work-debug-attribution.test.ts`,
on the recovery fixture with real PostgreSQL:
    - no recovery log calls while the flag is off;
- with the flag on, a run graph hint logs its signal, the graph-scoped
load and the check;
- `wake()` logs exactly one `direct_wake` that lists the queues and
carries the caller's stack.

## Verification

- `packages/db`: `vitest run src/work-signal-debug.test.ts
src/work-signals.test.ts`: 39 passed. `tsc --noEmit` passes.
- `server`: `vitest run
src/__tests__/issue-recovery-work-debug-attribution.test.ts
src/__tests__/issue-recovery-deadlines.test.ts`: 17 passed. `tsc
--noEmit` passes.
- Staging values:
`PAPERCLIP_DEBUG_WORK_SIGNALS=stranded-assignments:10`, then restart.
- Sample output from the synthetic single-file bundle test:

```
{"msg":"paperclip work signal debug","at":1000000,"event":"signal","topic":"stranded-assignments","hint":"{\"companyId\":\"c\",\"graphRunId\":\"r\"}","stack":["at notifyIssueGraphRecovery (file:///app/server/dist-runtime/index.mjs:120456:11)","at async notifyRunDispatch (file:///app/server/dist-runtime/index.mjs:120501:3)","at async PostgresJsDatabase.connection.transaction [as transaction] (file:///app/server/dist-runtime/index.mjs:4021:22)","at async Object.settleRunProjection (file:///app/server/dist-runtime/index.mjs:300777:5)","at async file:///app/server/dist-runtime/index.mjs:310002:17"]}
{"msg":"paperclip work signal debug","at":1000000,"event":"check","topic":"stranded-assignments","issueId":"i","companyId":"c","wake":"load","dueAt":1}
{"msg":"paperclip work signal debug","at":1000000,"event":"direct_wake","topic":"stranded-assignments","queues":"stranded-assignments,orphan-blockers","stack":["at notifyIssueGraphRecovery (file:///app/server/dist-runtime/index.mjs:120456:11)","…"]}
{"msg":"paperclip work signal debug","at":1001000,"event":"suppressed","topic":"stranded-assignments","suppressedEvent":"check","count":17}
```

## Risks

- Low risk. It is off by default. While off, each signal costs one
property read and one boolean check.
- While on, the log can show internal ids from hints (company, issue,
run). It holds no secrets and no user identifiers, and the topic
allowlist limits what is logged.
- Stack capture costs CPU. Sampling (default 1 in 20) and the 10 lines
per second cap bound it.
- The file owner of `packages/db/src/work-signals.ts` reviews this
before merge.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits, local PostgreSQL test runs).

## 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
- [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

Related: #21621.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:54:00 -06:00

221 lines
11 KiB
TypeScript

import { sql } from "drizzle-orm";
import { randomUUID } from "node:crypto";
import { workSignalDebug } from "./work-signal-debug.js";
// Hints about existing durable queues; process-local by default, with optional
// commit-bound PostgreSQL notifications during controller replacement. No SQL
// triggers, tables, timers, or query replay. Only registered work fetches an XID.
type Listener = (event: "intent" | "settled", hints?: ReadonlySet<string>) => void;
type Transaction = { topics: Set<string>; hints: Map<string, Set<string>>; xid?: Promise<string>; uncertain: boolean };
type Scope = { key: object; listeners: Map<string, Set<Listener>>; transactions: Set<Transaction>; root: Connection; notificationOrigin: string; notify: boolean };
type Context = { scope: Scope; transaction?: Transaction; pending?: Map<string, string>; settled?: Array<[string, string | undefined]>; ended?: boolean };
type Connection = { transaction: (...args: any[]) => Promise<any>; execute: (...args: any[]) => Promise<any> };
const contexts = new WeakMap<object, Context>();
function publish(scope: Scope, topic: string, event: "intent" | "settled" = "settled", hints?: ReadonlySet<string>) {
for (const listener of scope.listeners.get(topic) ?? []) {
try { listener(event, hints); }
catch (error) { process.emitWarning(`Database work listener failed: ${String(error)}`); }
}
}
/** Installed once by createDb; dedicated child pools share their owner's scope. */
export function installDatabaseWorkSignals<T extends Connection>(db: T, owner?: object): T {
const scope = (owner && contexts.get(owner)?.scope) || { key: {}, listeners: new Map(), transactions: new Set(), root: db, notificationOrigin: randomUUID(), notify: false };
install(db, { scope });
return db;
}
function install(connection: Connection, context: Context) {
contexts.set(connection, context);
const transaction = connection.transaction;
connection.transaction = async function (callback, ...options) {
// Nested savepoints belong to the outermost transaction. Even a released
// savepoint must not wake a consumer before its parent commits.
const state = context.transaction ?? { topics: new Set<string>(), hints: new Map<string, Set<string>>(), uncertain: false };
try {
let level: Context | undefined;
const result = await transaction.call(this, async (tx: Connection) => {
const current: Context = { scope: context.scope, transaction: state, pending: new Map(), settled: [] };
level = current;
install(tx, current);
try {
const value = await callback(tx);
current.ended = true;
if (!context.transaction) await flushNotifications(tx, current.pending!);
return value;
} finally { current.ended = true; }
}, ...options);
if (context.pending && level?.pending) {
for (const [key, payload] of level.pending) if (!context.pending.has(key)) context.pending.set(key, payload);
}
if (context.transaction) context.settled?.push(...level?.settled ?? []);
else for (const [topic, hint] of level?.settled ?? []) publish(context.scope, topic, "settled", hint === undefined ? undefined : new Set([hint]));
if (!context.transaction) context.scope.transactions.delete(state);
return result;
} catch (error) {
if (!context.transaction) {
// An XID is known before the first opted-in write can execute. If
// acquisition itself failed there cannot be a corresponding write.
if (state.xid) state.uncertain = true;
else context.scope.transactions.delete(state);
}
throw error;
} finally {
if (!context.transaction) for (const topic of state.topics) publish(context.scope, topic, "settled", state.hints.get(topic));
}
};
}
/** Await BEFORE the queue write, on its transaction. Nested transactions work. */
export async function signalDatabaseWork(connection: object, topic: string, hint?: string): Promise<void> {
const context = contexts.get(connection);
if (!context) return; // Lightweight service test doubles have no DB lifecycle.
const state = context.transaction;
if (!state) throw new Error("Database work must be registered inside a transaction");
if (workSignalDebug.enabled) workSignalDebug.signal(topic, hint, signalDatabaseWork);
state.topics.add(topic);
if (hint !== undefined) {
let hints = state.hints.get(topic);
if (!hints) state.hints.set(topic, hints = new Set());
hints.add(hint);
}
context.scope.transactions.add(state);
publish(context.scope, topic, "intent", state.hints.get(topic));
if (!state.xid) {
state.xid = (connection as Connection).execute(sql`select pg_current_xact_id()::text as xid`)
.then((rows: { xid: string }[]) => rows[0]!.xid);
}
// Keep a failed acquisition distinguishable from an uncertain queue write.
try { await state.xid; }
catch (error) { state.xid = undefined; throw error; }
if (context.scope.notify) notifyAtCommit(context, notification(context.scope, topic));
}
export function primeDatabaseWorkTransactionId(connection: object, xid: string): void {
const state = contexts.get(connection)?.transaction;
if (state && !state.xid) state.xid = Promise.resolve(xid);
}
function notifyAtCommit(context: Context, payload: string): void {
if (context.ended) throw new Error("Database work was signalled after its transaction or savepoint ended");
const key = `${DATABASE_WORK_CHANNEL}\u0000${payload}`;
if (!context.pending!.has(key)) context.pending!.set(key, payload);
}
async function flushNotifications(connection: Connection, pending: Map<string, string>): Promise<void> {
if (pending.size === 0) return;
await connection.execute(sql`select pg_notify(${DATABASE_WORK_CHANNEL}, payload)
from jsonb_array_elements_text(${JSON.stringify([...pending.values()])}::jsonb) as notification(payload)`);
}
export const DATABASE_WORK_CHANNEL = "paperclip_work_v1";
const validTopic = (topic: string) => /^[a-zA-Z0-9:_-]{1,200}$/.test(topic);
function notification(scope: Scope, topic: string) {
if (!validTopic(topic)) throw new Error("Invalid database work topic");
return JSON.stringify({ version: 1, origin: scope.notificationOrigin, topic });
}
export function enableDatabaseWorkNotifications(owner: object): void {
const scope = contexts.get(owner)?.scope;
if (!scope) throw new Error("Database work notifications require createDb");
scope.notify = true;
}
/**
* A commit-bound hint to other server processes, sent on the transaction's own connection. Unlike
* signalDatabaseWork it registers no local intent, so a failed transaction leaves nothing to reconcile
* on another pool. For writers whose correctness never depends on this hint (best-effort wakes).
*/
export async function notifyDatabaseWorkOnCommit(connection: object, topic: string): Promise<void> {
const context = contexts.get(connection);
if (!context?.scope.notify) return;
if (!context.transaction) throw new Error("Database work must be registered inside a transaction");
notifyAtCommit(context, notification(context.scope, topic));
}
export function databaseWorkCommitNotification(owner: object, topic: string): string | null {
const scope = contexts.get(owner)?.scope;
return scope?.notify ? notification(scope, topic) : null;
}
export function publishDatabaseWorkSettled(owner: object, topic: string, hint?: string): void {
const context = contexts.get(owner);
if (!context) return;
if (workSignalDebug.enabled) workSignalDebug.event(topic, "settled_publish", { hint }, "sampled", publishDatabaseWorkSettled);
if (!context.transaction) {
publish(context.scope, topic, "settled", hint === undefined ? undefined : new Set([hint]));
return;
}
if (context.ended) throw new Error("Database work was signalled after its transaction or savepoint ended");
context.settled!.push([topic, hint]);
if (context.scope.notify) notifyAtCommit(context, notification(context.scope, topic));
}
/** A post-commit invalidation hint, for already-persisted live UI state. */
export async function publishDatabaseWorkHint(owner: object, topic: string): Promise<void> {
const scope = contexts.get(owner)?.scope;
if (scope?.notify) await scope.root.execute(sql`select pg_notify(${DATABASE_WORK_CHANNEL}, ${notification(scope, topic)})`);
}
export function receiveDatabaseWorkNotification(owner: object, payload: string): void {
const scope = contexts.get(owner)?.scope;
if (!scope || payload.length > 1024) return;
let value: { version?: unknown; origin?: unknown; topic?: unknown };
try { value = JSON.parse(payload); } catch { return; }
if (!value || value.version !== 1 || typeof value.origin !== "string" || value.origin === scope.notificationOrigin
|| typeof value.topic !== "string" || !validTopic(value.topic)) return;
if (workSignalDebug.enabled) workSignalDebug.event(value.topic, "remote_notification");
publish(scope, value.topic);
}
/** Reconnect can lose hints. Reconstruct existing durable queues once; no poll. */
export function reconcileDatabaseWorkNotifications(owner: object): void {
const scope = contexts.get(owner)?.scope;
if (scope) for (const topic of scope.listeners.keys()) {
if (workSignalDebug.enabled) workSignalDebug.event(topic, "notification_reconnect");
publish(scope, topic);
}
}
export function databaseWorkPending(owner: object, topic: string): boolean {
return [...(contexts.get(owner)?.scope.transactions ?? [])].some(state => state.topics.has(topic));
}
/** Resolve only failed transactions, on a fresh root-pool statement. Call
* BEFORE the queue scan so rows from a newly confirmed commit are visible.
* NULL means the XID aged out; it can no longer be in progress, so scanning
* the durable queue is sufficient even though its outcome is unavailable.
*/
export async function reconcileDatabaseWork(owner: object, topic: string): Promise<void> {
const scope = contexts.get(owner)?.scope;
if (!scope) return;
for (const state of [...scope.transactions]) {
if (!state.uncertain || !state.topics.has(topic) || !state.xid) continue;
const xid = await state.xid;
const rows = await scope.root.execute(sql`select pg_xact_status(${xid}::xid8) as status`);
if (rows[0]?.status === "in progress") continue;
if (!rows.length || ![null, "committed", "aborted"].includes(rows[0].status)) {
throw new Error("Unexpected database transaction status");
}
scope.transactions.delete(state);
for (const affected of state.topics) {
if (workSignalDebug.enabled) workSignalDebug.event(affected, "uncertain_settled", { status: rows[0]?.status ?? null });
publish(scope, affected, "settled", state.hints.get(affected));
}
}
}
/** Includes intent, outer settlement, and uncertainty-resolution changes. */
export function subscribeDatabaseWork(owner: object, topic: string, listener: Listener): () => void {
const context = contexts.get(owner);
if (!context) throw new Error("Database work subscriptions require createDb");
let listeners = context.scope.listeners.get(topic);
if (!listeners) context.scope.listeners.set(topic, listeners = new Set());
listeners.add(listener);
if (databaseWorkPending(owner, topic)) {
try { listener("intent"); } catch (error) { process.emitWarning(`Database work listener failed: ${String(error)}`); }
}
return () => { listeners.delete(listener); };
}
export function databaseWorkScopeKey(connection: object): object {
return contexts.get(connection)?.scope.key ?? connection;
}