Multiplayer agent harness for work.
Drain the final items queue in bulk keyset passes during promotion
Regan Bell960592b2755d
diff --git a/package.json b/package.jsonindex 967552409..5a1f40ca0 100644--- a/package.json+++ b/package.json@@ -48,7 +48,7 @@"sandbox:local:build": "bash scripts/local-sandbox-build.sh","sandbox:porter:build": "docker build --platform linux/amd64 -t \"${PORTER_SANDBOX_IMAGE:?Set PORTER_SANDBOX_IMAGE to the registry tag to publish}\" porter && docker push \"$PORTER_SANDBOX_IMAGE\"","deploy:porter-runner-image": "docker build --platform linux/amd64 -t \"${PORTER_DEPLOY_RUNNER_IMAGE:?Set PORTER_DEPLOY_RUNNER_IMAGE to the registry tag to publish}\" -f deploy/porter-runner/Dockerfile . && docker push \"$PORTER_DEPLOY_RUNNER_IMAGE\"",- "test:pg": "node scripts/run-pg-tests.mjs test/batch-paths.test.ts test/session-append-many.test.ts test/cron-queue.test.ts test/postgres-migration-startup.test.ts test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-tapeless-store.test.ts test/postgres-legacy-tape-steps.test.ts test/postgres-items-copy.test.ts test/semantic-memory-pg.test.ts test/semantic-memory-http.test.ts test/semantic-memory-large-pg.test.ts test/postgres-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-acl-file-id-migration.test.ts test/postgres-admin-grants.test.ts test/postgres-teams.test.ts test/postgres-decisions.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-linked-identity-membership.test.ts test/postgres-map.test.ts test/postgres-background-ownership.test.ts test/postgres-resource-search.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-cron-run-as-migration.test.ts test/postgres-trigger-recipient-consent-migration.test.ts test/postgres-legacy-harness-migration.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-app-page-views.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/loop-ingress-pg.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/run-retry-delay.test.ts test/run-priority.test.ts test/postgres-run-stream.test.ts test/postgres-items-migration.test.ts test/postgres-items-promotion.test.ts test/postgres-items-contract.test.ts test/pi-harness-replay-fidelity.test.ts test/migrate-main.test.ts",+ "test:pg": "node scripts/run-pg-tests.mjs test/batch-paths.test.ts test/session-append-many.test.ts test/cron-queue.test.ts test/postgres-migration-startup.test.ts test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-tapeless-store.test.ts test/postgres-legacy-tape-steps.test.ts test/postgres-items-copy.test.ts test/postgres-items-bulk-catchup.test.ts test/postgres-items-parallel-catchup.test.ts test/semantic-memory-pg.test.ts test/semantic-memory-http.test.ts test/semantic-memory-large-pg.test.ts test/postgres-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-acl-file-id-migration.test.ts test/postgres-admin-grants.test.ts test/postgres-teams.test.ts test/postgres-decisions.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-linked-identity-membership.test.ts test/postgres-map.test.ts test/postgres-background-ownership.test.ts test/postgres-resource-search.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-cron-run-as-migration.test.ts test/postgres-trigger-recipient-consent-migration.test.ts test/postgres-legacy-harness-migration.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-app-page-views.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/loop-ingress-pg.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/run-retry-delay.test.ts test/run-priority.test.ts test/postgres-run-stream.test.ts test/postgres-items-migration.test.ts test/postgres-items-promotion.test.ts test/postgres-items-contract.test.ts test/pi-harness-replay-fidelity.test.ts test/migrate-main.test.ts","livetest": "node scripts/api-livetest.ts","bench:memory": "node --env-file-if-exists=.env scripts/memory-bench.ts","prepare": "node .husky/install.mjs",diff --git a/scripts/ops/items-copy.ts b/scripts/ops/items-copy.tsindex e3dc06f48..d07b0c4d2 100644--- a/scripts/ops/items-copy.ts+++ b/scripts/ops/items-copy.ts@@ -111,7 +111,7 @@ export class ItemsCopyOperator {});}- async assertState(phases: string[], lock: "UPDATE" | "SHARE" = "UPDATE") {+ async assertState(phases: string[], lock: "UPDATE" | "SHARE" | "KEY SHARE" = "UPDATE") {const {rows: [cutover],} = await this.client.query(@@ -237,18 +237,23 @@ export class ItemsCopyOperator {});}- async catchupBatch() {+ async catchupBatch(worker = 0, workers = 1) {return this.transaction(async () => {- await this.assertState(["catchup", "verified", "ready"]);- return this.drainBatch();- });+ await this.assertState(["catchup", "verified", "ready"], "KEY SHARE");+ return this.drainBatch(worker, workers);+ }, true);}- async drainBatch() {+ async drainBatch(worker = 0, workers = 1) {await this.client.query("TRUNCATE pg_temp.items_copy_batch");const {rows: [entry],- } = await this.client.query(`SELECT * FROM ${dirty} ORDER BY touched_at,session_id LIMIT 1`);+ } = await this.client.query(+ `SELECT * FROM ${dirty}+ WHERE (hashtext(session_id)::bigint & 2147483647) % $2 = $1+ ORDER BY touched_at,session_id LIMIT 1`,+ [worker, workers],+ );if (!entry) return 0;const version = entry.copy_version ?? entry.version;const params = [entry.session_id, entry.cursor_seq ?? -1, this.batch];@@ -328,7 +333,13 @@ export class ItemsCopyOperator {"SELECT count(*)::int AS n FROM public.session_leases WHERE expires_at>(extract(epoch FROM clock_timestamp())*1000)::bigint",);if (leases.n) throw new Error("active session leases remain; drain writers before finishing the copy");- while (await this.drainBatch()) continue;+ await this.snapshotDirty();+ for (let cursor: { session: string; seq: number } | null = { session: "", seq: -1 }; cursor;)+ cursor = (await this.bulkStep(cursor)).next;+ const {+ rows: [left],+ } = await this.client.query(`SELECT count(*)::int AS n FROM ${dirty}`);+ if (left.n) throw new Error("queued items changes remain after the final drain");const {rows: [{ valid }],} = await this.client.query(@@ -454,6 +465,148 @@ export class ItemsCopyOperator {count(*) FILTER (WHERE done)::int AS done FROM ${slices}) sl`)).rows[0];}+ async snapshotDirty(worker = 0, workers = 1) {+ await this.client.query("DROP TABLE IF EXISTS pg_temp.items_copy_snap");+ await this.client.query(+ `CREATE TEMP TABLE items_copy_snap AS SELECT session_id,version FROM ${dirty}+ WHERE (hashtext(session_id)::bigint & 2147483647) % $2 = $1`,+ [worker, workers],+ );+ await this.client.query("ALTER TABLE pg_temp.items_copy_snap ADD PRIMARY KEY(session_id)");+ return (await this.client.query("SELECT count(*)::int AS n FROM pg_temp.items_copy_snap")).rows[0].n as number;+ }+ async bulkCatchupBatch(cursor: { session: string; seq: number }, window = 50) {+ return this.transaction(async () => {+ await this.assertState(["catchup", "verified", "ready"], "KEY SHARE");+ return this.bulkStep(cursor, window);+ }, true);+ }+ async bulkStep(cursor: { session: string; seq: number }, window = 50) {+ await this.client.query("TRUNCATE pg_temp.items_copy_batch");+ await this.client.query(+ `INSERT INTO pg_temp.items_copy_batch+ WITH s AS (SELECT session_id FROM pg_temp.items_copy_snap WHERE session_id>=$1 ORDER BY session_id LIMIT $4),+ k AS (SELECT e.session_id,e.seq FROM s JOIN public.session_entries e USING(session_id)+ UNION SELECT i.session_id,i.seq::int FROM s JOIN public.items i+ ON i.tenant_id=(SELECT id FROM public.qm_tenant) AND i.session_id=s.session_id)+ SELECT session_id,seq FROM k WHERE (session_id,seq)>($1,$2) ORDER BY session_id,seq LIMIT $3`,+ [cursor.session, cursor.seq, this.batch, window],+ );+ const {+ rows: [last],+ } = await this.client.query(+ "SELECT session_id,seq,(SELECT count(*)::int FROM pg_temp.items_copy_batch) AS n FROM pg_temp.items_copy_batch ORDER BY session_id DESC,seq DESC LIMIT 1",+ );+ const n = (last?.n ?? 0) as number;+ if (n) await this.replaceSelected();+ let done: string | null;+ let next: { session: string; seq: number } | null;+ if (n < this.batch) {+ const {+ rows: [w],+ } = await this.client.query(+ "SELECT max(session_id) AS hi FROM (SELECT session_id FROM pg_temp.items_copy_snap WHERE session_id>=$1 ORDER BY session_id LIMIT $2) s",+ [cursor.session, window],+ );+ done = w.hi;+ next =+ w.hi === null || (w.hi === cursor.session && cursor.seq === 2147483647)+ ? null+ : { session: w.hi, seq: 2147483647 };+ if (done !== null) await this.finishSnapshot("s.session_id>=$1 AND s.session_id<=$2", [cursor.session, done]);+ } else {+ next = { session: last.session_id, seq: last.seq };+ await this.finishSnapshot("s.session_id>=$1 AND s.session_id<$2", [cursor.session, last.session_id]);+ }+ return { rows: n, next };+ }+ async finishSnapshot(range: string, params: string[]) {+ await this.client.query(+ `DELETE FROM ${dirty} d USING pg_temp.items_copy_snap s+ WHERE d.session_id=s.session_id AND d.version=s.version AND ${range}`,+ params,+ );+ await this.client.query(+ `UPDATE ${dirty} d SET copy_version=NULL,cursor_seq=NULL FROM pg_temp.items_copy_snap s+ WHERE d.session_id=s.session_id AND ${range}`,+ params,+ );+ }+}++export async function catchupBulk(+ url: string,+ batch: number,+ workers: number,+ progress: (p: Record<string, unknown>) => void,+ signal?: AbortSignal,+) {+ if (!Number.isSafeInteger(workers) || workers < 1 || workers > 32)+ throw new Error("workers must be between 1 and 32");+ let failed: unknown = null;+ await Promise.all(+ Array.from({ length: workers }, async (_, worker) => {+ const client = new pg.Client({ connectionString: url, application_name: "qm-items-copy" });+ try {+ await client.connect();+ const op = new ItemsCopyOperator(client, batch);+ const sessions = await op.snapshotDirty(worker, workers);+ let cursor: { session: string; seq: number } | null = { session: "", seq: -1 };+ let rows = 0;+ let batches = 0;+ while (cursor && failed === null && !signal?.aborted) {+ const r = await op.bulkCatchupBatch(cursor);+ rows += r.rows;+ cursor = r.next;+ if (++batches % 20 === 0 || !cursor)+ progress({ worker, sessions, batches, rows, cursor: cursor?.session ?? null });+ }+ } catch (error) {+ failed ??= error;+ } finally {+ await client.end();+ }+ }),+ );+ if (failed !== null) throw failed;+ signal?.throwIfAborted();+}++export async function catchupParallel(+ url: string,+ batch: number,+ workers: number,+ progress: (value: Record<string, unknown>) => void,+ signal?: AbortSignal,+) {+ if (!Number.isSafeInteger(workers) || workers < 1 || workers > 32)+ throw new Error("workers must be between 1 and 32");+ let remaining = true;+ while (remaining && !signal?.aborted) {+ let failed: unknown = null;+ const counts = await Promise.all(+ Array.from({ length: workers }, async (_, worker) => {+ const client = new pg.Client({ connectionString: url, application_name: "qm-items-copy" });+ let batches = 0;+ try {+ await client.connect();+ const op = new ItemsCopyOperator(client, batch);+ while (failed === null && !signal?.aborted && (await op.catchupBatch(worker, workers))) {+ if (++batches % 20 === 0) progress({ worker, batches, ...(await op.status()) });+ }+ return Number((await op.status()).queued);+ } catch (error) {+ failed ??= error;+ return 0;+ } finally {+ await client.end();+ }+ }),+ );+ if (failed !== null) throw failed;+ remaining = counts.some((count) => count > 0);+ }+ signal?.throwIfAborted();}async function main() {@@ -520,8 +673,9 @@ async function main() {await op.completeCopy();}if (action === "catchup") {- let batches = 0;- while (await op.catchupBatch()) if (++batches % 20 === 0) console.log(JSON.stringify(await op.status()));+ await catchupParallel(process.env.DATABASE_URL, op.batch, Number(values.workers), (value) =>+ console.log(JSON.stringify(value)),+ );}console.log(JSON.stringify(await op.status()));} finally {diff --git a/test/postgres-items-bulk-catchup.test.ts b/test/postgres-items-bulk-catchup.test.tsnew file mode 100644index 000000000..86eda6d9e--- /dev/null+++ b/test/postgres-items-bulk-catchup.test.ts@@ -0,0 +1,129 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import pg from "pg";+import { applyPgMigrations, registeredPgMigrations } from "../src/persistence/pg-pool.ts";+import { createPostgresSessionStore } from "../src/sessions/postgres-session-store.ts";+import { createPostgresDirectoryStore } from "../src/directory/postgres-directory-store.ts";+import { ItemsCopyOperator, catchupBulk } from "../scripts/ops/items-copy.ts";++const base = process.env.DATABASE_URL;+const skip = !base;++async function fixture(fn: (client: pg.Client, url: string, op: ItemsCopyOperator) => Promise<void>) {+ const admin = new pg.Client({ connectionString: base });+ await admin.connect();+ const name = `bulkcatch_${randomUUID().replaceAll("-", "")}`;+ const target = new URL(base!);+ target.pathname = `/${name}`;+ await admin.query(`CREATE DATABASE ${name}`);+ const client = new pg.Client({ connectionString: target.toString() });+ const pool = new pg.Pool({ connectionString: target.toString() });+ await client.connect();+ try {+ createPostgresSessionStore(target.toString());+ createPostgresDirectoryStore(target.toString());+ await applyPgMigrations(+ pool,+ registeredPgMigrations(target.toString()).filter(+ (m) => m.id !== "sessions/store/0035-items" && m.id !== "sessions/store/0036-items-cutover",+ ),+ );+ const op = new ItemsCopyOperator(client, 2);+ await op.prepare();+ await client.query(`INSERT INTO sessions(id,type,scope_id,thread_ref,created_at)+ SELECT 's'||i,'dm','personal:alice','web:s'||i,1 FROM generate_series(0,31) i`);+ await client.query(`INSERT INTO session_entries(session_id,seq,type,payload,scope_label,created_at)+ SELECT 's'||i,j,'user',json_build_object('text','old-'||j)::text,'personal:alice',1700000000000+j+ FROM generate_series(0,31) i CROSS JOIN generate_series(0,6) j`);+ await op.split(1);+ while (await op.copyBatch()) continue;+ await op.completeCopy();+ await client.query("DELETE FROM items_copy_ops.dirty");+ await fn(client, target.toString(), op);+ } finally {+ await client.end();+ await pool.end();+ await admin.query(`DROP DATABASE ${name} WITH (FORCE)`);+ await admin.end();+ }+}++const count = async (client: pg.Client, sql: string) => (await client.query(sql)).rows[0].n as number;++for (const [batch, workers] of [+ [3, 1],+ [5, 3],+ [2000, 2],+] as const)+ test(+ `bulk catchup reconciles edits, deletes, new rows and empty sessions (batch ${batch}, ${workers} workers)`,+ { skip },+ async () => {+ await fixture(async (client, url, op) => {+ await client.query(`UPDATE session_entries SET payload='{"text":"changed"}' WHERE seq=0`);+ await client.query(`DELETE FROM session_entries WHERE seq=2`);+ await client.query(`DELETE FROM session_entries WHERE session_id='s5'`);+ await client.query(`INSERT INTO session_entries(session_id,seq,type,payload,scope_label,created_at)+ SELECT id,7,'assistant','{"text":"new"}','personal:alice',1700000000007 FROM sessions WHERE id<>'s5'`);+ await client.query(`UPDATE items_copy_ops.dirty SET copy_version=version,cursor_seq=3 WHERE session_id='s7'`);+ await catchupBulk(url, batch, workers, () => {});+ assert.equal(await count(client, "SELECT count(*)::int AS n FROM items_copy_ops.dirty"), 0);+ assert.equal(await count(client, "SELECT count(*)::int AS n FROM items WHERE seq=2"), 0);+ assert.equal(await count(client, "SELECT count(*)::int AS n FROM items WHERE session_id='s5'"), 0);+ assert.equal(await count(client, "SELECT count(*)::int AS n FROM items WHERE text='changed'"), 31);+ assert.equal(await count(client, "SELECT count(*)::int AS n FROM items WHERE text='new'"), 31);+ await op.verify();+ });+ },+ );++test("a session written during the pass stays queued with a reset cursor", { skip }, async () => {+ await fixture(async (client, url) => {+ await client.query(`UPDATE session_entries SET payload='{"text":"changed"}' WHERE seq=0`);+ class Racing extends ItemsCopyOperator {+ raced = false;+ override async replaceSelected() {+ const ids = (await this.client.query("SELECT DISTINCT session_id FROM pg_temp.items_copy_batch")).rows.map(+ (r) => r.session_id,+ );+ if (!this.raced && ids.includes("s3")) {+ this.raced = true;+ const other = new pg.Client({ connectionString: url });+ await other.connect();+ await other.query(`INSERT INTO session_entries(session_id,seq,type,payload,scope_label,created_at)+ VALUES('s3',9,'assistant','{"text":"late"}','personal:alice',1700000000009)`);+ await other.end();+ }+ return super.replaceSelected();+ }+ }+ const c = new pg.Client({ connectionString: url });+ await c.connect();+ const op = new Racing(c, 4);+ await op.snapshotDirty();+ let cursor: { session: string; seq: number } | null = { session: "", seq: -1 };+ while (cursor) cursor = (await op.bulkCatchupBatch(cursor)).next;+ await c.end();+ const left = (await client.query("SELECT session_id,copy_version,cursor_seq FROM items_copy_ops.dirty")).rows;+ assert.deepEqual(left, [{ session_id: "s3", copy_version: null, cursor_seq: null }]);+ assert.equal(await count(client, "SELECT count(*)::int AS n FROM items WHERE text='changed'"), 32);+ });+});++test("finish drains queued sessions in bulk after an operator marks the copy verified", { skip }, async () => {+ await fixture(async (client, _url, op) => {+ await client.query(`UPDATE session_entries SET payload='{"text":"changed"}' WHERE seq=0`);+ await client.query(`DELETE FROM session_entries WHERE seq=2`);+ await client.query(`INSERT INTO session_entries(session_id,seq,type,payload,scope_label,created_at)+ SELECT id,7,'assistant','{"text":"new"}','personal:alice',1700000000007 FROM sessions`);+ await op.indexes();+ await client.query("UPDATE items_copy_ops.state SET phase='verified',updated_at=now() WHERE phase='catchup'");+ await op.finish(true);+ assert.equal(await count(client, "SELECT count(*)::int AS n FROM items_copy_ops.dirty"), 0);+ assert.equal(await count(client, "SELECT count(*)::int AS n FROM items WHERE seq=2"), 0);+ assert.equal(await count(client, "SELECT count(*)::int AS n FROM items WHERE text='changed'"), 32);+ assert.equal(await count(client, "SELECT count(*)::int AS n FROM items WHERE text='new'"), 32);+ assert.equal((await client.query("SELECT phase FROM items_copy_ops.state")).rows[0].phase, "ready");+ });+});diff --git a/test/postgres-items-parallel-catchup.test.ts b/test/postgres-items-parallel-catchup.test.tsnew file mode 100644index 000000000..9b7f51c8b--- /dev/null+++ b/test/postgres-items-parallel-catchup.test.ts@@ -0,0 +1,175 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import pg from "pg";+import { applyPgMigrations, registeredPgMigrations } from "../src/persistence/pg-pool.ts";+import { createPostgresSessionStore } from "../src/sessions/postgres-session-store.ts";+import { createPostgresDirectoryStore } from "../src/directory/postgres-directory-store.ts";+import { ItemsCopyOperator, catchupParallel } from "../scripts/ops/items-copy.ts";++const base = process.env.DATABASE_URL;+const skip = !base;++async function fixture(fn: (client: pg.Client, url: string, op: ItemsCopyOperator) => Promise<void>) {+ const admin = new pg.Client({ connectionString: base });+ await admin.connect();+ const name = `parallel_${randomUUID().replaceAll("-", "")}`;+ const target = new URL(base!);+ target.pathname = `/${name}`;+ await admin.query(`CREATE DATABASE ${name}`);+ const client = new pg.Client({ connectionString: target.toString() });+ const pool = new pg.Pool({ connectionString: target.toString() });+ await client.connect();+ try {+ createPostgresSessionStore(target.toString());+ createPostgresDirectoryStore(target.toString());+ await applyPgMigrations(+ pool,+ registeredPgMigrations(target.toString()).filter(+ (m) => m.id !== "sessions/store/0035-items" && m.id !== "sessions/store/0036-items-cutover",+ ),+ );+ const op = new ItemsCopyOperator(client, 2);+ await op.prepare();+ await client.query(`INSERT INTO sessions(id,type,scope_id,thread_ref,created_at)+ SELECT 's'||i,'dm','personal:alice','web:s'||i,1 FROM generate_series(0,31) i`);+ await client.query(`INSERT INTO session_entries(session_id,seq,type,payload,scope_label,created_at)+ SELECT 's'||i,j,'user',json_build_object('text','old-'||j)::text,'personal:alice',1700000000000+j+ FROM generate_series(0,31) i CROSS JOIN generate_series(0,6) j`);+ await op.split(1);+ while (await op.copyBatch()) continue;+ await op.completeCopy();+ await catchupParallel(target.toString(), 20, 4, () => {});+ await fn(client, target.toString(), op);+ } finally {+ await client.end();+ await pool.end();+ await admin.query(`DROP DATABASE ${name} WITH (FORCE)`);+ await admin.end();+ }+}++test("parallel catchup reconciles edits, deletes, new rows, and passes full verification", { skip }, async () => {+ await fixture(async (client, url, op) => {+ await client.query(`UPDATE session_entries SET payload='{"text":"changed"}' WHERE seq=0`);+ await client.query(`DELETE FROM session_entries WHERE seq=2`);+ await client.query(`INSERT INTO session_entries(session_id,seq,type,payload,scope_label,created_at)+ SELECT id,7,'assistant','{"text":"new"}','personal:alice',1700000000007 FROM sessions`);+ await catchupParallel(url, 2, 4, () => {});+ assert.equal((await client.query("SELECT count(*)::int AS n FROM items_copy_ops.dirty")).rows[0].n, 0);+ assert.equal((await client.query("SELECT count(*)::int AS n FROM items WHERE seq=2")).rows[0].n, 0);+ assert.equal((await client.query("SELECT count(*)::int AS n FROM items WHERE text='changed'")).rows[0].n, 32);+ assert.equal((await client.query("SELECT count(*)::int AS n FROM items WHERE text='new'")).rows[0].n, 32);+ await op.verify();+ });+});++test("distinct partitions enter copy concurrently without claiming the same session", { skip }, async () => {+ await fixture(async (client, url) => {+ await client.query("UPDATE session_entries SET payload=payload WHERE seq=0");+ const seen = new Set<string>();+ let entered = 0;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let allEntered!: () => void;+ const ready = new Promise<void>((resolve) => {+ allEntered = resolve;+ });+ class Gated extends ItemsCopyOperator {+ override async replaceSelected() {+ const id = (await this.client.query("SELECT DISTINCT session_id FROM pg_temp.items_copy_batch")).rows[0]+ .session_id;+ assert.ok(!seen.has(id));+ seen.add(id);+ if (++entered === 4) allEntered();+ await gate;+ return super.replaceSelected();+ }+ }+ const clients = Array.from({ length: 4 }, () => new pg.Client({ connectionString: url }));+ await Promise.all(clients.map((c) => c.connect()));+ const pending = clients.map((c, i) => new Gated(c, 2).catchupBatch(i, 4));+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ ready,+ new Promise((_, reject) => {+ timer = setTimeout(() => reject(Error("workers did not overlap")), 1500);+ }),+ ]);+ assert.equal(entered, 4);+ } finally {+ clearTimeout(timer);+ release();+ await Promise.allSettled(pending);+ await Promise.all(clients.map((c) => c.end()));+ }+ assert.ok((await Promise.all(pending)).every((n) => n === 2));+ });+});++test("saved cursors resume and an edit behind the cursor triggers another complete pass", { skip }, async () => {+ await fixture(async (client, url, op) => {+ await client.query("UPDATE session_entries SET payload=payload WHERE session_id='s0' AND seq=0");+ await op.catchupBatch();+ const before = (+ await client.query("SELECT cursor_seq,copy_version,version FROM items_copy_ops.dirty WHERE session_id='s0'")+ ).rows[0];+ assert.equal(before.cursor_seq, 1);+ await client.query(+ `UPDATE session_entries SET payload='{"text":"changed-behind-cursor"}' WHERE session_id='s0' AND seq=0`,+ );+ await catchupParallel(url, 2, 4, () => {});+ assert.equal(+ (await client.query("SELECT text FROM items WHERE session_id='s0' AND seq=0")).rows[0].text,+ "changed-behind-cursor",+ );+ await op.verify();+ });+});++test("aborted parallel work preserves the queue and invalid worker counts are rejected", { skip }, async () => {+ await fixture(async (client, url, op) => {+ await client.query("UPDATE session_entries SET payload=payload WHERE seq=0");+ for (const count of [0, -1, 33, 1.5, NaN])+ await assert.rejects(+ catchupParallel(url, 2, count, () => {}),+ /workers must/,+ );+ await assert.rejects(catchupParallel(url, 2, 4, () => {}, AbortSignal.abort()));+ assert.equal((await client.query("SELECT count(*)::int AS n FROM items_copy_ops.dirty")).rows[0].n, 32);+ await catchupParallel(url, 2, 4, () => {});+ await op.verify();+ });+});++test("worker failures close all worker connections and retain retryable queue state", { skip }, async () => {+ await fixture(async (client, url, op) => {+ await client.query(+ `UPDATE session_entries SET type='system',payload='{"kind":"not-real"}' WHERE session_id='s0' AND seq=0`,+ );+ await assert.rejects(+ catchupParallel(url, 2, 4, () => {}),+ /unmapped system entry/,+ );+ assert.equal(+ (+ await client.query(+ "SELECT count(*)::int AS n FROM pg_stat_activity WHERE datname=current_database() AND application_name='qm-items-copy'",+ )+ ).rows[0].n,+ 0,+ );+ assert.equal(+ (await client.query("SELECT count(*)::int AS n FROM items_copy_ops.dirty WHERE session_id='s0'")).rows[0].n,+ 1,+ );+ await client.query(+ `UPDATE session_entries SET type='user',payload='{"text":"repaired"}' WHERE session_id='s0' AND seq=0`,+ );+ await catchupParallel(url, 2, 4, () => {});+ await op.verify();+ });+});diff --git a/test/postgres-items-promotion.test.ts b/test/postgres-items-promotion.test.tsindex a2d047bdc..d3779a838 100644--- a/test/postgres-items-promotion.test.ts+++ b/test/postgres-items-promotion.test.ts@@ -41,6 +41,11 @@ test("staged core stays on the verified copy until authenticated promotion complawait op.verify();await assert.rejects(createItemsPromotion(url!), /indexes ready/);await op.indexes();+ await pool.query(+ "INSERT INTO session_entries(session_id,seq,type,payload,scope_label,created_at) VALUES($1,1,'assistant','{\"text\":\"queued\"}','personal:alice',2)",+ [id],+ );+ assert.equal((await pool.query("SELECT count(*)::int AS n FROM items_copy_ops.dirty")).rows[0].n, 1);const stageUrl = new URL(url!);stageUrl.searchParams.set("application_name", "staged-promotion-test");staged = createPostgresSessionStore(stageUrl.toString(), { stageItemsCutover: true });@@ -88,7 +93,7 @@ test("staged core stays on the verified copy until authenticated promotion complawait staged.releaseLease(lease);assert.deepEqual((await pool.query("SELECT text FROM items ORDER BY seq")).rows.map((r) => r.text),- ["before", "after"],+ ["before", "queued", "after"],);await applyPgMigrations(pool, migrations);await pool.query("UPDATE qm_schema_migrations SET checksum='invalid' WHERE id=$1", [ITEMS_CUTOVER_ID]);