Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync: guarded no-op delete waiver and waived counters (#5984)

garrytan001e5f9d6e1f
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index e26ade76c2..0a37134286 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -15,5 +15,6 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- `src/core/persistence/connector-errors.ts` — `connector_account_changed` with its two-exit hint, the retired-intent messages, and `receiptDeliveredHint`, which rebuilds `suggestion`/`detail`/`docs` for codes delivered through a stored receipt (the coordinator persists only code and message); `writeResponse` applies it.
- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.
- `src/core/persistence/noop-kernel.ts` — the #5470 no-op kernel. `inspectUnchanged` takes a preparer's `PreparedMutation` for an unadmitted `screeningRequest` and returns `contentUnchanged`, `projectionWorkRequired` (safe-chunk fence, text projection behind the knowledge revision, embedded page without a contextual mode), `metadataWorkRequired` (source path) and `observedRevision`; bound pages also need local file bytes equal to the serialized page. Callers run the preparer's own `validate` before counting a skip. An optional `waive` list (#5751) lets a caller skip two admit reasons its no-op publication can never resolve, a pending contextual-mode stamp and file bytes that differ from the prepared content (never a missing file); the result lists each waiver applied in `waived`; only managed working-tree sync entries pass it. Used by connector sync, `import-mutations.ts`, and `sync-run.ts` (working-tree and company-profile entries; renames and overlays always admit). Tests: `test/noop-kernel-paths.test.ts`, `test/connector-wave3.test.ts`.
+- `src/core/persistence/sync-waivers.ts` — managed-sync no-op waivers (#5470, #5984). `waiveNoopEntry` screens a frozen, unadmitted entry: an unchanged import (`unchangedSyncImport`, moved here from `sync-run.ts`, with the #5751 working-tree kernel waivers) or a delete whose page is already soft-deleted at the entry's frozen `expected_revision` with its file absent (never an unowned deletion or a rename). A candidate runs `validateSyncAuthority` first (a revoked grant throws before any waiver), then commits in one transaction with a fixed lock order: page guard (`lockPageKeys`), then the managed-sync cursor row `FOR UPDATE`; it re-reads the snapshot (and, for deletes, the origin and file absence) and refuses while `UNFINISHED_PAGE_REQUEST_SQL` finds an unfinished request for the page by slug, page id or a `renameFrom` naming it. That lookup is three `LIMIT 1` branches served by `persistence_requests_pending`, `persistence_requests_recovery` and the database-only pending index (EXPLAIN pinned in `test/persistence-managed-sync.test.ts`). A cursor that moved meanwhile is adopted instead of waived again, so `waived` counts only increment in the winning transaction. `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry. Tests: `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.test.ts`.
- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget.
- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 3cfc7317ed..b804111c2f 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -16,7 +16,7 @@
- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths.
- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).
-- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.
+- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). #5984: the no-op screens live in `sync-waivers.ts` (unchanged imports and deletes of already soft-deleted pages); waived entries count under `waived: { imports, deletes }` in the cursor and `SyncResult`, never under `deleted`, while `legacySkips` keeps its #5751 kernel breakdown. The admission transaction re-reads the cursor row `FOR SHARE` after its counter locks and admits only while the cursor still holds the frozen entry. A still-unfinished wait returns the single-pass `partial/writer_pending` (or `timeout`) result plus `writeWait`: `pending`, `blocked` (a head whose `blocked_reason` is `recovery_required`, `owner_unavailable`, `unexpected_file_bytes` or `unexpected_staging_bytes`, with `gbrain sources writer status <source> --json`) or a classified `read_failed`, always with the request ID. A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.
- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index f1e9408b66..291da97cbe 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -47,7 +47,7 @@ export interface SyncResult {
*/
malformedSkipped?: number;
/** #5751: unchanged managed working-tree files skipped although a no-op publication cannot resolve their admit reason. */
- legacySkips?: { contextualMode: number; canonicalBytes: number };
+ legacySkips?: { contextualMode: number; canonicalBytes: number }; /** #5984: managed entries advanced without a write (DX-A7), and how a still-unfinished managed write's wait ended (DX-A3). */ waived?: { imports: number; deletes: number }; writeWait?: import('../core/persistence/sync-run.ts').ManagedSyncWriteWait;
/** Managed sync: files skipped because another origin keeps their slug, and links derived after the checkpoint. */
slugCollisions?: import('../core/persistence/sync-discovery.ts').SyncSlugCollision[];
fileRefusals?: import('../core/persistence/sync-discovery.ts').SyncFileRefusal[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction;
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 652047051f..bd01bfb039 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -8,14 +8,14 @@ import { throwIfAborted } from '../abort-check.ts';
import { digest, sha256 } from './digest.ts';
import { getWriteRequest, admitWriteInTransaction, receiptFor } from './journal.ts';
import { retryWriteAdmission } from './admission-retry.ts';
-import { assertPersistenceAccepting, foregroundWriteCompletions, startPersistenceConsumer, waitForWrite } from './service.ts';
+import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer, type WriteWait } from './service.ts';
import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncContent, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.ts';
import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';
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 { inspectUnchanged, screeningRequest, type NoopKernelWaiver } from './noop-kernel.ts';
-import type { GBrainConfig } from '../config.ts';
-import { join, resolve } from 'node:path';
+import { screeningRequest } from './noop-kernel.ts';
+import { waiveNoopEntry, type NoopWaiver } 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';
import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
@@ -48,7 +48,9 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authority
processingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions; overtaken?: true;
counts: { added: number; modified: number; deleted: number; chunks: number; renamed?: number;
/** #5751: unchanged working-tree files skipped only because a no-op publication could never resolve their admit reason. */
- skippedContextualMode?: number; skippedCanonicalBytes?: number }; }
+ skippedContextualMode?: number; skippedCanonicalBytes?: number;
+ /** DX-A7: entries advanced without an admission because their publication would change nothing. */
+ waived?: { imports: number; deletes: number } }; }
const OP = 'managed-sync';
type CursorHeader = Omit<Cursor, 'entries' | 'companyPlan'> & { total: number };
const header = ({ entries, companyPlan: _plan, ...value }: Cursor): CursorHeader => ({ ...value, total: entries.length });
@@ -81,20 +83,50 @@ async function saveCursor(engine: BrainEngine, key: string, before: Cursor | nul
return current;
}
}
- if (before === null) {
- await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);
- await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [OP, key, JSON.stringify([header(next)])]);
- } else {
- await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now()
- WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb`, [OP, key, JSON.stringify([header(before)]), JSON.stringify([header(next)])]);
- await tx.executeRaw('UPDATE op_checkpoints SET updated_at=now() WHERE op=$1 AND fingerprint=$2', [`${OP}-manifest`, next.runId]);
- }
- const current = await readCursor(tx, key, next);
- if (!current) throw new OperationError('storage_error', 'The durable sync cursor disappeared.');
+ const current = await writeCursor(tx, key, before, next);
assertActive?.();
return current;
});
}
+/** Compare-and-swap inside the caller's transaction; a lost swap returns the cursor that won. */
+async function writeCursor(tx: BrainEngine, key: string, before: Cursor | null, next: Cursor): Promise<Cursor> {
+ if (before === null) {
+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);
+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [OP, key, JSON.stringify([header(next)])]);
+ } else {
+ await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now()
+ WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb`, [OP, key, JSON.stringify([header(before)]), JSON.stringify([header(next)])]);
+ await tx.executeRaw('UPDATE op_checkpoints SET updated_at=now() WHERE op=$1 AND fingerprint=$2', [`${OP}-manifest`, next.runId]);
+ }
+ return currentCursor(tx, key, next);
+}
+async function currentCursor(engine: BrainEngine, key: string, cached?: Cursor): Promise<Cursor> {
+ const current = await readCursor(engine, key, cached);
+ if (!current) throw new OperationError('storage_error', 'The durable sync cursor disappeared.');
+ return current;
+}
+/** The cursor after a waived entry: counted under `waived`, plus the #5751 kernel breakdown kept for `legacySkips`. */
+function waivedCursor(cursor: Cursor, waived: NoopWaiver): Cursor {
+ const prior = cursor.counts.waived ?? { imports: 0, deletes: 0 };
+ const next: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts,
+ waived: { imports: prior.imports + (waived.kind === 'import' ? 1 : 0), deletes: prior.deletes + (waived.kind === 'delete' ? 1 : 0) } } };
+ delete next.pending;
+ if (waived.kernel.includes('contextual_mode')) next.counts.skippedContextualMode = (next.counts.skippedContextualMode ?? 0) + 1;
+ if (waived.kernel.includes('canonical_file_differs')) next.counts.skippedCanonicalBytes = (next.counts.skippedCanonicalBytes ?? 0) + 1;
+ return next;
+}
+/** The rollback signal of an admission whose cursor no longer holds the frozen entry (ENG-A7). */
+class CursorMoved extends Error {}
+/** DX-A3 / ENG-A12: how the wait for a still-unfinished sync write ended, with its request ID kept. */
+export type ManagedSyncWriteWait = { status: 'pending'; request_id: string }
+ | { status: 'blocked'; request_id: string; cause: string; command: string }
+ | { status: 'read_failed'; request_id: string; reason: string; transient: boolean; sqlstate?: string; attempts: number; message: string; remediation: string };
+function writeWaitOf(wait: WriteWait): ManagedSyncWriteWait {
+ if (wait.kind === 'blocked') return { status: 'blocked', request_id: wait.request_id, cause: wait.cause, command: wait.command };
+ if (wait.kind !== 'read_failed') return { status: 'pending', request_id: wait.row.request_id };
+ const { kind: _kind, row: _row, ...failure } = wait;
+ return { status: 'read_failed', ...failure };
+}
async function replaceCursor(engine: BrainEngine, key: string, before: CursorHeader, next: Cursor, assertActive: () => void): Promise<Cursor> {
return engine.transaction(async tx => {
assertActive();
@@ -120,6 +152,7 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], rea
deleted: cursor.counts.deleted, renamed: cursor.counts.renamed ?? 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],
...(cursor.slugCollisions?.length ? { slugCollisions: cursor.slugCollisions } : {}),
...(cursor.fileRefusals?.length ? { fileRefusals: cursor.fileRefusals } : {}),
+ waived: { imports: cursor.counts.waived?.imports ?? 0, deletes: cursor.counts.waived?.deletes ?? 0 },
filesImported: cursor.index, bankedFiles: cursor.index, ...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}),
...(cursor.counts.skippedContextualMode || cursor.counts.skippedCanonicalBytes ? { legacySkips: {
contextualMode: cursor.counts.skippedContextualMode ?? 0, canonicalBytes: cursor.counts.skippedCanonicalBytes ?? 0 } } : {}) };
@@ -128,7 +161,7 @@ function writeDiagnostic(cursor: Cursor, pending: Pending, row: WriteRequest): M
const terminal = isTerminalWriteState(row.state);
const code = terminal ? row.error_code ?? (row.state === 'cancelled' ? 'cancelled' : 'storage_error') : 'write_pending';
const blockedReason = ['writer_busy', 'writer_pool_capacity', 'owner_unavailable', 'recovery_required', 'writer_lock_unavailable',
- 'database_contention', 'consumer_stopping', 'revision_changed_repreparing'].includes(row.blocked_reason ?? '') ? row.blocked_reason! : 'write_pending';
+ 'database_contention', 'consumer_stopping', 'revision_changed_repreparing', 'unexpected_file_bytes', 'unexpected_staging_bytes'].includes(row.blocked_reason ?? '') ? row.blocked_reason! : 'write_pending';
const detail = terminal ? writeFailureDiagnostic(code, row.error_message) : {
reason: blockedReason, message: 'The write is accepted but not committed; the sync checkpoint has not advanced.',
suggestion: 'Re-run the same sync options to resume this request. Do not submit a replacement request or skip the pending write.',
@@ -424,17 +457,16 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
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
- const pending = cursor.pending;
+ const pending: Pending = cursor.pending;
phase = 'admission';
const prior = await getWriteRequest(engine, cursor.authority.writer.principal, pending.requestId);
assertActive();
- // #5470: a frozen import whose publication would change nothing advances the cursor without an admission.
- const waived = prior ? null : await unchangedSyncImport(engine, cursor, pending, config);
+ // #5470/#5984: a frozen entry whose publication would change nothing advances the cursor without an admission.
+ const screened: Cursor = cursor;
+ const waived: Cursor | null = prior ? null : await waiveNoopEntry(engine, screened, pending, config, key,
+ (tx, noop) => writeCursor(tx, key, screened, waivedCursor(screened, noop)), tx => currentCursor(tx, key, screened));
if (waived) {
- const skipped: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts } }; delete skipped.pending;
- if (waived.includes('contextual_mode')) skipped.counts.skippedContextualMode = (skipped.counts.skippedContextualMode ?? 0) + 1;
- if (waived.includes('canonical_file_differs')) skipped.counts.skippedCanonicalBytes = (skipped.counts.skippedCanonicalBytes ?? 0) + 1;
- cursor = await saveCursor(engine, key, cursor, skipped);
+ cursor = waived;
opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index });
assertActive();
// A skipped entry still counts toward the caller's slice, so a sliced run yields at the same positions.
@@ -450,18 +482,24 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
sourceId: admitting.sourceId, sourceIncarnation: admitting.incarnation, slug: pending.slug, pageId: pending.pageId,
worktreeId: admitting.binding.worktree_id, topologyGeneration: admitting.binding.topology_generation,
principal: admitting.authority.writer.principal, authority: admitting.authority.writer, callerIntent: pending.intent, intent: pending.intent });
+ // ENG-A7: after the counter locks (the publication lock order), admit only while the cursor still holds this entry.
+ const [held] = await tx.executeRaw<{ request_id: string | null }>(`SELECT completed_keys->0->'pending'->>'requestId' AS request_id
+ FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key]);
+ if (held?.request_id !== pending.requestId) throw new CursorMoved();
assertActive();
return accepted;
- }));
+ })).catch(error => { if (error instanceof CursorMoved) return null; throw error; });
+ if (!row) { cursor = await currentCursor(engine, key, cursor); continue; }
await validateSyncAuthority(engine, cursor.authority, pending.slug);
assertSyncDispatchActive();
// #5762: a checkpoint's validation runs under the coordinator's 5 s statement timeout, so its wait outlasts that
// budget; a timed-out checkpoint then reports its terminal refusal and hint in this run instead of the next.
- const done = await waitForWrite(engine, row, config, pending.intent.kind === 'managed_sync_checkpoint' ? 8000 : 5000);
+ const waited = await awaitWrite(engine, row, config, { waitMs: pending.intent.kind === 'managed_sync_checkpoint' ? 8000 : 5000 });
+ const done = waited.row;
assertSyncDispatchActive();
if (!isTerminalWriteState(done.state)) {
return { ...result(cursor, 'partial', signal?.aborted ? 'timeout' : 'writer_pending'),
- ...(authority.writer.remote ? {} : { managedWrite: writeDiagnostic(cursor, pending, done) }) };
+ ...(authority.writer.remote ? {} : { managedWrite: writeDiagnostic(cursor, pending, done), writeWait: writeWaitOf(waited) }) };
}
if (done.state !== 'committed') {
const { failure, ledgerRecorded } = await recordManagedSyncFailure(engine, { source_id: cursor.sourceId, source_incarnation: cursor.incarnation, path: pending.intent.path ?? '<checkpoint>',
@@ -532,33 +570,3 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
throw error;
}
}
-
-/**
- * #5470 no-op screen for working-tree and company-profile sync: runs the sync
- * preparer on the frozen, unadmitted entry. A rename or a canonical overlay is
- * always admitted. Returns null to admit, or the kernel waivers the skip used.
- * #5751: a managed working-tree entry waives the two admit reasons its no-op
- * publication can never resolve (a pending contextual-mode stamp, and file
- * bytes that differ from the prepared content yet parse to the same page), so
- * an unchanged legacy file stops taking a request ID on every run.
- */
-async function unchangedSyncImport(engine: BrainEngine, cursor: Cursor, pending: Pending, config: GBrainConfig): Promise<NoopKernelWaiver[] | null> {
- const intent = pending.intent;
- if (intent.kind !== 'managed_sync_import' || intent.renameFrom || pending.pageId === null || typeof intent.path !== 'string' || typeof intent.content !== 'string') return null;
- try {
- const snapshot = await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
- const row = screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: pending.slug, page_id: pending.pageId,
- worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent, request_id: pending.requestId });
- const prepared = await prepareManagedSyncMutation(engine, row, config);
- if (prepared.file || prepared.target === 'skill_bundle') return null;
- const file = { root: cursor.root, path: join(cursor.root, intent.path), content: intent.content };
- const inspected = await inspectUnchanged(engine, { prepared: { ...prepared, target: 'page', file }, snapshot, sourcePath: intent.sourcePath, databaseOnly: false,
- embeddingRequested: !prepared.deferEmbedding && !config.embedding_disabled && !!config.embedding_model?.trim(),
- waive: intent.working === true ? ['contextual_mode', 'canonical_file_differs'] : undefined });
- if (inspected.admitReason) return null;
- await prepared.validate?.(engine);
- return inspected.waived ?? [];
- } catch {
- return null;
- }
-}
diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.ts
new file mode 100644
index 0000000000..bb93f06c53
--- /dev/null
+++ b/src/core/persistence/sync-waivers.ts
@@ -0,0 +1,109 @@
+/**
+ * #5470 / #5984: no-op screens for a frozen managed-sync entry. An entry whose
+ * publication would change nothing advances the cursor without an admission.
+ * The decision commits in one transaction that takes the page guard and then the
+ * cursor row (the fixed order), re-reads the page and refuses while any
+ * unfinished request names the page, so a waiver never overtakes queued work.
+ */
+import { join } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import { prepareManagedSyncMutation, type SyncIntent } from './sync-prepare.ts';
+import { inspectUnchanged, screeningRequest, type NoopKernelWaiver } from './noop-kernel.ts';
+import { validateSyncAuthority, type SyncAuthority } from './sync-authority.ts';
+import { readSyncFile } from './sync-discovery.ts';
+import { assertSyncPageOrigin, syncOriginScope } from './sync-origin.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 }
+export interface WaiverEntry { requestId: string; slug: string; pageId: number | null; intent: SyncIntent }
+export interface NoopWaiver { kind: 'import' | 'delete'; kernel: NoopKernelWaiver[] }
+
+/** DX-A15: `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry, for triage. */
+export function noopWaiversEnabled(env: NodeJS.ProcessEnv = process.env): boolean { return env.GBRAIN_SYNC_WAIVE_NOOP !== '0'; }
+
+const PAGE_MATCH = "r.source_id=$3 AND (r.slug=$4 OR r.page_id=$5::bigint OR r.intent->'renameFrom'->>'slug'=$4 OR r.intent->'renameFrom'->>'pageId'=$6)";
+/**
+ * CEO-A12/A34: an unfinished request for the page, by slug, page id or a rename
+ * from it. Each branch matches one partial request index: worktree pending,
+ * worktree recovery, and database-only pending by source incarnation.
+ */
+export const UNFINISHED_PAGE_REQUEST_SQL = `SELECT 1 FROM (
+ (SELECT r.id FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running','recovering') AND ${PAGE_MATCH} LIMIT 1)
+ UNION ALL (SELECT r.id FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL AND ${PAGE_MATCH} LIMIT 1)
+ UNION ALL (SELECT r.id FROM persistence_requests r WHERE r.source_incarnation=$2::uuid AND r.worktree_id IS NULL
+ AND r.state IN ('queued','running','recovering') AND ${PAGE_MATCH} LIMIT 1)) unfinished LIMIT 1`;
+
+/**
+ * Screens a frozen, unadmitted entry. Returns null to admit, or the cursor that
+ * `advance` (the waiver won) or `reread` (the cursor moved meanwhile) returns
+ * inside the waiver transaction. A revoked sync authority throws before any
+ * waiver decision.
+ */
+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 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,
+ 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 !== pending.requestId) return reread(tx);
+ const snapshot = await tx.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
+ if (waived.kind === 'delete') {
+ if (!softDeletedAt(snapshot, pending) || readSyncFile(cursor.root, intent.path!) !== null) return null;
+ try { await assertSyncPageOrigin(tx, cursor.sourceId, intent.sourcePath!, pending.pageId, true, syncOriginScope(cursor)); }
+ catch { return null; }
+ } else if (snapshot?.page.id !== pending.pageId || snapshot.page.deleted_at != null || snapshot.revision !== intent.expected_revision) return null;
+ const unfinished = await tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, [cursor.binding.worktree_id, cursor.incarnation, cursor.sourceId, pending.slug, pending.pageId, String(pending.pageId)]);
+ if (unfinished.length) return null;
+ return advance(tx, waived);
+ });
+}
+
+function softDeletedAt(snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>>, pending: WaiverEntry): boolean {
+ return snapshot?.page.id === pending.pageId && snapshot.page.deleted_at != null && snapshot.revision === pending.intent.expected_revision;
+}
+
+/**
+ * #5470 no-op screen for working-tree and company-profile sync: runs the sync
+ * preparer on the frozen, unadmitted entry. A rename or a canonical overlay is
+ * always admitted. Returns null to admit, or the kernel waivers the skip used.
+ * #5751: a managed working-tree entry waives the two admit reasons its no-op
+ * publication can never resolve (a pending contextual-mode stamp, and file
+ * bytes that differ from the prepared content yet parse to the same page), so
+ * an unchanged legacy file stops taking a request ID on every run.
+ */
+export async function unchangedSyncImport(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig): Promise<NoopKernelWaiver[] | null> {
+ const intent = pending.intent;
+ if (intent.kind !== 'managed_sync_import' || intent.renameFrom || pending.pageId === null || typeof intent.path !== 'string' || typeof intent.content !== 'string') return null;
+ try {
+ const snapshot = await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
+ const row = screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: pending.slug, page_id: pending.pageId,
+ worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent, request_id: pending.requestId });
+ const prepared = await prepareManagedSyncMutation(engine, row, config);
+ if (prepared.file || prepared.target === 'skill_bundle') return null;
+ const file = { root: cursor.root, path: join(cursor.root, intent.path), content: intent.content };
+ const inspected = await inspectUnchanged(engine, { prepared: { ...prepared, target: 'page', file }, snapshot, sourcePath: intent.sourcePath, databaseOnly: false,
+ embeddingRequested: !prepared.deferEmbedding && !config.embedding_disabled && !!config.embedding_model?.trim(),
+ waive: intent.working === true ? ['contextual_mode', 'canonical_file_differs'] : undefined });
+ if (inspected.admitReason) return null;
+ await prepared.validate?.(engine);
+ return inspected.waived ?? [];
+ } catch {
+ return null;
+ }
+}
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index 4f72ffdcf5..1883ef27dd 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -18,7 +18,9 @@ import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { discoverManagedSync } from '../src/core/persistence/sync-discovery.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
-import { disposePersistenceConsumer } from '../src/core/persistence/service.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 { 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';
@@ -575,3 +577,154 @@ test('managed sync leaves reserved skillpack paths to the skill publisher instea
expect(await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state<>'committed'", [f.id])).toEqual([]);
}
}), 120_000);
+
+// #5984 (CEO-A12/A32/A34, ENG-A7, DX-A7/A15): a manifest delete of a page that is
+// already soft-deleted at its frozen revision advances without an admission.
+const WAIVER_OPTS = { noPull: true, noEmbed: true, noExtract: true };
+async function deletedFixture(engine: BrainEngine, files: Record<string, string>, softDeleted: string[]) {
+ const f = await fixture(engine, files);
+ expect((await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS })).status).toBe('first_sync');
+ for (const slug of softDeleted) await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.softDeletePage(slug, { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));
+ for (const path of Object.keys(files)) rmSync(join(f.root, path));
+ commit(f.root, 'remove every file');
+ return f;
+}
+const runRequests = (engine: BrainEngine, sourceId: string, runId: string) => engine.executeRaw<{ kind: string; slug: string; state: string }>(
+ "SELECT intent->>'kind' AS kind,slug,state FROM persistence_requests WHERE source_id=$1 AND intent->>'runId'=$2 ORDER BY sequence", [sourceId, runId]);
+const deleteRequests = (engine: BrainEngine, sourceId: string) => engine.executeRaw<{ slug: string; state: string }>(
+ "SELECT slug,state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_delete' ORDER BY sequence", [sourceId]);
+/** Runs `hook` when the screen re-reads `slug` (the second snapshot read: the first is the freeze). */
+function onScreen(engine: BrainEngine, slug: string, hook: () => Promise<void>): BrainEngine {
+ let reads = 0;
+ return new Proxy(engine, { get(target, key) {
+ if (key === 'readPageSnapshot') return async (read: string, opts: Parameters<BrainEngine['readPageSnapshot']>[1]) => {
+ if (read === slug && ++reads === 2) await hook();
+ return target.readPageSnapshot(read, opts);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+}
+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;
+
+test('a mostly-waived manifest reports waived deletes, not deleted pages, and admits only the live delete', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const f = await deletedFixture(engine, { 'a.md': note('First'), 'b.md': note('Second'), 'c.md': note('Third'), 'd.md': note('Fourth') }, ['a', 'b', 'c']);
+ const result = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS });
+ expect(result).toMatchObject({ status: 'synced', deleted: 1, waived: { imports: 0, deletes: 3 }, filesImported: 4 });
+ expect(result.legacySkips).toBeUndefined();
+ expect((await runRequests(engine, f.id, result.runId!)).map(row => [row.kind, row.slug, row.state]))
+ .toEqual([['managed_sync_delete', 'd', 'committed'], ['managed_sync_checkpoint', '__managed_sync_checkpoint__', 'committed']]);
+ expect(await engine.getPage('d', { sourceId: f.id })).toBeNull();
+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(git(f.root, 'rev-parse', 'HEAD'));
+ }
+}), 120_000);
+
+test('GBRAIN_SYNC_WAIVE_NOOP=0 admits every no-op entry', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_WAIVE_NOOP: '0' }, async () => {
+ expect(noopWaiversEnabled()).toBe(false);
+ expect(noopWaiversEnabled({})).toBe(true);
+ for (const engine of engines) {
+ const f = await deletedFixture(engine, { 'a.md': note('First'), 'b.md': note('Second') }, ['a', 'b']);
+ const result = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS });
+ expect(result).toMatchObject({ status: 'synced', deleted: 0, waived: { imports: 0, deletes: 0 } });
+ expect((await runRequests(engine, f.id, result.runId!)).map(row => row.kind)).toEqual(['managed_sync_delete', 'managed_sync_delete', 'managed_sync_checkpoint']);
+ }
+}), 120_000);
+
+test('a restore between freeze and screen is admitted, not waived', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) {
+ const f = await deletedFixture(engine, { 'a.md': note('Restored concurrently') }, ['a']);
+ const proxy = onScreen(engine, 'a', () => engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => { await tx.restorePage('a', { sourceId: f.id }); }, TEST_WRITE_ATTRIBUTION)));
+ try {
+ const result = await performManagedSync(proxy, { sourceId: f.id, ...WAIVER_OPTS });
+ expect(result.waived).toEqual({ imports: 0, deletes: 0 });
+ expect(await deleteRequests(engine, f.id)).toHaveLength(1);
+ expect(await engine.getPage('a', { sourceId: f.id })).not.toBeNull();
+ } finally { await disposePersistenceConsumer(proxy); rmSync(syncFailuresPath(), { force: true }); }
+ }
+}), 120_000);
+
+test.each(['restore', 'rename', 'database-only'] as const)('an unfinished %s request for the page is never overtaken by a waiver', async kind => withEnv({ GBRAIN_HOME: home }, async () => {
+ let hold = Promise.withResolvers<void>();
+ registerMutationPreparer('test_waiver_hold', async () => { await hold.promise; return { observedRevision: null, noop: true, apply: async () => ({ status: 'complete' }) }; });
+ try {
+ for (const engine of engines) {
+ hold = Promise.withResolvers<void>();
+ const f = await deletedFixture(engine, { 'a.md': note('Pending foreground work') }, ['a']);
+ const binding = (await getWorktreeBinding(engine, f.id))!;
+ const authority = await managedSyncAuthority(engine, f.id, binding.source_incarnation, f.root);
+ const page = (await engine.readPageSnapshot('a', { sourceId: f.id, includeDeleted: true }))!.page;
+ const intent = kind === 'rename' ? { renameFrom: { slug: 'a', pageId: page.id } } : { restore: true };
+ const foreground = await admitWrite(engine, { operation: 'test_waiver_hold', sourceId: f.id, sourceIncarnation: binding.source_incarnation,
+ slug: kind === 'rename' ? 'a-renamed' : 'a', pageId: kind === 'rename' ? null : page.id,
+ worktreeId: kind === 'database-only' ? null : binding.worktree_id, topologyGeneration: kind === 'database-only' ? null : binding.topology_generation,
+ principal: authority.writer.principal, authority: authority.writer, callerIntent: intent, intent });
+ expect(await engine.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, [binding.worktree_id, binding.source_incarnation, f.id, 'a', page.id, String(page.id)])).toHaveLength(1);
+ const abort = new AbortController();
+ const admitted = waitFor(async () => (await deleteRequests(engine, f.id)).length > 0, { timeoutMs: 30_000 }).then(() => abort.abort());
+ const result = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS, signal: abort.signal });
+ await admitted;
+ expect(result.waived ?? { imports: 0, deletes: 0 }).toEqual({ imports: 0, deletes: 0 });
+ expect(await deleteRequests(engine, f.id)).toHaveLength(1);
+ if (kind !== 'database-only') expect(result).toMatchObject({ status: 'partial', reason: 'timeout', writeWait: { status: 'pending' } });
+ hold.resolve();
+ await waitFor(async () => ['committed', 'conflict', 'failed'].includes((await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE id=$1::uuid', [foreground.id]))[0].state), { timeoutMs: 30_000 });
+ let finished = result;
+ for (let i = 0; i < 5 && finished.status === 'partial'; i++) finished = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS });
+ expect(finished).toMatchObject({ status: 'synced', waived: { imports: 0, deletes: 0 } });
+ await disposePersistenceConsumer(engine);
+ }
+ } finally { hold.resolve(); }
+}), 120_000);
+
+test('revoked sync authority refuses before any waiver or cursor advance', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const f = await deletedFixture(engine, { 'a.md': note('Deleted before the grant is revoked') }, ['a']);
+ const clientId = `sync-client-${randomUUID()}`;
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)
+ VALUES($1,'example-client','test-only','admin',$2,ARRAY['submit_job'])`, [clientId, f.id]);
+ const ctx = { engine, remote: true, sourceId: f.id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['admin'], sourceId: f.id, allowedOperations: ['submit_job'] } } as OperationContext;
+ const accepted = await prepareRemoteJob(ctx, 'sync', { noPull: true });
+ const before = (await engine.readPageSnapshot('a', { sourceId: f.id, includeDeleted: true }))!.revision;
+ const proxy = onScreen(engine, 'a', async () => { await engine.executeRaw("UPDATE oauth_clients SET scope='read' WHERE client_id=$1", [clientId]); });
+ try {
+ await expect(withSubmissionAuthority(accepted.authority, () => performManagedSync(proxy, accepted.data))).rejects.toMatchObject({ code: 'permission_denied' });
+ 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].counts.waived).toBeUndefined();
+ expect((await engine.readPageSnapshot('a', { sourceId: f.id, includeDeleted: true }))!.revision).toBe(before);
+ } finally { await disposePersistenceConsumer(proxy); }
+ }
+}), 120_000);
+
+test('a waiver that loses the cursor to another drain adopts the winner without double counting', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const f = await deletedFixture(engine, { 'a.md': note('First'), 'b.md': note('Second') }, ['a', 'b']);
+ let winner: Awaited<ReturnType<typeof performManagedSync>> | undefined;
+ const proxy = onScreen(engine, 'a', async () => { winner = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS }); });
+ try {
+ const loser = await performManagedSync(proxy, { sourceId: f.id, ...WAIVER_OPTS });
+ expect(winner).toMatchObject({ status: 'synced', waived: { imports: 0, deletes: 2 } });
+ expect(loser).toMatchObject({ status: 'synced', runId: winner!.runId, waived: { imports: 0, deletes: 2 }, deleted: 0 });
+ expect((await runRequests(engine, f.id, winner!.runId!)).map(row => row.kind)).toEqual(['managed_sync_checkpoint']);
+ } finally { await disposePersistenceConsumer(proxy); 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 => {
+ await tx.executeRaw('SET LOCAL enable_seqscan=off');
+ return tx.executeRaw<Record<string, string>>(`EXPLAIN ${UNFINISHED_PAGE_REQUEST_SQL}`,
+ [randomUUID(), randomUUID(), 'example-source', 'notes/example', 1, '1']);
+ });
+ const text = plan.map(row => Object.values(row)[0]).join('\n');
+ // Every branch (worktree pending, worktree recovery, database-only pending) is an index scan; the planner may
+ // serve the database-only branch from either partial pending index.
+ expect(text.match(/(Index Scan|Index Only Scan|Bitmap Index Scan) (using|on) persistence_requests_(pending|recovery|database_pending)\b/g)?.length).toBeGreaterThanOrEqual(3);
+ expect(text).toContain('persistence_requests_recovery');
+ expect(text).not.toContain('Seq Scan');
+ }
+}, 60_000);