mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 20:29:18 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Server processes share durable queues and wake each other with a
commit-bound PostgreSQL NOTIFY
> - The NOTIFY payload carries only `{version, origin, topic}`, so the
receiver gets an unscoped "settled" event
> - In `scoped-deadline-work.ts` an unscoped settle becomes `*`, which
reloads every candidate of that queue on the whole instance
> - On a large instance one cross-process notification can re-check
about 850 open tasks, at about 22 statements each
> - This blocks more than one server process per stack, and it costs
work during every deploy overlap
> - This pull request puts the topic's hints in the NOTIFY payload, so
the receiver reloads only the hinted scopes
> - The benefit is that a scoped commit in one process costs the same
scoped reload in every other process
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Cross-process work notifications between server processes on one
database.
**Subsystem affected**
`packages/db` work signals (`work-signals.ts`) and their consumers, such
as `server/src/services/scoped-deadline-work.ts`.
**Current behavior**
`receiveDatabaseWorkNotification` publishes "settled" with no hints. A
scoped deadline queue then reloads all of its candidates, throttled only
by its reconstruction interval.
**Proposed behavior**
The NOTIFY payload carries the deduplicated hints of its topic. The
receiving process publishes "settled" with the same hints that a local
commit publishes. Overflow and malformed input fall back to the old
unscoped behavior.
**Reason and benefit**
A scoped commit no longer causes an instance-wide reload in other
processes. This is necessary before a stack runs more than one server
process.
**Breaking changes**
None. Old and new processes interoperate in both directions (see Risks).
## What Changed
- `packages/db/src/work-signals.ts`: the per-level pending notifications
are now a map of topic to `{ hints, unscoped }`. Savepoint merge and
rollback keep the same rules as before.
- The hints follow the local "settled" semantics: the union of the hints
from `signalDatabaseWork` and `publishDatabaseWorkSettled`. An unhinted
`publishDatabaseWorkSettled`, `notifyDatabaseWorkOnCommit`, or a topic
with no hints sends the unscoped payload.
- A hinted payload is `{version: 1, origin, topic, hints: [...]}`. The
field is additive and the version stays 1.
- Each payload is at most 1,024 bytes
(`DATABASE_WORK_NOTIFICATION_MAX_BYTES`), because current receivers drop
any payload longer than 1,024 characters before they parse it. Many
hints split into several payloads. The payloads of one topic are at most
7,000 bytes in total (`DATABASE_WORK_TOPIC_NOTIFICATIONS_MAX_BYTES`). If
a topic exceeds this cap, or one hint alone does not fit, the topic
sends one unscoped payload.
- All payloads still go in the one batched `select pg_notify(...) from
jsonb_array_elements_text(...)` statement at commit. There are no added
statements or awaits on the commit path.
- `receiveDatabaseWorkNotification` accepts payloads up to 8,000
characters (the PostgreSQL limit). It keeps the drop of own-origin
payloads and of payloads without a usable origin or topic. A missing,
malformed, or empty hint list, or a version other than 1, gives an
unscoped wake. It never throws.
- The `remote_notification` debug event now logs the received hints
(`hints`: a JSON array, or `null` when unscoped).
- Tests: new payload, compatibility and fallback tests in
`packages/db/src/work-signals.test.ts`, and a new two-process test on
real PostgreSQL in
`server/src/__tests__/scoped-deadline-work-notifications.test.ts`.
## Verification
- `cd server && npx vitest run
src/__tests__/scoped-deadline-work-notifications.test.ts`: two pools on
one embedded PostgreSQL database. Process A commits work. Process B runs
a real delivery coordinator with `registerScopedDeadlineWork` over 800
candidate rows in 20 companies.
- Master (red): a commit hinted with one company makes B load `*`: 1
load, 801 rows.
- This branch (green): B loads only `company-7`: 1 load, 41 rows. A
commit with two hints loads only those two companies (80 rows). An
unscoped commit still loads all 801 rows.
- `cd packages/db && npx vitest run src/work-signals.test.ts` (32 tests,
real PostgreSQL). New tests:
- deduplicated hints per topic, including a released savepoint and a
rolled-back savepoint
- split into payloads of at most 1,024 bytes, at most 7,000 bytes in
total, and the union of hints is complete
- overflow and one oversized hint fall back to one unscoped payload
- malformed hint lists and unknown versions wake unscoped; unusable
payloads do not wake; own-origin payloads are dropped; nothing throws
- an old-format payload `{version, origin, topic}` gives an unscoped
wake
- every new payload passes a copy of the receiver from master, which
reads it as an unscoped wake for the correct topic
- the debug event logs the received hints
- With master's `work-signals.ts`, 5 of these tests fail (red). With
this branch, all pass.
- Also run: `scoped-deadline-work.test.ts`,
`delivery-work-coordinator.test.ts`, `deployment-notifications.test.ts`,
`run-start-handover.test.ts`, `heartbeat-run-start-handover.test.ts`,
`heartbeat-run-event-atomic-append.test.ts` (111 tests pass),
`work-signal-debug.test.ts` (12 pass), and `tsc --noEmit` for
`packages/db`.
## Risks
- Mixed deploys, new sender to old receiver: every payload is version 1
and at most 1,024 bytes. The old receiver ignores the `hints` field and
wakes unscoped, as today. A commit with many hints sends several
payloads, so an old receiver can get up to about 7 unscoped wakes for
one commit. The coordinator merges them into one `*` reload.
- The sender bounds bytes, and old receivers compare `.length` in UTF-16
code units. A string never has more UTF-16 code units than UTF-8 bytes,
so a payload of at most 1,024 bytes always passes the old check.
- PostgreSQL collapses identical NOTIFY payloads in one transaction. The
chunks of one topic always carry different hints, so PostgreSQL drops
none of them.
- Mixed deploys, old sender to new receiver: the old payload has no
`hints`, so the new receiver wakes unscoped, as today.
- I did not use one large payload of about 7 KB: current receivers drop
any payload over 1,024 characters before they parse it, so they would
miss the wake during a deploy overlap.
- Consumers that read hints (for example `chat-action-work`,
`approval-queue-seeding-work`) now get the same hints from another
process that they already get from a local commit. Before, they got no
hints from another process.
- The receiver accepts hint strings from the database channel. Consumers
decode them in the same way as local hints. `scoped-deadline-work`
already turns a decode failure into a `*` retry.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edit, test execution).
## 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
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
560 lines
30 KiB
TypeScript
560 lines
30 KiB
TypeScript
import { sql } from "drizzle-orm";
|
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
|
import { createDb, withDedicatedDbConnection } from "./client.js";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js";
|
|
import { workSignalDebug } from "./work-signal-debug.js";
|
|
import { DATABASE_WORK_CHANNEL, DATABASE_WORK_NOTIFICATION_MAX_BYTES, DATABASE_WORK_TOPIC_NOTIFICATIONS_MAX_BYTES, databaseWorkScopeKey, databaseWorkPending, enableDatabaseWorkNotifications, installDatabaseWorkSignals, notifyDatabaseWorkOnCommit, primeDatabaseWorkTransactionId, publishDatabaseWorkSettled, receiveDatabaseWorkNotification, reconcileDatabaseWork, signalDatabaseWork, subscribeDatabaseWork } from "./work-signals.js";
|
|
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
(support.supported ? describe : describe.skip)("database work signals", () => {
|
|
let db: ReturnType<typeof createDb>;
|
|
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
beforeAll(async () => {
|
|
temporary = await startEmbeddedPostgresTestDatabase("work-signals-");
|
|
db = createDb(temporary.connectionString);
|
|
await db.execute(sql`create table work_signal_test (id text primary key)`);
|
|
}, 90_000);
|
|
afterAll(async () => { await temporary?.cleanup(); });
|
|
|
|
it("does not touch the debug attribution log on the signal path when the flag is off", async () => {
|
|
const signal = vi.spyOn(workSignalDebug, "signal");
|
|
const event = vi.spyOn(workSignalDebug, "event");
|
|
try {
|
|
await db.transaction(async tx => {
|
|
await signalDatabaseWork(tx, "debug-off", "{\"companyId\":\"c\"}");
|
|
await tx.execute(sql`insert into work_signal_test values ('debug-off')`);
|
|
});
|
|
publishDatabaseWorkSettled(db, "debug-off");
|
|
expect(signal).not.toHaveBeenCalled();
|
|
expect(event).not.toHaveBeenCalled();
|
|
} finally { signal.mockRestore(); event.mockRestore(); }
|
|
});
|
|
|
|
it("defers nested savepoint notifications until the outer commit and preserves return values", async () => {
|
|
const events: string[] = [];
|
|
const unsubscribe = subscribeDatabaseWork(db, "nested", event => events.push(event));
|
|
try {
|
|
const result = await db.transaction(async tx => {
|
|
await tx.transaction(async nested => {
|
|
await signalDatabaseWork(nested, "nested");
|
|
await nested.execute(sql`insert into work_signal_test values ('nested')`);
|
|
});
|
|
expect(events).toEqual(["intent"]);
|
|
expect(databaseWorkPending(db, "nested")).toBe(true);
|
|
expect(await db.execute(sql`select * from work_signal_test where id = 'nested'`)).toHaveLength(0);
|
|
return 123;
|
|
});
|
|
expect(result).toBe(123);
|
|
expect(events).toEqual(["intent", "settled"]);
|
|
expect(databaseWorkPending(db, "nested")).toBe(false);
|
|
expect(await db.execute(sql`select * from work_signal_test where id = 'nested'`)).toHaveLength(1);
|
|
} finally { unsubscribe(); }
|
|
});
|
|
|
|
it("sends an untracked commit-bound hint that leaves nothing to reconcile", async () => {
|
|
const events: string[] = [];
|
|
const unsubscribe = subscribeDatabaseWork(db, "untracked", event => events.push(event));
|
|
try {
|
|
await expect(db.transaction(async tx => {
|
|
await notifyDatabaseWorkOnCommit(tx, "untracked");
|
|
throw new Error("abort");
|
|
})).rejects.toThrow("abort");
|
|
await db.transaction(async tx => { await notifyDatabaseWorkOnCommit(tx, "untracked"); });
|
|
expect(databaseWorkPending(db, "untracked")).toBe(false);
|
|
expect(events).toEqual([]);
|
|
} finally { unsubscribe(); }
|
|
});
|
|
|
|
it("reconciles a rollback without leaving a permanent pending flag", async () => {
|
|
await expect(db.transaction(async tx => {
|
|
await signalDatabaseWork(tx, "rollback");
|
|
await tx.execute(sql`insert into work_signal_test values ('rollback')`);
|
|
throw new Error("abort");
|
|
})).rejects.toThrow("abort");
|
|
await reconcileDatabaseWork(db, "rollback");
|
|
expect(databaseWorkPending(db, "rollback")).toBe(false);
|
|
expect(await db.execute(sql`select * from work_signal_test where id = 'rollback'`)).toHaveLength(0);
|
|
});
|
|
|
|
it("coalesces scoped hints and publishes them only when the outer transaction settles", async () => {
|
|
const settled: string[][] = [];
|
|
const unsubscribe = subscribeDatabaseWork(db, "scoped", (event, hints) => {
|
|
if (event === "settled") settled.push([...(hints ?? [])]);
|
|
});
|
|
try {
|
|
await db.transaction(async tx => {
|
|
await signalDatabaseWork(tx, "scoped", "connection-a");
|
|
await tx.transaction(async nested => {
|
|
await signalDatabaseWork(nested, "scoped", "connection-b");
|
|
await signalDatabaseWork(nested, "scoped", "connection-a");
|
|
});
|
|
expect(settled).toEqual([]);
|
|
});
|
|
expect(settled).toEqual([["connection-a", "connection-b"]]);
|
|
} finally { unsubscribe(); }
|
|
});
|
|
|
|
it("keeps outer ownership after a caught savepoint rollback", async () => {
|
|
const events: string[] = [];
|
|
const unsubscribe = subscribeDatabaseWork(db, "savepoint", event => events.push(event));
|
|
try {
|
|
await db.transaction(async tx => {
|
|
await expect(tx.transaction(async nested => {
|
|
await signalDatabaseWork(nested, "savepoint");
|
|
await nested.execute(sql`insert into work_signal_test values ('savepoint')`);
|
|
throw new Error("rollback savepoint");
|
|
})).rejects.toThrow("rollback savepoint");
|
|
expect(databaseWorkPending(db, "savepoint")).toBe(true);
|
|
expect(events).toEqual(["intent"]);
|
|
await signalDatabaseWork(tx, "savepoint");
|
|
await tx.execute(sql`insert into work_signal_test values ('savepoint-retry')`);
|
|
});
|
|
expect(events).toEqual(["intent", "intent", "settled"]);
|
|
expect(databaseWorkPending(db, "savepoint")).toBe(false);
|
|
} finally { unsubscribe(); }
|
|
});
|
|
|
|
it.each(["commit", "abort"])("does not clear a late %s until PostgreSQL reports a settled transaction", async outcome => {
|
|
// Inject a lost response at the client boundary while a REAL transaction
|
|
// remains open on PostgreSQL. The status probe and row visibility are real.
|
|
const raw = drizzle(db.$client);
|
|
const transaction = raw.transaction.bind(raw);
|
|
let release!: () => void;
|
|
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
let wrote!: () => void;
|
|
const written = new Promise<void>(resolve => { wrote = resolve; });
|
|
let serverDone!: Promise<unknown>;
|
|
raw.transaction = ((callback: any) => {
|
|
serverDone = transaction(async tx => {
|
|
const result = await callback(tx);
|
|
wrote();
|
|
await gate;
|
|
if (outcome === "abort") throw new Error("server abort");
|
|
return result;
|
|
});
|
|
// Observe rejection immediately; tests await the same result below.
|
|
void serverDone.catch(() => {});
|
|
return written.then(() => { throw new Error("lost transaction response"); });
|
|
}) as typeof raw.transaction;
|
|
const owner = installDatabaseWorkSignals(raw);
|
|
const topic = `late-${outcome}`;
|
|
const settled: string[][] = [];
|
|
const unsubscribe = subscribeDatabaseWork(owner, topic, (event, hints) => {
|
|
if (event === "settled") settled.push([...(hints ?? [])]);
|
|
});
|
|
try {
|
|
await expect(owner.transaction(async tx => {
|
|
await signalDatabaseWork(tx, topic, "connection-late");
|
|
await tx.execute(sql`insert into work_signal_test values (${topic})`);
|
|
})).rejects.toThrow("lost transaction response");
|
|
await reconcileDatabaseWork(owner, topic);
|
|
expect(databaseWorkPending(owner, topic)).toBe(true);
|
|
expect(await db.execute(sql`select * from work_signal_test where id = ${topic}`)).toHaveLength(0);
|
|
settled.length = 0;
|
|
release(); await serverDone.catch(() => {});
|
|
await reconcileDatabaseWork(owner, topic);
|
|
expect(settled).toEqual([["connection-late"]]);
|
|
expect(databaseWorkPending(owner, topic)).toBe(false);
|
|
expect(await db.execute(sql`select * from work_signal_test where id = ${topic}`)).toHaveLength(outcome === "commit" ? 1 : 0);
|
|
} finally { release(); await serverDone?.catch(() => {}); unsubscribe(); }
|
|
});
|
|
|
|
it("resolves an uncertain transaction with a transaction id that a statement returned", async () => {
|
|
await expect(db.transaction(async tx => {
|
|
const [{ xid }] = await tx.execute(sql`select pg_current_xact_id()::text as xid`);
|
|
primeDatabaseWorkTransactionId(tx, xid as string);
|
|
await signalDatabaseWork(tx, "primed-disconnect");
|
|
await tx.execute(sql`insert into work_signal_test values ('primed-disconnect')`);
|
|
const [{ pid }] = await tx.execute(sql`select pg_backend_pid() as pid`);
|
|
await db.execute(sql`select pg_terminate_backend(${pid as number})`);
|
|
await tx.execute(sql`select 1`);
|
|
})).rejects.toThrow();
|
|
expect(databaseWorkPending(db, "primed-disconnect")).toBe(true);
|
|
await reconcileDatabaseWork(db, "primed-disconnect");
|
|
expect(databaseWorkPending(db, "primed-disconnect")).toBe(false);
|
|
expect(await db.execute(sql`select * from work_signal_test where id = 'primed-disconnect'`)).toHaveLength(0);
|
|
});
|
|
|
|
it("publishes a settled wake at once outside a transaction, and inside one only after the outermost commit", async () => {
|
|
const events: Array<[string, string[]]> = [];
|
|
const unsubscribe = subscribeDatabaseWork(db, "settled-after-commit", (event, hints) => events.push([event, [...hints ?? []]]));
|
|
try {
|
|
publishDatabaseWorkSettled(db, "settled-after-commit", "outside");
|
|
expect(events).toEqual([["settled", ["outside"]]]);
|
|
events.length = 0;
|
|
await db.transaction(async tx => {
|
|
publishDatabaseWorkSettled(tx, "settled-after-commit", "committed");
|
|
await tx.transaction(async savepoint => { publishDatabaseWorkSettled(savepoint, "settled-after-commit", "released"); });
|
|
await expect(tx.transaction(async savepoint => {
|
|
publishDatabaseWorkSettled(savepoint, "settled-after-commit", "rolled-back-savepoint");
|
|
throw new Error("savepoint rollback");
|
|
})).rejects.toThrow("savepoint rollback");
|
|
expect(events).toEqual([]);
|
|
});
|
|
expect(events).toEqual([["settled", ["committed"]], ["settled", ["released"]]]);
|
|
events.length = 0;
|
|
await expect(db.transaction(async tx => {
|
|
publishDatabaseWorkSettled(tx, "settled-after-commit", "rolled-back");
|
|
throw new Error("outer rollback");
|
|
})).rejects.toThrow("outer rollback");
|
|
expect(events).toEqual([]);
|
|
expect(databaseWorkPending(db, "settled-after-commit")).toBe(false);
|
|
} finally { unsubscribe(); }
|
|
});
|
|
|
|
it("recovers after a real backend disconnect without replaying the queue write", async () => {
|
|
await expect(db.transaction(async tx => {
|
|
await signalDatabaseWork(tx, "disconnect");
|
|
await tx.execute(sql`insert into work_signal_test values ('disconnect')`);
|
|
const [{ pid }] = await tx.execute(sql`select pg_backend_pid() as pid`);
|
|
await db.execute(sql`select pg_terminate_backend(${pid as number})`);
|
|
await tx.execute(sql`select 1`);
|
|
})).rejects.toThrow();
|
|
await reconcileDatabaseWork(db, "disconnect");
|
|
expect(databaseWorkPending(db, "disconnect")).toBe(false);
|
|
expect(await db.execute(sql`select * from work_signal_test where id = 'disconnect'`)).toHaveLength(0);
|
|
});
|
|
|
|
it("shares notifications with dedicated child pools but isolates unrelated roots and topics", async () => {
|
|
const listener = vi.fn();
|
|
const other = createDb(temporary.connectionString);
|
|
const unsubscribe = subscribeDatabaseWork(db, "dedicated", listener);
|
|
try {
|
|
await other.transaction(tx => signalDatabaseWork(tx, "dedicated"));
|
|
await db.transaction(tx => signalDatabaseWork(tx, "other"));
|
|
expect(listener).not.toHaveBeenCalled();
|
|
await withDedicatedDbConnection(db, dedicated => dedicated.transaction(tx => signalDatabaseWork(tx, "dedicated")));
|
|
expect(listener.mock.calls.map(([event]) => event)).toEqual(["intent", "settled"]);
|
|
} finally { unsubscribe(); await other.$client.end(); }
|
|
});
|
|
|
|
it("never changes transaction success because a listener throws", async () => {
|
|
const warn = vi.spyOn(process, "emitWarning").mockImplementation(() => {});
|
|
const unsubscribe = subscribeDatabaseWork(db, "listener", () => { throw new Error("listener"); });
|
|
try {
|
|
await expect(db.transaction(async tx => { await signalDatabaseWork(tx, "listener"); return 7; })).resolves.toBe(7);
|
|
expect(warn).toHaveBeenCalledTimes(2);
|
|
} finally { unsubscribe(); warn.mockRestore(); }
|
|
});
|
|
});
|
|
|
|
describe("work signal query boundaries", () => {
|
|
it("adds no SQL to transactions which do not register queue work", async () => {
|
|
const execute = vi.fn();
|
|
const connection = installDatabaseWorkSignals({ execute, transaction: async (callback: any) => callback({ execute, transaction: async () => {} }) });
|
|
await expect(connection.transaction(async () => 19)).resolves.toBe(19);
|
|
expect(execute).not.toHaveBeenCalled();
|
|
});
|
|
it("fails before the write if XID acquisition fails, without retaining uncertainty", async () => {
|
|
const execute = vi.fn().mockRejectedValue(new Error("disconnected"));
|
|
const connection = installDatabaseWorkSignals({ execute, transaction: async (callback: any) => callback({ execute, transaction: async () => {} }) });
|
|
const write = vi.fn();
|
|
await expect(connection.transaction(async (tx: any) => { await signalDatabaseWork(tx, "failed"); write(); })).rejects.toThrow("disconnected");
|
|
expect(write).not.toHaveBeenCalled();
|
|
expect(databaseWorkPending(connection, "failed")).toBe(false);
|
|
});
|
|
it("reads no transaction id when a statement of the transaction already returned it", async () => {
|
|
const execute = vi.fn();
|
|
const connection = installDatabaseWorkSignals({ execute, transaction: async (callback: any) => callback({ execute, transaction: async () => {} }) });
|
|
primeDatabaseWorkTransactionId(connection, "outside");
|
|
await connection.transaction(async (tx: any) => {
|
|
primeDatabaseWorkTransactionId(tx, "42");
|
|
await signalDatabaseWork(tx, "primed");
|
|
await signalDatabaseWork(tx, "primed-again");
|
|
});
|
|
expect(execute).not.toHaveBeenCalled();
|
|
});
|
|
it("rejects registration on an autocommit root", async () => {
|
|
const connection = installDatabaseWorkSignals({ execute: vi.fn(), transaction: vi.fn() });
|
|
await expect(signalDatabaseWork(connection, "bad")).rejects.toThrow("inside a transaction");
|
|
});
|
|
});
|
|
|
|
|
|
describe("database work scope identity", () => {
|
|
type TestConnection = { execute: () => Promise<unknown[]>; transaction: (callback: (tx: TestConnection) => unknown) => Promise<unknown> };
|
|
function connection(): TestConnection {
|
|
return { execute: vi.fn(async () => []), transaction: async callback => callback(connection()) };
|
|
}
|
|
it("shares owner identity through child pools and nested transactions, but isolates independent owners", async () => {
|
|
const first = installDatabaseWorkSignals(connection());
|
|
const second = installDatabaseWorkSignals(connection());
|
|
const child = installDatabaseWorkSignals(connection(), first);
|
|
const key = databaseWorkScopeKey(first);
|
|
expect(databaseWorkScopeKey(second)).not.toBe(key);
|
|
expect(databaseWorkScopeKey(child)).toBe(key);
|
|
await child.transaction(async tx => {
|
|
expect(databaseWorkScopeKey(tx)).toBe(key);
|
|
await tx.transaction(async nested => { expect(databaseWorkScopeKey(nested)).toBe(key); });
|
|
});
|
|
});
|
|
});
|
|
|
|
(support.supported ? describe : describe.skip)("database work notifications flushed once per transaction", () => {
|
|
let db: ReturnType<typeof createDb>;
|
|
let listener: ReturnType<typeof createDb>;
|
|
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
const delivered: string[] = [];
|
|
let notifyStatements = 0;
|
|
let sentPayloads: string[] = [];
|
|
beforeAll(async () => {
|
|
temporary = await startEmbeddedPostgresTestDatabase("work-signals-notify-");
|
|
db = createDb(temporary.connectionString);
|
|
enableDatabaseWorkNotifications(db);
|
|
listener = createDb(temporary.connectionString, { maxConnections: 1 });
|
|
await listener.$client.listen(DATABASE_WORK_CHANNEL, payload => { delivered.push(payload); });
|
|
db.$client.options.debug = (_connection: number, query: string, parameters: unknown[]) => {
|
|
if (!/pg_notify/.test(query) || parameters.some(value => String(value).includes("fence"))) return;
|
|
notifyStatements += 1;
|
|
sentPayloads.push(...JSON.parse(String(parameters[parameters.length - 1])) as string[]);
|
|
};
|
|
}, 90_000);
|
|
afterAll(async () => {
|
|
await listener?.$client.end({ timeout: 1 });
|
|
await db?.$client.end({ timeout: 1 });
|
|
await temporary?.cleanup();
|
|
});
|
|
const topic = (payload: string) => (JSON.parse(payload) as { topic: string }).topic;
|
|
async function run(action: (root: typeof db) => Promise<unknown>) {
|
|
notifyStatements = 0;
|
|
sentPayloads = [];
|
|
delivered.length = 0;
|
|
let failure: unknown = null;
|
|
await action(db).catch(error => { failure = error; });
|
|
await db.execute(sql`select pg_notify(${DATABASE_WORK_CHANNEL}, ${JSON.stringify({ topic: "fence" })})`);
|
|
await vi.waitFor(() => expect(delivered.some(payload => topic(payload) === "fence")).toBe(true));
|
|
const received = delivered.filter(payload => topic(payload) !== "fence");
|
|
return { statements: notifyStatements, sent: sentPayloads.map(topic), delivered: received.map(topic), payloads: received,
|
|
failure: failure instanceof Error ? failure.message : failure };
|
|
}
|
|
const rollback = () => { throw new Error("rollback"); };
|
|
|
|
it("sends every distinct topic of a transaction in one statement at commit, in first-signal order", async () => {
|
|
const result = await run(root => root.transaction(async tx => {
|
|
await signalDatabaseWork(tx, "a", "one");
|
|
await signalDatabaseWork(tx, "b");
|
|
await signalDatabaseWork(tx, "a", "two");
|
|
await notifyDatabaseWorkOnCommit(tx, "c");
|
|
expect(notifyStatements).toBe(0);
|
|
}));
|
|
expect(result).toMatchObject({ statements: 1, sent: ["a", "b", "c"], delivered: ["a", "b", "c"], failure: null });
|
|
expect(result.payloads.map(payload => JSON.parse(payload))).toEqual([
|
|
{ version: 1, origin: expect.any(String), topic: "a", hints: ["one", "two"] },
|
|
{ version: 1, origin: expect.any(String), topic: "b" },
|
|
{ version: 1, origin: expect.any(String), topic: "c" },
|
|
]);
|
|
});
|
|
|
|
it("sends nothing for a transaction that signals nothing", async () => {
|
|
expect(await run(root => root.transaction(async tx => { await tx.execute(sql`select 1`); })))
|
|
.toMatchObject({ statements: 0, delivered: [] });
|
|
});
|
|
|
|
it("keeps a released savepoint's topics, two levels deep, and drops a rolled-back savepoint's topics", async () => {
|
|
expect(await run(root => root.transaction(async tx => {
|
|
await tx.transaction(async first => {
|
|
await first.transaction(async second => { await signalDatabaseWork(second, "kept"); });
|
|
await first.transaction(async second => { await signalDatabaseWork(second, "dropped"); rollback(); }).catch(() => {});
|
|
});
|
|
await tx.transaction(async nested => { await signalDatabaseWork(nested, "dropped-too"); rollback(); }).catch(() => {});
|
|
}))).toMatchObject({ statements: 1, sent: ["kept"], delivered: ["kept"], failure: null });
|
|
});
|
|
|
|
it("still sends a topic signalled in a rolled-back savepoint when the outer level signals it again", async () => {
|
|
expect(await run(root => root.transaction(async tx => {
|
|
await tx.transaction(async nested => { await signalDatabaseWork(nested, "a"); rollback(); }).catch(() => {});
|
|
await signalDatabaseWork(tx, "a");
|
|
}))).toMatchObject({ statements: 1, delivered: ["a"] });
|
|
expect(await run(root => root.transaction(async tx => {
|
|
await signalDatabaseWork(tx, "a");
|
|
await tx.transaction(async nested => { await signalDatabaseWork(nested, "a"); rollback(); }).catch(() => {});
|
|
}))).toMatchObject({ statements: 1, delivered: ["a"] });
|
|
});
|
|
|
|
it("sends nothing when the callback throws", async () => {
|
|
expect(await run(root => root.transaction(async tx => { await signalDatabaseWork(tx, "a"); rollback(); })))
|
|
.toMatchObject({ statements: 0, delivered: [], failure: "rollback" });
|
|
});
|
|
|
|
it("fails and rolls back the transaction when the commit-time send fails", async () => {
|
|
await db.execute(sql`create table if not exists work_signal_flush_test (id text primary key)`);
|
|
const result = await run(root => root.transaction(async tx => {
|
|
await tx.execute(sql`insert into work_signal_flush_test values ('flush')`);
|
|
await signalDatabaseWork(tx, "a");
|
|
await tx.execute(sql`select 1 / 0`).catch(() => {});
|
|
}));
|
|
expect(result.delivered).toEqual([]);
|
|
expect(result.statements).toBe(1);
|
|
expect(result.failure).toMatch(/pg_notify/);
|
|
expect(await db.execute(sql`select id from work_signal_flush_test where id = 'flush'`)).toHaveLength(0);
|
|
});
|
|
|
|
it("sends a large number of distinct topics in one bounded statement", async () => {
|
|
const names = Array.from({ length: 500 }, (_, index) => `topic-${index}`);
|
|
const result = await run(root => root.transaction(async tx => { for (const name of names) await signalDatabaseWork(tx, name); }));
|
|
expect(result.statements).toBe(1);
|
|
expect(result.delivered).toEqual(names);
|
|
});
|
|
|
|
it("rejects a signal recorded after its transaction or savepoint ended instead of losing it", async () => {
|
|
let outer: Parameters<Parameters<typeof db.transaction>[0]>[0] | undefined;
|
|
let savepoint: typeof outer;
|
|
const result = await run(root => root.transaction(async tx => {
|
|
outer = tx;
|
|
await signalDatabaseWork(tx, "a");
|
|
await tx.transaction(async nested => { savepoint = nested; await signalDatabaseWork(nested, "b"); });
|
|
await expect(signalDatabaseWork(savepoint!, "late-savepoint")).rejects.toThrow("after its transaction or savepoint ended");
|
|
await expect(notifyDatabaseWorkOnCommit(savepoint!, "late-savepoint")).rejects.toThrow("after its transaction or savepoint ended");
|
|
}));
|
|
expect(result).toMatchObject({ statements: 1, delivered: ["a", "b"], failure: null });
|
|
await expect(signalDatabaseWork(outer!, "late-outer")).rejects.toThrow("after its transaction or savepoint ended");
|
|
await expect(notifyDatabaseWorkOnCommit(outer!, "late-outer")).rejects.toThrow("after its transaction or savepoint ended");
|
|
});
|
|
|
|
it("starts every transaction clean, including concurrent transactions and a retried callback", async () => {
|
|
expect(await run(async root => {
|
|
await root.transaction(async tx => { await signalDatabaseWork(tx, "a"); });
|
|
await root.transaction(async tx => { await signalDatabaseWork(tx, "a"); });
|
|
await Promise.all([1, 2].map(() => root.transaction(async tx => { await signalDatabaseWork(tx, "b"); })));
|
|
let attempts = 0;
|
|
const callback = async (tx: Parameters<Parameters<typeof root.transaction>[0]>[0]) => {
|
|
attempts += 1;
|
|
await signalDatabaseWork(tx, "c");
|
|
if (attempts === 1) rollback();
|
|
};
|
|
await root.transaction(callback).catch(() => {});
|
|
await root.transaction(callback);
|
|
})).toMatchObject({ statements: 5, delivered: ["a", "a", "b", "b", "c"] });
|
|
});
|
|
|
|
function legacyReceive(payload: string): string | null {
|
|
if (payload.length > 1024) return null;
|
|
let value: { version?: unknown; origin?: unknown; topic?: unknown };
|
|
try { value = JSON.parse(payload); } catch { return null; }
|
|
if (!value || value.version !== 1 || typeof value.origin !== "string"
|
|
|| typeof value.topic !== "string" || !/^[a-zA-Z0-9:_-]{1,200}$/.test(value.topic)) return null;
|
|
return value.topic;
|
|
}
|
|
function receiving(topics: string[]) {
|
|
const receiver = createDb(temporary.connectionString, { maxConnections: 1 });
|
|
const wakes: Array<[string, string[] | null]> = [];
|
|
const stops = topics.map(name => subscribeDatabaseWork(receiver, name, (event, hints) => {
|
|
wakes.push([name, hints ? [...hints] : null]);
|
|
expect(event).toBe("settled");
|
|
}));
|
|
return {
|
|
receiver, wakes,
|
|
deliver(payloads: string[]) { for (const payload of payloads) receiveDatabaseWorkNotification(receiver, payload); },
|
|
async close() { for (const stop of stops) stop(); await receiver.$client.end({ timeout: 1 }); },
|
|
};
|
|
}
|
|
|
|
it("carries a commit's deduplicated hints, so another process wakes only those scopes", async () => {
|
|
const other = receiving(["hinted", "unhinted", "mixed"]);
|
|
try {
|
|
const result = await run(root => root.transaction(async tx => {
|
|
await signalDatabaseWork(tx, "hinted", "company-1");
|
|
await tx.transaction(async nested => {
|
|
await signalDatabaseWork(nested, "hinted", "company-2");
|
|
publishDatabaseWorkSettled(nested, "hinted", "company-1");
|
|
});
|
|
await tx.transaction(async nested => { await signalDatabaseWork(nested, "hinted", "rolled-back"); rollback(); }).catch(() => {});
|
|
await signalDatabaseWork(tx, "unhinted");
|
|
await signalDatabaseWork(tx, "mixed", "company-3");
|
|
publishDatabaseWorkSettled(tx, "mixed");
|
|
}));
|
|
expect(result).toMatchObject({ statements: 1, sent: ["hinted", "unhinted", "mixed"], failure: null });
|
|
expect(result.payloads.map(payload => JSON.parse(payload).hints)).toEqual([["company-1", "company-2"], undefined, undefined]);
|
|
other.deliver(result.payloads);
|
|
expect(other.wakes).toEqual([["hinted", ["company-1", "company-2"]], ["unhinted", null], ["mixed", null]]);
|
|
expect(result.payloads.map(legacyReceive)).toEqual(["hinted", "unhinted", "mixed"]);
|
|
} finally { await other.close(); }
|
|
});
|
|
|
|
it("splits many hints into payloads an older receiver still reads, within the per-topic byte cap", async () => {
|
|
const hints = Array.from({ length: 80 }, (_, index) => JSON.stringify({ companyId: `company-${String(index).padStart(4, "0")}` }));
|
|
const other = receiving(["many"]);
|
|
try {
|
|
const result = await run(root => root.transaction(async tx => { for (const hint of hints) await signalDatabaseWork(tx, "many", hint); }));
|
|
expect(result.statements).toBe(1);
|
|
expect(result.payloads.length).toBeGreaterThan(1);
|
|
for (const payload of result.payloads) expect(Buffer.byteLength(payload)).toBeLessThanOrEqual(DATABASE_WORK_NOTIFICATION_MAX_BYTES);
|
|
expect(result.payloads.reduce((total, payload) => total + Buffer.byteLength(payload), 0))
|
|
.toBeLessThanOrEqual(DATABASE_WORK_TOPIC_NOTIFICATIONS_MAX_BYTES);
|
|
expect(result.payloads.flatMap(payload => JSON.parse(payload).hints)).toEqual(hints);
|
|
expect(result.payloads.map(legacyReceive)).toEqual(result.payloads.map(() => "many"));
|
|
other.deliver(result.payloads);
|
|
expect(other.wakes.flatMap(([, received]) => received ?? ["*"])).toEqual(hints);
|
|
} finally { await other.close(); }
|
|
});
|
|
|
|
it("falls back to one unscoped notification when a topic's hints exceed the byte cap", async () => {
|
|
const tooMany = Array.from({ length: 400 }, (_, index) => `scope-${index}-${"x".repeat(20)}`);
|
|
const tooLong = "y".repeat(DATABASE_WORK_NOTIFICATION_MAX_BYTES);
|
|
const other = receiving(["overflow", "long-hint"]);
|
|
try {
|
|
const result = await run(root => root.transaction(async tx => {
|
|
for (const hint of tooMany) await signalDatabaseWork(tx, "overflow", hint);
|
|
await signalDatabaseWork(tx, "long-hint", "short");
|
|
await signalDatabaseWork(tx, "long-hint", tooLong);
|
|
}));
|
|
expect(result.payloads.map(payload => JSON.parse(payload))).toEqual([
|
|
{ version: 1, origin: expect.any(String), topic: "overflow" },
|
|
{ version: 1, origin: expect.any(String), topic: "long-hint" },
|
|
]);
|
|
other.deliver(result.payloads);
|
|
expect(other.wakes).toEqual([["overflow", null], ["long-hint", null]]);
|
|
} finally { await other.close(); }
|
|
});
|
|
|
|
it("treats a malformed or unknown-version hint list as unscoped and ignores unusable or own-origin payloads", async () => {
|
|
const other = receiving(["remote"]);
|
|
const warn = vi.spyOn(process, "emitWarning");
|
|
try {
|
|
const own = await run(root => root.transaction(async tx => { await signalDatabaseWork(tx, "remote", "mine"); }));
|
|
const ownEvents: string[] = [];
|
|
const stopOwn = subscribeDatabaseWork(db, "remote", event => ownEvents.push(event));
|
|
try { receiveDatabaseWorkNotification(db, own.payloads[0]!); } finally { stopOwn(); }
|
|
expect(ownEvents).toEqual([]);
|
|
const origin = "another-process";
|
|
const payload = (value: Record<string, unknown>) => JSON.stringify({ version: 1, origin, topic: "remote", ...value });
|
|
other.deliver([
|
|
payload({ hints: "company-1" }),
|
|
payload({ hints: ["company-1", 7] }),
|
|
payload({ hints: [] }),
|
|
payload({ hints: null }),
|
|
payload({ version: 2, hints: ["company-1"] }),
|
|
payload({}),
|
|
]);
|
|
expect(other.wakes).toEqual(Array.from({ length: 6 }, () => ["remote", null]));
|
|
other.wakes.length = 0;
|
|
expect(() => other.deliver([
|
|
"not json", "null", "[]", "7", JSON.stringify({ origin, topic: "remote", hints: ["a"] }),
|
|
payload({ version: "1" }), payload({ version: 1.5 }), payload({ version: 0 }), payload({ origin: 4 }),
|
|
payload({ topic: "bad topic" }), payload({ hints: ["a".repeat(9000)] }),
|
|
])).not.toThrow();
|
|
expect(other.wakes).toEqual([]);
|
|
other.deliver([payload({ hints: ["company-9"] })]);
|
|
expect(other.wakes).toEqual([["remote", ["company-9"]]]);
|
|
expect(warn).not.toHaveBeenCalled();
|
|
} finally { warn.mockRestore(); await other.close(); }
|
|
});
|
|
|
|
it("logs the received hints in the remote notification debug event", async () => {
|
|
const enabled = vi.spyOn(workSignalDebug, "enabled", "get").mockReturnValue(true);
|
|
const event = vi.spyOn(workSignalDebug, "event").mockImplementation(() => {});
|
|
const other = receiving([]);
|
|
try {
|
|
other.deliver([
|
|
JSON.stringify({ version: 1, origin: "another-process", topic: "debugged", hints: ["company-1", "company-2"] }),
|
|
JSON.stringify({ version: 1, origin: "another-process", topic: "debugged" }),
|
|
]);
|
|
expect(event.mock.calls.filter(([, name]) => name === "remote_notification")).toEqual([
|
|
["debugged", "remote_notification", { hints: JSON.stringify(["company-1", "company-2"]) }],
|
|
["debugged", "remote_notification", { hints: null }],
|
|
]);
|
|
} finally { enabled.mockRestore(); event.mockRestore(); await other.close(); }
|
|
});
|
|
});
|