Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync: waive runs of no-op entries in one transaction (#5984 Phase 3)

garrytana727599a74ca
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index 899a039c60..1c8444a94b 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -14,7 +14,7 @@ import type { WriteRequest } from './model.ts';
export type PublicationBoundary = Parameters<NonNullable<PublicationHooks['boundary']>>[0];
export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid`
- | 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'consumer:prepared';
+ | 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:mid_waiver_run' | 'consumer:prepared';
export interface FaultDetail { requestId?: string; effectId?: string | number; sourceId?: string; operation?: string | null }
type FaultHook = (point: FaultPoint, detail: FaultDetail) => Promise<void> | void;
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 7c605881ba..3be5a5c91c 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -197,6 +197,14 @@ export async function clearGitHold(tx: Exec, input: { sourceId: string; incarnat
return true;
}
+/** #5984: which of these paths have a hold row (one indexed read), so a batched waiver run clears only those. */
+export async function heldGitPaths(tx: Exec, sourceId: string, incarnation: string, paths: readonly string[]): Promise<Set<string>> {
+ if (!paths.length) return new Set();
+ const byPrint = new Map(paths.map(path => [gitHoldFingerprint(sourceId, incarnation, path), path]));
+ const rows = await tx.executeRaw<{ fingerprint: string }>('SELECT fingerprint FROM op_checkpoints WHERE op=$1 AND fingerprint=ANY($2::text[])', [GIT_HOLD_OP, [...byPrint.keys()]]);
+ return new Set(rows.map(row => byPrint.get(row.fingerprint)!));
+}
+
export async function readGitHold(engine: Exec, sourceId: string, incarnation: string, path: string): Promise<GitHoldRecord | null> {
return readRow(engine, sourceId, incarnation, path);
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 4bc7b5bfb0..940e9a1246 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -17,7 +17,7 @@ import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-or
import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';
import { screeningRequest } from './noop-kernel.ts';
-import { waiveNoopEntry, type NoopWaiver } from './sync-waivers.ts';
+import { noopWaiversEnabled, screenWaiver, waiveNoopEntry, waiveNoopRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';
import { resolve } from 'node:path';
import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';
import { readCommittedBlob } from '../company-brain/revision.ts';
@@ -42,7 +42,7 @@ import { faultPoint } from './fault-points.ts';
import { withCoordinatedWrite } from './context.ts';
import { principalAttribution } from './attribution.ts';
import { recordSyncRunTrend } from '../fence-repair/census-store.ts';
-import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, fencesNormalizedReport, readSyncHoldPolicy, recordSyncConversion, recoveredReport, writeGitHold, type FencesTally } from './sync-holds.ts';
+import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, readSyncHoldPolicy, recordSyncConversion, recoveredReport, writeGitHold, type FencesTally } from './sync-holds.ts';
export interface ManagedSyncWriteDiagnostic {
source_id: string;
@@ -534,6 +534,51 @@ interface BulkPass { settings: BulkSettings; perMemberMs: number | null;
const FOREGROUND_RECENT_MS = 60_000;
type FreezeAt = (base: Cursor) => (index: number) => Promise<Pending | null>;
+/** The most consecutive no-op entries one waiver transaction passes. */
+const WAIVER_RUN_MAX = 64;
+/**
+ * #5984 Phase 3: when the frozen head would be waived, freezes and screens the entries after it four at a time
+ * (stopping at the first that would not be waived, is held, is overtaken, refuses to freeze, or at the checkpoint)
+ * and waives the run in one transaction, without a `pending` cursor save per entry. Returns null to take the
+ * per-entry path for the head (its screen admits it, or the run's transaction validated nothing or timed out);
+ * otherwise the cursor past the waived prefix (or as another run moved it), with the entry that ended the prefix
+ * saved as pending.
+ */
+async function waiveRun(engine: BrainEngine, cursor: Cursor, head: Pending, key: string, config: GBrainConfig, assertActive: () => void,
+ frozenRun: Parameters<typeof freezeEntry>[4], drainStartedAt: number, limit: number, onProgress: SyncOpts['onProgress']): Promise<Cursor | null> {
+ const first = await screenWaiver(engine, cursor, head, config);
+ if (!first) return null;
+ assertActive();
+ const run: WaiverRunEntry[] = [{ pending: head, waived: first }];
+ const max = Math.max(1, Math.min(WAIVER_RUN_MAX, limit));
+ extend: for (let next = cursor.index + 1; run.length < max && next < cursor.entries.length;) {
+ const batch = Array.from({ length: Math.min(4, max - run.length, cursor.entries.length - next) }, (_, i) => next + i);
+ const frozen = await Promise.all(batch.map(index => freezeEntry(engine, { ...cursor, index }, key, assertActive, frozenRun).catch(() => null)));
+ const screened = await Promise.all(frozen.map((entry, i) => entry && !('hold' in entry) && !entry.rebound
+ ? screenWaiver(engine, { ...cursor, index: batch[i]! }, entry, config).catch(() => null) : null));
+ for (const [i, waived] of screened.entries()) {
+ if (!waived) break extend;
+ run.push({ pending: frozen[i] as Pending, waived });
+ }
+ next += batch.length;
+ }
+ assertActive();
+ const observedAt = frozenRun.observedAt ?? new Date().toISOString();
+ const done = await waiveNoopRun(engine, cursor, run, key, async (tx, prefix) => {
+ let next: Cursor = cursor;
+ for (const { waived } of prefix) next = waivedCursor(next, waived);
+ const paths = prefix.map(({ pending }) => pending.intent.path).filter((path): path is string => typeof path === 'string');
+ return writeCursor(tx, key, cursor, { ...next, progress: stampProgress(cursor.progress, cursor.index, cursor.index + prefix.length, drainStartedAt) }, async inner => {
+ for (const path of await heldGitPaths(inner, cursor.sourceId, cursor.incarnation, paths)) await holdClear(cursor, path, observedAt)!(inner);
+ });
+ }, tx => currentCursor(tx, key, cursor));
+ if (!done) return null;
+ for (let index = cursor.index + 1; index <= cursor.index + done.waived; index++) onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: index, total: cursor.entries.length, waived: true });
+ assertActive();
+ return done.next && done.cursor.index === cursor.index + done.waived
+ ? saveCursor(engine, key, done.cursor, { ...done.cursor, pending: done.next as Pending }, false, assertActive) : done.cursor;
+}
+
/** #5984 bulk: freezes the followers of an eligible head and records them with it as the cursor's group. */
async function formGroup(engine: BrainEngine, head: Cursor, pending: Pending, key: string, bulk: BulkPass, config: GBrainConfig, freezeAt: FreezeAt,
assertActive: () => void): Promise<Cursor> {
@@ -868,6 +913,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
let creditedPages = 0, creditStarted = 0, foregroundQueued = false;
const sliceStarted = performance.now(), sliceFirstIndex = cursor.index, drainStartedAt = opts.drainStartedAt ?? Date.now();
const bulk: BulkPass = { settings: opts.bulk && !company ? opts.bulk : { enabled: false, reason: null, size: 1, maxTxnMs: 0 }, perMemberMs: null };
+ const waiveBatch = noopWaiversEnabled() && await waiverBatchEnabled(engine);
opts.onProgress?.({ phase: 'managed_sync.start', bankedFiles: cursor.index, total: cursor.entries.length });
while (!cursor.done) {
assertActive();
@@ -901,6 +947,10 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
continue;
}
+ const waived: Cursor | null = waiveBatch && !frozen.rebound ? await waiveRun(engine, cursor, frozen, key, config, assertActive, frozenRun, drainStartedAt,
+ slice ? slice.maxPages - (cursor.index - sliceFirstIndex) : WAIVER_RUN_MAX, opts.onProgress) : null;
+ if (waived && slice && (waived.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(waived, 'partial', 'writer_yield');
+ if (waived) { cursor = waived; continue; }
cursor = await saveCursor(engine, key, cursor, { ...cursor, ...(frozen.rebound ? { overtaken: true as const } : {}), pending: frozen }, false, assertActive);
}
if (!cursor.pending) continue; // another owner-loop advanced the cursor
diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.ts
index 2519f95a53..6e00186386 100644
--- a/src/core/persistence/sync-waivers.ts
+++ b/src/core/persistence/sync-waivers.ts
@@ -13,6 +13,9 @@ import { inspectUnchanged, screeningRequest, type NoopKernelWaiver } from './noo
import { validateSyncAuthority, type SyncAuthority } from './sync-authority.ts';
import { readSyncFile } from './sync-discovery.ts';
import { assertSyncPageOrigin, syncOriginScope } from './sync-origin.ts';
+import { faultPoint } from './fault-points.ts';
+import { pipelined } from '../page-state/transactions.ts';
+import { REVISION_BACKFILL_PENDING } from '../page-state/types.ts';
export interface WaiverCursor { sourceId: string; incarnation: string; root: string; gitRoot: string; slugMode: 'git-root' | 'source-root';
binding: { worktree_id: string }; authority: SyncAuthority; runId: string; index: number }
@@ -42,21 +45,9 @@ export const UNFINISHED_PAGE_REQUEST_SQL = `SELECT 1 FROM (
*/
export async function waiveNoopEntry<C extends WaiverCursor>(engine: BrainEngine, cursor: C, pending: WaiverEntry, config: GBrainConfig, key: string,
advance: (tx: BrainEngine, waived: NoopWaiver) => Promise<C>, reread: (tx: BrainEngine) => Promise<C>): Promise<C | null> {
- if (!noopWaiversEnabled() || pending.pageId === null) return null;
+ const waived = await screenWaiver(engine, cursor, pending, config);
+ if (!waived) return null;
const intent = pending.intent;
- let waived: NoopWaiver;
- if (intent.kind === 'managed_sync_delete') {
- if (intent.unownedDeletion || intent.renameFrom || intent.rawHash !== null || typeof intent.path !== 'string' || typeof intent.sourcePath !== 'string') return null;
- const snapshot = await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
- if (!softDeletedAt(snapshot, pending)) return null;
- await validateSyncAuthority(engine, cursor.authority, pending.slug);
- waived = { kind: 'delete', kernel: [] };
- } else {
- const kernel = await unchangedSyncImport(engine, cursor, pending, config);
- if (!kernel) return null;
- await validateSyncAuthority(engine, cursor.authority, pending.slug);
- waived = { kind: 'import', kernel };
- }
return engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId: cursor.sourceId, slug: pending.slug }]);
const [held] = await tx.executeRaw<{ run_id: string | null; index: number | string | null; request_id: string | null }>(`SELECT completed_keys->0->>'runId' AS run_id,
@@ -74,6 +65,87 @@ export async function waiveNoopEntry<C extends WaiverCursor>(engine: BrainEngine
});
}
+/**
+ * The screen half of a waiver, before its transaction: whether this frozen,
+ * unadmitted entry's publication would change nothing (a delete of a page
+ * already soft-deleted at its frozen revision, or an unchanged import). A
+ * revoked sync authority throws.
+ */
+export async function screenWaiver(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig): Promise<NoopWaiver | null> {
+ if (!noopWaiversEnabled() || pending.pageId === null) return null;
+ const intent = pending.intent;
+ if (intent.kind === 'managed_sync_delete') {
+ if (intent.unownedDeletion || intent.renameFrom || intent.rawHash !== null || typeof intent.path !== 'string' || typeof intent.sourcePath !== 'string') return null;
+ const snapshot = await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
+ if (!softDeletedAt(snapshot, pending)) return null;
+ await validateSyncAuthority(engine, cursor.authority, pending.slug);
+ return { kind: 'delete', kernel: [] };
+ }
+ const kernel = await unchangedSyncImport(engine, cursor, pending, config);
+ if (!kernel) return null;
+ await validateSyncAuthority(engine, cursor.authority, pending.slug);
+ return { kind: 'import', kernel };
+}
+
+/** #5984: `GBRAIN_SYNC_WAIVE_BATCH=0` (or `sync.waive_batch=false`) waives one entry per transaction, as before. */
+export async function waiverBatchEnabled(engine: BrainEngine, env: NodeJS.ProcessEnv = process.env): Promise<boolean> {
+ const value = env.GBRAIN_SYNC_WAIVE_BATCH ?? await engine.getConfig('sync.waive_batch').catch(() => null);
+ return !(value === '0' || value === 'false');
+}
+export interface WaiverRunEntry { pending: WaiverEntry; waived: NoopWaiver }
+/**
+ * #5984 Phase 3: commits a run of consecutive screened waivers at the cursor
+ * head in one transaction. It takes every page guard (in the engine's key
+ * order) and then the cursor row, which must still be at the run's first entry
+ * with nothing pending; it re-validates each entry inside the transaction
+ * (page identity, revision and deleted state, file absence and origin for a
+ * delete, no unfinished request for the page) and advances only past the
+ * contiguous validated prefix. Returns null when not even the first entry
+ * holds, or on a lock or statement timeout, so the caller takes the per-entry
+ * path; `next` is the frozen entry that stopped the prefix, for that path to
+ * screen again without re-freezing; `reread` answers when another run moved
+ * the cursor.
+ */
+export async function waiveNoopRun<C extends WaiverCursor>(engine: BrainEngine, cursor: C, run: readonly WaiverRunEntry[], key: string,
+ advance: (tx: BrainEngine, prefix: readonly WaiverRunEntry[]) => Promise<C>, reread: (tx: BrainEngine) => Promise<C>): Promise<{ cursor: C; waived: number; next?: WaiverEntry } | null> {
+ if (!run.length) return null;
+ try {
+ return await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('lock_timeout','2s',true),set_config('statement_timeout','10s',true)");
+ await tx.lockPageKeys(run.map(entry => ({ sourceId: cursor.sourceId, slug: entry.pending.slug })));
+ const [held] = await tx.executeRaw<{ run_id: string | null; index: number | string | null; request_id: string | null }>(`SELECT completed_keys->0->>'runId' AS run_id,
+ completed_keys->0->'index' AS index,completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE`, [key]);
+ if (held?.run_id !== cursor.runId || Number(held.index) !== cursor.index || held.request_id != null) return { cursor: await reread(tx), waived: 0 };
+ await faultPoint('sync:mid_waiver_run', { sourceId: cursor.sourceId });
+ const pages = await tx.executeRaw<{ id: number | string; slug: string; deleted: boolean; knowledge_revision: string | number | null }>(
+ 'SELECT id,slug,deleted_at IS NOT NULL AS deleted,knowledge_revision FROM pages WHERE source_id=$1 AND slug=ANY($2::text[])', [cursor.sourceId, run.map(entry => entry.pending.slug)]);
+ const bySlug = new Map(pages.map(page => [page.slug, page]));
+ const scope = syncOriginScope(cursor);
+ const checks = await pipelined(tx, run.flatMap(({ pending, waived }) => [
+ () => tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, [cursor.binding.worktree_id, cursor.incarnation, cursor.sourceId, pending.slug, pending.pageId, String(pending.pageId)]),
+ () => waived.kind === 'delete'
+ ? assertSyncPageOrigin(tx, cursor.sourceId, pending.intent.sourcePath!, pending.pageId, true, scope).then(() => true, () => false)
+ : Promise.resolve(true),
+ ])) as Array<unknown[] | boolean>;
+ let valid = 0;
+ for (const [i, { pending, waived }] of run.entries()) {
+ const page = bySlug.get(pending.slug);
+ const revision = page ? page.knowledge_revision == null ? REVISION_BACKFILL_PENDING : String(page.knowledge_revision) : null;
+ if (!page || Number(page.id) !== pending.pageId || revision !== pending.intent.expected_revision) break;
+ if (waived.kind === 'delete' ? !page.deleted || readSyncFile(cursor.root, pending.intent.path!) !== null : page.deleted) break;
+ if ((checks[2 * i] as unknown[]).length || checks[2 * i + 1] !== true) break;
+ valid++;
+ }
+ if (!valid) return null;
+ return { cursor: await advance(tx, run.slice(0, valid)), waived: valid, ...(valid < run.length ? { next: run[valid]!.pending } : {}) };
+ });
+ } catch (error) {
+ const code = (error as { code?: unknown } | null)?.code;
+ if (code === '55P03' || code === '57014') return null;
+ throw error;
+ }
+}
+
/** #5984: whether `waiveNoopEntry` would waive this frozen entry now (read-only; the bulk group stops before such an entry). */
export async function wouldWaiveEntry(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig): Promise<boolean> {
if (!noopWaiversEnabled() || pending.pageId === null) return false;
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index c3357e15d5..6a90cc7ed8 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -21,6 +21,7 @@ import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { disposePersistenceConsumer, registerMutationPreparer } from '../src/core/persistence/service.ts';
import { UNFINISHED_PAGE_REQUEST_SQL, noopWaiversEnabled } from '../src/core/persistence/sync-waivers.ts';
import { waitFor } from './helpers/wait-for.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
import { withEnv } from './helpers/with-env.ts';
import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
@@ -768,7 +769,8 @@ test('revoked sync authority refuses before any waiver or cursor advance', async
expect(await deleteRequests(engine, f.id)).toHaveLength(0);
const [cursor] = await engine.executeRaw<{ completed_keys: [{ index: number; pending?: { slug: string }; counts: { waived?: unknown } }] }>(
"SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->'authority'->'writer'->>'remote'='true'", [f.id]);
- expect(cursor.completed_keys[0]).toMatchObject({ index: 0, pending: { slug: 'a' } });
+ expect(cursor.completed_keys[0]).toMatchObject({ index: 0 });
+ expect(cursor.completed_keys[0].pending).toBeUndefined();
expect(cursor.completed_keys[0].counts.waived).toBeUndefined();
expect((await engine.readPageSnapshot('a', { sourceId: f.id, includeDeleted: true }))!.revision).toBe(before);
} finally { await disposePersistenceConsumer(proxy); }
@@ -789,6 +791,74 @@ test('a waiver that loses the cursor to another drain adopts the winner without
}
}), 120_000);
+/** Counts top-level transactions: a waived entry costs two (a pending save and its waiver) on the per-entry path. */
+function countTransactions(engine: BrainEngine): { engine: BrainEngine; count: () => number } {
+ let count = 0;
+ return { count: () => count, engine: new Proxy(engine, { get(target, key) {
+ if (key === 'transaction') return (fn: (tx: BrainEngine) => Promise<unknown>) => { count++; return target.transaction(fn); };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } }) };
+}
+const manyNotes = (n: number) => Object.fromEntries(Array.from({ length: n }, (_, i) => [`n${String(i).padStart(2, '0')}.md`, note(`Note ${i}`)]));
+const manySlugs = (n: number) => Array.from({ length: n }, (_, i) => `n${String(i).padStart(2, '0')}`);
+
+test('a run of no-op deletes is waived in one transaction, and GBRAIN_SYNC_WAIVE_BATCH=0 waives them one at a time', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ for (const batch of ['1', '0']) await withEnv({ GBRAIN_SYNC_WAIVE_BATCH: batch }, async () => {
+ const f = await deletedFixture(engine, manyNotes(10), manySlugs(10));
+ const counted = countTransactions(engine);
+ const waived: number[] = [];
+ try {
+ const result = await performManagedSync(counted.engine, { sourceId: f.id, ...WAIVER_OPTS,
+ onProgress: event => { if (event.phase === 'managed_sync.page_committed' && event.waived) waived.push(event.bankedFiles!); } });
+ expect(result).toMatchObject({ status: 'synced', deleted: 0, waived: { imports: 0, deletes: 10 } });
+ expect(waived).toEqual(Array.from({ length: 10 }, (_, i) => i + 1));
+ expect((await runRequests(engine, f.id, result.runId!)).map(row => row.kind)).toEqual(['managed_sync_checkpoint']);
+ if (batch === '1') expect(counted.count()).toBeLessThan(8);
+ else expect(counted.count()).toBeGreaterThanOrEqual(20);
+ } finally { await disposePersistenceConsumer(counted.engine); }
+ });
+ }
+}), 120_000);
+
+test('a page restored in the middle of a waiver run ends the run there: earlier entries are waived, it is admitted, and nothing after it is passed', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) {
+ const f = await deletedFixture(engine, manyNotes(8), manySlugs(8));
+ const proxy = onScreen(engine, 'n06', () => engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => { await tx.restorePage('n02', { sourceId: f.id }); }, TEST_WRITE_ATTRIBUTION)));
+ try {
+ const result = await performManagedSync(proxy, { sourceId: f.id, ...WAIVER_OPTS });
+ expect(result.waived).toEqual({ imports: 0, deletes: 2 });
+ expect((await deleteRequests(engine, f.id)).map(row => row.slug)).toEqual(['n02']);
+ expect(await engine.getPage('n02', { sourceId: f.id })).not.toBeNull();
+ const [cursor] = await engine.executeRaw<{ index: number }>("SELECT (completed_keys->0->>'index')::int AS index FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);
+ expect(cursor!.index).toBe(2);
+ } finally { await disposePersistenceConsumer(proxy); rmSync(syncFailuresPath(), { force: true }); }
+ }
+}), 120_000);
+
+test('a crash inside a waiver run skips nothing and waives nothing twice; a lock timeout falls back to one entry at a time', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ for (const fault of ['crash', 'lock_timeout'] as const) {
+ const f = await deletedFixture(engine, manyNotes(6), manySlugs(6));
+ let fired = 0;
+ installFaultHook(point => {
+ if (point !== 'sync:mid_waiver_run') return;
+ fired++;
+ if (fault === 'crash' && fired === 1) throw new Error('injected crash inside the waiver run');
+ if (fault === 'lock_timeout') throw Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' });
+ });
+ try {
+ if (fault === 'crash') await expect(performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS })).rejects.toThrow('injected crash');
+ const result = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS });
+ expect(result).toMatchObject({ status: 'synced', deleted: 0, waived: { imports: 0, deletes: 6 } });
+ expect(await deleteRequests(engine, f.id)).toHaveLength(0);
+ expect(fired).toBeGreaterThan(0);
+ } finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); }
+ }
+ }
+}), 120_000);
+
test('the waiver lookup for unfinished page requests is served by the request indexes', async () => {
for (const engine of engines) {
const plan = await engine.transaction(async tx => {