Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(#6712 PR 4b): proof-carrying confirm round: round 2 re-reads only the pass's writes

garrytan84fac1e30590
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index c81bec4710..fc99f874a5 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -37,6 +37,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
| 'purge:ledger_redaction'
// #6712 PR 4b: after a page-row deletion of a managed Git source wrote its origin's deletion marker (sync-markers.ts), before the row goes.
| 'purge:marker_written'
+ // #6712 PR 4b: before each round of a pass reads its level (`round`), and after it read it (`level`: its statements and its
+ // confirm-round verdict), before it applies.
+ | 'sync:round_start' | 'sync:level_read'
// #6650: `gbrain repair stuck-recovery` (recovery-resolve.ts): after the backup is durable (before its journal step), after the prior
// bytes are written (before their journal step), after a --keep disk write is abandoned (its journal step written), and after recoverPublication returns.
| 'stuck_recovery:backed_up' | 'stuck_recovery:written' | 'stuck_recovery:abandoned' | 'stuck_recovery:recovered'
@@ -52,7 +55,8 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
* cancellation (settle on abort) and one that ignores it (hang on).
*/
/** `writeId` is the write request row: rows of a caller-bound replay share one `requestId` (crash-robot per-request seams key on the row). */
-export interface FaultDetail { requestId?: string; writeId?: string; effectId?: string; sourceId?: string; operation?: string | null; signal?: AbortSignal; slug?: string; path?: string }
+export interface FaultDetail { requestId?: string; writeId?: string; effectId?: string; sourceId?: string; operation?: string | null; signal?: AbortSignal; slug?: string; path?: string;
+ round?: number; level?: { statements: number; confirm: { taken: boolean; reason: string | null; rows: number } | null } }
/** Postgres returns `persistence_effects.id` (bigserial) as a BigInt; `faultPoint` hands hooks its decimal string (#6584). */
export type FaultDetailInput = Omit<FaultDetail, 'effectId'> & { effectId?: string | number | bigint };
type FaultHook = (point: FaultPoint, detail: FaultDetail) => Promise<void> | void;
diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.ts
index 758df6fec3..4faa89009a 100644
--- a/src/core/persistence/sync-pass-apply.ts
+++ b/src/core/persistence/sync-pass-apply.ts
@@ -82,11 +82,16 @@ export interface PassApplyState {
/** The newest round's classes and summary (design §9), after this module settled what it finished. */
classes: Record<string, { count: number; action: SyncClassAction }>;
summary: PassRoundSummary | null;
+ /**
+ * The pages whose import record the newest round wrote: here, or in its batches (an import, or a waiver of an unchanged
+ * page). The next round's confirm proof attributes those records to the pass.
+ */
+ recorded: Set<number>;
}
export function newPassApplyState(): PassApplyState {
return { markersRetired: 0, holds: { file_gone: 0, tombstone_edited: 0, purged_differs: 0, settle_mismatch: 0 }, settleMismatch: [], adopted: 0,
- swept: { screened: 0, recorded: 0 }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], matchedSlugs: new Set(), classes: {}, summary: null };
+ swept: { screened: 0, recorded: 0 }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], matchedSlugs: new Set(), classes: {}, summary: null, recorded: new Set() };
}
export interface PassApplyInput {
@@ -123,6 +128,7 @@ function levelMeta(level: ShadowLevel, entry: ShadowPath): Partial<GitHoldMeta>
/** Runs the round's settle-side work (module header) and settles the paths it finished in `level.paths`. */
export async function applyPassRound(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {
+ state.recorded.clear();
if (input.fullRound && !input.remote) await retireMarkers(engine, level, state);
if (input.remote && input.grantPrefixes) {
const step = loopYield();
@@ -272,8 +278,10 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Pa
interface RecordWrite { pageId: number; revision: string; record: Omit<SyncImportProvenance, 'recorded_at' | 'validated'> }
/** The batched, fenced record write: a page whose revision moved since the round read it is left alone. Returns the pages written. */
-async function writeRecords(engine: BrainEngine, level: ShadowLevel, writes: RecordWrite[]): Promise<Set<number>> {
+async function writeRecords(engine: BrainEngine, level: ShadowLevel, writes: RecordWrite[], recorded: Set<number>): Promise<Set<number>> {
if (!writes.length) return new Set();
+ // Noted before the transaction: a commit whose acknowledgement is lost still names the pass as the records' writer.
+ for (const write of writes) recorded.add(write.pageId);
return engine.transaction(async tx => {
await assertDrainLease(tx, level.sourceId);
const rows = await tx.executeRaw<{ id: number | string; revision: string }>('SELECT id, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND id=ANY($2::int[]) FOR SHARE',
@@ -297,7 +305,7 @@ async function adoptRecords(engine: BrainEngine, level: ShadowLevel, state: Pass
: { source_id: level.sourceId, incarnation: level.incarnation, page_id: entry.pageId!, origin: sourcePath, raw_sha256: entry.state.levelSha256 ?? '', gbrain_version: VERSION, working: level.mode === 'working' };
return { pageId: entry.pageId!, revision: entry.revision!, record: { ...base, blob_oid: entry.state.level!, disk_blob_oid: entry.state.diskOid ?? prior?.disk_blob_oid ?? entry.state.level!, revision: entry.revision! } };
});
- state.adopted += (await writeRecords(engine, level, writes)).size;
+ state.adopted += (await writeRecords(engine, level, writes, state.recorded)).size;
}
/** Design §2.7: the bounded read-only legacy sweep; an equal page gets a record and is `matched`. */
@@ -324,7 +332,7 @@ async function sweepLegacy(engine: BrainEngine, level: ShadowLevel, input: PassA
blob_oid: entry.state.level!, disk_blob_oid: entry.state.diskOid ?? entry.state.level!, revision: entry.revision!, parser: syncImportParserFor(path, level.pack), gbrain_version: VERSION,
working: level.mode === 'working' } }];
});
- const written = await writeRecords(engine, level, writes);
+ const written = await writeRecords(engine, level, writes, state.recorded);
state.swept.recorded += written.size;
for (const entry of same) if (written.has(entry.pageId!)) settleAs(entry, { cls: 'matched', settled: true, action: 'none', classAction: 'none' });
}
diff --git a/src/core/persistence/sync-pass-confirm.ts b/src/core/persistence/sync-pass-confirm.ts
new file mode 100644
index 0000000000..e619dad1fc
--- /dev/null
+++ b/src/core/persistence/sync-pass-confirm.ts
@@ -0,0 +1,134 @@
+/**
+ * #6712 PR 4b: the proof-carrying confirm round. A pass's next round at the same commit reuses the previous round's `I⋈P`
+ * (every page of the source with an origin, joined with its import record) and re-reads only the pages the pass itself
+ * wrote, when the database proves that nothing else changed since the previous round's mark (S1). A change it cannot
+ * attribute to the pass, a count it cannot account for, or a statement error takes the full read. Q4 is narrowed for this
+ * round only (GBRA-108, under Garry's 2026-10-17 standing approval).
+ *
+ * Every relation the level read or the classifier consumes, and why a reused `I⋈P` stays exact:
+ * - `pages` (`I⋈P`): every row of the source whose `xmin` S1 does not prove committed must carry a revision a committed
+ * request of this pass produced (`revision_write_request_id` names the request, its intent names the pass and its outcome
+ * names the row's revision); the delta re-reads exactly those rows. `pages` carries no `last_write_request_id` (only
+ * facts, takes and timeline entries do), and the revision's writer survives a write that keeps the revision: such a write
+ * to a page the pass wrote is re-read with it, so the reused rows still equal a whole read. A deletion leaves no `xmin`,
+ * so the source's count of pages with an origin must equal the reused rows plus the new ones the delta read.
+ * - `op_checkpoints`, every op the level reads for the incarnation (`CONFIRM_OPS`): import records (`I⋈P`), holds, the hold
+ * summary and retry rows, origin and legacy deletion markers, the withheld-deletes record and the pass row with its
+ * episode. A changed row is allowed only as the pass row, as the import record of a page the pass wrote at that page's
+ * revision or of a page whose record the pass's round wrote (`recorded`: the record writes of sync-pass-apply.ts, the
+ * page then re-read too), or as a hold the pass wrote (its `run_id`, with the summary row that moves with it); every other op's count
+ * must equal S1's plus the records the pass inserted (and the pass row, when S1 had none), and the holds must keep every
+ * S1 fingerprint (a release is not attributed) and add only the pass's. Holds, markers, the withheld record and the pass
+ * row are re-read by every round as well; the proof keeps a foreign change of them on the full read all the same.
+ * - `persistence_requests` and `persistence_effects`: open work (`U_db`), the attestations (`A`) and the legacy deletions
+ * are re-read by every round.
+ * - `sources` and `config`: the pass's context is fixed for the pass, and the level's settings are re-read by every round.
+ * - Git: HEAD must equal the previous round's and the mode be committed (both are in the reuse key); `T` is cached by commit
+ * and the index (`X`) is re-read by every round. Working mode always takes the full read.
+ *
+ * Visibility: a row's `xmin` (a 32-bit xid) widens to 64 bits in the 2^32 window below S2's `xmax` (an unfrozen xid is
+ * within 2^31 of it), and the row is unchanged only when that is below S1's `xmin`: every transaction below it, a
+ * subtransaction's included (`pg_visible_in_snapshot` cannot see subtransactions, which savepoints create), had ended
+ * before S1. The frozen ids (below 3) are unchanged. The `txid_*` snapshot functions exist on every supported Postgres and
+ * on PGLite. More than 2^31 xids between S1 and S2 takes the full read.
+ */
+import { GIT_HOLD_OP, GIT_HOLD_RETRY_OP, GIT_HOLD_SUMMARY_OP, SYNC_IMPORT_PROVENANCE_OP } from './sync-holds.ts';
+import { MANAGED_SYNC_PASS_OP, SYNC_DELETES_WITHHELD_OP, SYNC_ORIGIN_DELETED_OP } from './sync-pass-row.ts';
+import type { BrainEngine } from '../engine.ts';
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+
+export const CONFIRM_OPS = [SYNC_IMPORT_PROVENANCE_OP, GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, GIT_HOLD_RETRY_OP, SYNC_ORIGIN_DELETED_OP, SYNC_DELETES_WITHHELD_OP, MANAGED_SYNC_PASS_OP];
+
+/** A round's mark: its snapshot's `xmin` and `xmax` (64-bit), each `CONFIRM_OPS` op's row count for the incarnation and its holds' fingerprints. */
+export interface LevelMark { xmin: string; xmax: string; ops: Record<string, number>; holds: string[] }
+
+/** The incarnation's `CONFIRM_OPS` rows (`o`: the table alias's prefix; `ops` and `scope`: their placeholders). */
+const opScope = (o: string, ops: string, scope: string) => `${o}op = ANY(${ops}::text[]) AND (${o}fingerprint = ${scope} OR starts_with(${o}fingerprint, ${scope} || ':'))`;
+const opCounts = (ops: string, scope: string) => `(SELECT COALESCE(jsonb_object_agg(op, n), '{}'::jsonb) FROM (SELECT op, count(*)::int AS n FROM op_checkpoints WHERE ${opScope('', ops, scope)} GROUP BY op) c) AS ops,
+ (SELECT COALESCE(jsonb_agg(fingerprint), '[]'::jsonb) FROM op_checkpoints WHERE op='${GIT_HOLD_OP}' AND starts_with(fingerprint, ${scope} || ':')) AS holds`;
+
+/** The round's mark, read inside its snapshot (on PGLite, before the round's other reads, so whatever lands later reads as changed). */
+export async function readLevelMark(exec: Exec, sourceId: string, incarnation: string): Promise<LevelMark> {
+ const [row] = await exec.executeRaw<{ xmin: string; xmax: string; ops: Record<string, number> | null; holds: string[] }>(
+ `SELECT txid_snapshot_xmin(txid_current_snapshot())::text AS xmin, txid_snapshot_xmax(txid_current_snapshot())::text AS xmax, ${opCounts('$1', '$2')}`,
+ [CONFIRM_OPS, `${sourceId}:${incarnation}`]);
+ return { xmin: row!.xmin, xmax: row!.xmax, ops: row!.ops ?? {}, holds: row!.holds };
+}
+
+/** Whether `col` (an xid) was committed before S1: widened below S2's `xmax` (`x.hi`), it is below S1's `xmin` (`x.lo`). */
+const unchanged = (col: string) => {
+ const wide = `((x.hi - x.hi % 4294967296) + ${col}::text::bigint)`;
+ return `(${col}::text::bigint < 3 OR (CASE WHEN ${wide} >= x.hi THEN ${wide} - 4294967296 ELSE ${wide} END) < x.lo)`;
+};
+
+const PROOF = `WITH x AS MATERIALIZED (SELECT $4::bigint AS lo, txid_snapshot_xmin(txid_current_snapshot()) AS now_lo,
+ txid_snapshot_xmax(txid_current_snapshot()) AS hi)
+ SELECT x.now_lo::text AS xmin, x.hi::text AS xmax, (x.hi - $5::bigint)::float8 AS span, ${opCounts('$2', '$3')},
+ (SELECT count(*)::int FROM pages WHERE source_id=$1 AND source_path IS NOT NULL) AS pages,
+ (SELECT COALESCE(jsonb_agg(jsonb_build_array(p.id::text, r.id IS NOT NULL, p.knowledge_revision::text)), '[]'::jsonb)
+ FROM pages p LEFT JOIN persistence_requests r ON r.id=p.revision_write_request_id AND r.source_id=$1
+ AND r.state='committed' AND r.intent->>'passId'=$6 AND r.outcome->>'revision'=p.knowledge_revision::text
+ WHERE p.source_id=$1 AND NOT ${unchanged('p.xmin')}) AS pages_changed,
+ (SELECT COALESCE(jsonb_agg(jsonb_build_array(o.op, o.fingerprint, o.completed_keys->0->>'revision', o.completed_keys->0->>'run_id')), '[]'::jsonb)
+ FROM op_checkpoints o WHERE ${opScope('o.', '$2', '$3')} AND NOT ${unchanged('o.xmin')}) AS ops_changed
+ FROM x`;
+
+/**
+ * What the pass may reuse: the pages it wrote since S1 (`pages`, by id), which of them changed their import record
+ * (`records`), the source's count of pages with an origin, and S2's mark for the next round; or why the full read.
+ */
+export type ConfirmProof = { ok: true; mark: LevelMark; pages: string[]; records: Set<string>; pageCount: number; summary: boolean } | { ok: false; reason: string; mark: LevelMark | null };
+
+/**
+ * Proves, in S2 (the round's snapshot), that every change since `base` (S1) to what the level read consumes is the pass's
+ * own write (see the header). The counts still need the reused rows: `countsMatch` checks them after the delta read.
+ */
+export async function proveConfirm(exec: Exec, input: { sourceId: string; incarnation: string; passId: string; base: LevelMark; recorded?: ReadonlySet<number> }): Promise<ConfirmProof> {
+ const scope = `${input.sourceId}:${input.incarnation}`;
+ const [row] = await exec.executeRaw<{ xmin: string; xmax: string; span: number; ops: Record<string, number> | null; holds: string[]; pages: number;
+ pages_changed: Array<[string, boolean, string]>; ops_changed: Array<[string, string, string | null, string | null]> }>(
+ PROOF, [input.sourceId, CONFIRM_OPS, scope, input.base.xmin, input.base.xmax, input.passId]);
+ const mark: LevelMark = { xmin: row!.xmin, xmax: row!.xmax, ops: row!.ops ?? {}, holds: row!.holds };
+ if (!(Number(row!.span) >= 0 && Number(row!.span) < 2 ** 31)) return { ok: false, reason: 'xid_span', mark };
+ const revisions = new Map<string, string>();
+ for (const [id, ours, revision] of row!.pages_changed) {
+ if (!ours) return { ok: false, reason: 'foreign_page_write', mark };
+ revisions.set(id, revision);
+ }
+ const records = new Set<string>(), held = new Set<string>(), reread = new Set<string>();
+ let summary = false;
+ for (const [op, fingerprint, revision, runId] of row!.ops_changed) {
+ if (op === MANAGED_SYNC_PASS_OP && fingerprint === scope) continue;
+ // A hold the pass wrote names it (`run_id`); the summary row moves with it.
+ if (op === GIT_HOLD_OP && runId === input.passId) { held.add(fingerprint); continue; }
+ if (op === GIT_HOLD_SUMMARY_OP && fingerprint === scope) { summary = true; continue; }
+ const pageId = op === SYNC_IMPORT_PROVENANCE_OP && fingerprint.startsWith(`${scope}:`) ? fingerprint.slice(scope.length + 1) : null;
+ // A record the pass's round wrote outside its imports (a page it did not rewrite): its page is re-read with the others.
+ if (pageId !== null && !revisions.has(pageId) && input.recorded?.has(Number(pageId))) { reread.add(pageId); records.add(pageId); continue; }
+ if (pageId === null || revisions.get(pageId) !== revision) return { ok: false, reason: 'foreign_checkpoint_write', mark };
+ records.add(pageId);
+ }
+ if (summary && !held.size) return { ok: false, reason: 'foreign_checkpoint_write', mark };
+ // Holds: none of S1's is gone (a release is not attributed), and every new one is the pass's.
+ const before = new Set(input.base.holds), now = new Set(mark.holds);
+ if ([...before].some(print => !now.has(print)) || [...now].some(print => !before.has(print) && !held.has(print))) return { ok: false, reason: 'holds', mark };
+ return { ok: true, mark, pages: [...revisions.keys(), ...reread], records, pageCount: Number(row!.pages), summary };
+}
+
+/**
+ * The counts S2 must show: the reused rows plus the new pages the delta read (`pages`), and S1's op counts plus the import
+ * records the pass inserted (`newRecords`), its pass row if S1 had none and the hold summary its holds created. Anything else
+ * (a deletion) is a mismatch.
+ */
+export function countsMatch(base: LevelMark, proof: Extract<ConfirmProof, { ok: true }>, added: { pages: number; newRecords: number }): boolean {
+ if (proof.pageCount !== added.pages) return false;
+ for (const op of CONFIRM_OPS) {
+ const before = base.ops[op] ?? 0, after = proof.mark.ops[op] ?? 0;
+ if (op === GIT_HOLD_OP) continue;
+ // The pass row, and the hold summary a hold of the pass created, may be new.
+ const created = before === 0 && after === 1 && (op === MANAGED_SYNC_PASS_OP || op === GIT_HOLD_SUMMARY_OP && proof.summary);
+ if (op === SYNC_IMPORT_PROVENANCE_OP ? after !== before + added.newRecords : after !== before && !created) return false;
+ }
+ return true;
+}
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index ee389ce965..3e17637587 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -31,6 +31,7 @@ import { recordPassFenceTrend, type PassStamp, type SyncCursorOptions, type Sync
import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP, writePassRow, type ManagedSyncPassValue, type PassEpisode,
type PassKind, type PassOutcome, type SyncSelection } from './sync-pass-row.ts';
import { readSyncAdmission, type SyncAdmission } from './sync-admission.ts';
+import { faultPoint } from './fault-points.ts';
import { passIdleProbe, readShadowLevel, workingIdleChange, type PassLevelCache, type ShadowLevel, type ShadowPath } from './sync-pass.ts';
import { loopYield } from './sync-yield.ts';
import { recallWorkingStatCache, rememberWorkingStatCache, SyncTreeReadIncomplete } from './sync-git-stream.ts';
@@ -604,6 +605,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
/** Drains one batch; a stop is the pass's ending, and `stop` folds that batch's counts in. */
const drain = async (entries: PassEntry[], stamp?: PassStamp): Promise<SyncResult | null> => {
const key = `${PASS_BATCH_KEY_PREFIX}${passId}:${batchNo++}`;
+ for (const entry of entries) if (entry.pageId != null) applied.recorded.add(entry.pageId);
const batch = batchCursor(entries, stamp);
const drained = await input.drainBatch(key, batch, sliceBase);
if ('entries' in drained) {
@@ -667,9 +669,11 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
input.onLevelRead(head);
// The previous round's level is done with: dropped before the next one is read, so a large source holds one level, not two.
lastLevel = null;
+ await faultPoint('sync:round_start', { sourceId, round });
const level = await readShadowLevel(engine, { sourceId, context, workingTree: mode === 'working',
pass: { noSchemaPack: processingOptions.noSchemaPack, episodeFullId: episode?.full_id ?? null, retryConsumed: round > 1 ? retryConsumed : undefined, exclude: opts.exclude, includeHidden: opts.includeHidden, strategy: opts.strategy, bootstrap: markersOwed(),
- slugMode: value.obligations.slug_mode, cache: levelCache } });
+ slugMode: value.obligations.slug_mode, cache: levelCache, passId, recorded: applied.recorded } });
+ await faultPoint('sync:level_read', { sourceId, round, level: level ? { statements: level.statements, confirm: level.confirm ?? null } : undefined });
assertActive();
if (!level) throw new Error(`Source ${sourceId} became a company-brain source during its sync pass.`);
// Each round reads the level at the current HEAD, and its batches freeze that commit (a commit landing mid-pass is
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index 9e994f1348..5a361d9be2 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -41,6 +41,7 @@ import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceRec
import { readManagedMode } from './ownership.ts';
import { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP, type SyncSelection } from './sync-pass-row.ts';
import { filterYielding, loopYield, sortYielding, type LoopYield } from './sync-yield.ts';
+import { countsMatch, proveConfirm, readLevelMark, type ConfirmProof, type LevelMark } from './sync-pass-confirm.ts';
export { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP };
@@ -65,6 +66,10 @@ export interface PassLevelInput {
slugMode?: 'git-root' | 'source-root';
/** The pass's own cache (it dies with the pass): the eligible tree of the commit and selection its last round read. */
cache?: PassLevelCache;
+ /** The pass's id: a round after the first reuses the cached `I⋈P` when its writes are all the database changed (sync-pass-confirm.ts). */
+ passId?: string;
+ /** The pages whose import record the pass's previous round wrote (sync-pass-apply.ts `recorded`). */
+ recorded?: ReadonlySet<number>;
}
/** PGLite's keyset page size (design v3.2 §2.1). */
const PGLITE_KEYSET_ROWS = 2_000;
@@ -80,7 +85,11 @@ const LEVEL_BLOB_MAX_BYTES = 8 * 1024 * 1024;
const SYNC_WRITE_KINDS = ['managed_sync_import', 'managed_sync_delete'];
/** What one pass reuses between its rounds: a commit's tree never changes, so the next round at the same commit and selection reads it from here. */
-export interface PassLevelCache { tree?: { key: string; tree: Map<string, GitTreeEntry>; colon: string[] } }
+export interface PassLevelCache {
+ tree?: { key: string; tree: Map<string, GitTreeEntry>; colon: string[] };
+ /** The last committed-mode round's `I⋈P` and its mark (S1), keyed by source, incarnation, worktree, HEAD and expected parser. */
+ pages?: { key: string; mark: LevelMark; table: PageTable };
+}
/**
* Classifier results never change once made (a settle replaces the object), so equal ones are one object: a 600k-path
@@ -176,6 +185,8 @@ export interface ShadowLevel {
fileRefusals?: SyncFileRefusal[];
timings_ms: Record<string, number>;
statements: number;
+ /** A round after a pass's first: whether it reused the previous round's `I⋈P` (`rows` re-read), or why it read it whole. */
+ confirm?: { taken: boolean; reason: string | null; rows: number };
}
/** A page of the source with the import-record fields the classifier reads; `arm1` / `attested_hash` (`A`) are filled for the pages that need a proof. */
@@ -258,7 +269,8 @@ async function withRoundSnapshot<T>(engine: BrainEngine, fn: (exec: Exec) => Pro
* stretch of about a second and held every raw row at once. `cursor_tuple_fraction = 1` keeps the whole-result plan.
* PGLite reads bounded keyset statements so writers interleave.
*/
-async function readPages(exec: Exec, kind: 'postgres' | 'pglite', sourceId: string, incarnation: string, expected: SyncImportParser): Promise<{ pages: PageTable; statements: number }> {
+async function readPages(exec: Exec, kind: 'postgres' | 'pglite', sourceId: string, incarnation: string, expected: SyncImportParser,
+ only?: { table: PageTable; ids: string[]; slots: Map<string, number> }): Promise<{ pages: PageTable; statements: number } | null> {
// A record's fields usually repeat the page's (origin = source_path, disk = blob, revision = the page's), so those come back
// as a flag instead of a second copy of the string, and so does the parser when it is the Markdown one the level expects
// (`expected`, the same object for every such page; any other comes as text parsed once per distinct value): a 600k-page
@@ -285,30 +297,40 @@ async function readPages(exec: Exec, kind: 'postgres' | 'pglite', sourceId: stri
const params = [sourceId, SYNC_IMPORT_PROVENANCE_OP, `${sourceId}:${incarnation}:`, JSON.stringify(expected)];
type Raw = Omit<PageRow, 'record' | 'arm1' | 'attested_hash'> & { has_record: boolean; rec_origin_same: boolean; rec_origin: string | null; rec_blob_oid: string | null;
rec_disk_same: boolean; rec_disk_blob_oid: string | null; rec_revision_null: boolean; rec_revision: string | null; rec_parser: string | null; rec_parser_expected: boolean | null; rec_full_episode: string | null; rec_working: string | null };
- const pages = new PageTable(expected);
+ const pages = only?.table ?? new PageTable(expected);
const parsers = new Map<string, SyncImportProvenance['parser'] | undefined>(), episodes = new Map<string, string>();
const parserOf = (text: string | null) => {
if (text === null) return undefined;
if (!parsers.has(text)) parsers.set(text, JSON.parse(text) ?? undefined);
return parsers.get(text);
};
- const take = (page: Raw[]) => {
- for (const raw of page) {
- const i = pages.length, working = raw.rec_working === 'true' || raw.rec_working === 'false';
- pages.id.push(raw.id); pages.slug.push(raw.slug); pages.sourcePath.push(raw.source_path); pages.revision.push(raw.revision); pages.requestId.push(raw.request_id);
- pages.bits.push((raw.deleted ? PAGE_DELETED : 0) | (raw.has_record ? PAGE_RECORD : 0) | (raw.rec_revision_null ? PAGE_REVISION_NULL : 0)
- | (raw.rec_parser_expected ? PAGE_PARSER_EXPECTED : 0) | (working ? PAGE_WORKING : 0) | (raw.rec_working === 'true' ? PAGE_WORKING_TRUE : 0));
- const episode = raw.has_record ? raw.rec_full_episode : null;
- if (typeof episode === 'string' && !episodes.has(episode)) episodes.set(episode, episode);
- pages.blobOid.push(raw.has_record ? raw.rec_blob_oid ?? undefined : undefined); pages.fullEpisode.push(typeof episode === 'string' ? episodes.get(episode)! : episode);
- if (!raw.has_record) continue;
- if (!raw.rec_origin_same) pages.origin.set(i, raw.rec_origin ?? '');
- if (!raw.rec_disk_same) pages.diskBlobOid.set(i, raw.rec_disk_blob_oid);
- if (raw.rec_revision !== null) pages.recordRevision.set(i, raw.rec_revision);
- const parser = raw.rec_parser_expected ? undefined : parserOf(raw.rec_parser);
- if (parser !== undefined) pages.parser.set(i, parser);
- }
+ /** Writes `raw` to slot `i`: the next one, or (a confirm round) the slot of a page the pass rewrote. */
+ const put = (raw: Raw, i: number) => {
+ const working = raw.rec_working === 'true' || raw.rec_working === 'false';
+ pages.id[i] = raw.id; pages.slug[i] = raw.slug; pages.sourcePath[i] = raw.source_path; pages.revision[i] = raw.revision; pages.requestId[i] = raw.request_id;
+ pages.bits[i] = (raw.deleted ? PAGE_DELETED : 0) | (raw.has_record ? PAGE_RECORD : 0) | (raw.rec_revision_null ? PAGE_REVISION_NULL : 0)
+ | (raw.rec_parser_expected ? PAGE_PARSER_EXPECTED : 0) | (working ? PAGE_WORKING : 0) | (raw.rec_working === 'true' ? PAGE_WORKING_TRUE : 0);
+ const episode = raw.has_record ? raw.rec_full_episode : null;
+ if (typeof episode === 'string' && !episodes.has(episode)) episodes.set(episode, episode);
+ pages.blobOid[i] = raw.has_record ? raw.rec_blob_oid ?? undefined : undefined; pages.fullEpisode[i] = typeof episode === 'string' ? episodes.get(episode)! : episode;
+ if (only) for (const sparse of [pages.origin, pages.diskBlobOid, pages.recordRevision, pages.parser]) sparse.delete(i);
+ if (!raw.has_record) return;
+ if (!raw.rec_origin_same) pages.origin.set(i, raw.rec_origin ?? '');
+ if (!raw.rec_disk_same) pages.diskBlobOid.set(i, raw.rec_disk_blob_oid);
+ if (raw.rec_revision !== null) pages.recordRevision.set(i, raw.rec_revision);
+ const parser = raw.rec_parser_expected ? undefined : parserOf(raw.rec_parser);
+ if (parser !== undefined) pages.parser.set(i, parser);
};
+ const take = (page: Raw[]) => { for (const raw of page) put(raw, pages.length); };
+ if (only) {
+ // A confirm round: the previous round's rows, with the pages the pass wrote re-read into their slots (a new page last,
+ // as the keyset would read it). A rewritten page that left `I⋈P` cannot be patched: the caller reads it whole.
+ const rows = await exec.executeRaw<Raw>(`${select} AND p.id = ANY($5::bigint[]) ORDER BY p.id`, [...params, only.ids]);
+ const read = new Set(rows.map(raw => String(raw.id)));
+ if ([...only.slots.keys()].some(id => !read.has(id))) return null;
+ for (const raw of rows) put(raw, only.slots.get(String(raw.id)) ?? pages.length);
+ return { pages, statements: 1 };
+ }
let statements = 0;
if (kind === 'postgres') {
const declared = Promise.all([exec.executeRaw('SET LOCAL cursor_tuple_fraction = 1'), exec.executeRaw(`DECLARE sync_pass_pages NO SCROLL CURSOR FOR ${select}`, params)]);
@@ -520,7 +542,8 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
mode === 'working' ? timed('X', () => readIndexLevel(gitRoot)) : Promise.resolve(new Map<string, GitIndexEntry>()),
timed('U', async () => (mode === 'working' ? (await readUntracked(gitRoot, scope)).filter(eligible) : []))]),
// Issued together, the snapshot's statements pipeline on its one connection (PGLite runs them in turn).
- timed('I⋈P', () => readRoundSnapshot(engine, { kind: engineKind, sourceId, incarnation, worktreeId: context.binding.worktree_id, parser: syncImportParser(pack?.identity ?? null) }, timed)),
+ timed('I⋈P', () => readRoundSnapshot(engine, { kind: engineKind, sourceId, incarnation, worktreeId: context.binding.worktree_id, parser: syncImportParser(pack?.identity ?? null),
+ reuse: cache && input.pass?.passId ? { cache, passId: input.pass.passId, recorded: input.pass.recorded, working: mode === 'working', head } : undefined }, timed)),
timed('H', () => readLevelHolds(engine, sourceId, incarnation, input.pass?.retryConsumed)),
]);
timings.reads = t();
@@ -540,7 +563,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
};
const inLevel = (path: string) => tree.has(path) || eligible(path);
const untracked = new Set(untrackedPaths);
- const { open, markers, passRow, statements } = snapshot;
+ const { open, markers, passRow, statements, confirm } = snapshot;
const { holds, retry } = held;
const toGit = (holdPath: string) => (scope ? `${scope}/${holdPath}` : holdPath);
const holdByGitPath = new Map<string, GitHoldRecord>(holds.map(hold => [toGit(hold.path), hold]));
@@ -737,7 +760,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
return { sourceId, incarnation, root, gitRoot, scope, slugMode, mode, head, baselineCommit, full: input.full === true, kind: kind.kind, kindBlockers: kind.blockers,
heldRenames: holds.flatMap(hold => hold.meta.rename_from ? [{ path: toGit(hold.path), rename: hold.meta.rename_from }] : []),
releasableHolds: holds.filter(hold => !domain.has(toGit(hold.path))).map(hold => hold.path),
- paths, reconcilable, ...(colon.refusals.size ? { fileRefusals: [...colon.refusals.values()] } : {}), timings_ms: timings, statements: statements + attestationStatements + 3, pack: pack?.identity ?? null,
+ paths, reconcilable, ...(colon.refusals.size ? { fileRefusals: [...colon.refusals.values()] } : {}), timings_ms: timings, statements: statements + attestationStatements + 3, ...(confirm ? { confirm } : {}), pack: pack?.identity ?? null,
selection: { exclude: [...exclude].sort(), includeHidden: [...includeHidden].sort(), strategy, srcSubpath: scope || null, mode },
rescreenDue: holds.filter(hold => holdRescreenDue(hold, retry.has(hold.path))).map(hold => toGit(hold.path)), workingCache: hashed?.cache ?? null };
}
@@ -762,16 +785,77 @@ async function readLevelSettings(engine: BrainEngine, context: ManagedSyncContex
keepDbPrefixes: (() => { try { return loadStorageConfig(root)?.keep_db ?? []; } catch { return []; } })() };
}
-/** The round's database snapshot (`I⋈P`, `U_db`, the markers and the pass row); issued together, its statements pipeline on its one connection (PGLite runs them in turn). */
-async function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres' | 'pglite'; sourceId: string; incarnation: string; worktreeId: string; parser: SyncImportParser },
- timed: <T>(key: string, read: () => Promise<T>) => Promise<T>) {
- const { kind, sourceId, incarnation, worktreeId } = input;
- return withRoundSnapshot(engine, async exec => {
- const [read, work, markers, passRow] = await Promise.all([timed('pages', () => readPages(exec, kind, sourceId, incarnation, input.parser)),
- timed('open_work', () => readOpenWork(exec, sourceId, incarnation, worktreeId)), timed('markers', () => readMarkers(exec, sourceId, incarnation)),
+/** A failed mark, proof or delta read: the round reads again without them (it aborted a Postgres snapshot). */
+class ConfirmFailure extends Error {}
+const confirmGuard = <T>(read: Promise<T>) => read.catch((error: unknown) => { throw new ConfirmFailure(String(error)); });
+
+/**
+ * The round's database snapshot (`I⋈P`, `U_db`, the markers and the pass row); issued together, its statements pipeline on
+ * its one connection (PGLite runs them in turn). A pass round (`reuse`) also marks the snapshot, and a later round at the
+ * same key reuses the last `I⋈P` when sync-pass-confirm.ts proves it (else reads it whole). The proof never throws: a
+ * failed mark, proof or delta read reads the round again, whole and unmarked.
+ */
+async function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres' | 'pglite'; sourceId: string; incarnation: string; worktreeId: string; parser: SyncImportParser;
+ reuse?: { cache: PassLevelCache; passId: string; recorded?: ReadonlySet<number>; working: boolean; head: string } }, timed: <T>(key: string, read: () => Promise<T>) => Promise<T>) {
+ const { kind, sourceId, incarnation, worktreeId, reuse } = input;
+ // Reused only at the same commit, worktree and parser, in committed mode: working mode always reads `I⋈P` whole.
+ const key = JSON.stringify([sourceId, incarnation, worktreeId, reuse?.head, input.parser]);
+ const unkeyed = reuse?.cache.pages && (reuse.working || reuse.cache.pages.key !== key) ? { taken: false, reason: reuse.working ? 'working' : 'key', rows: 0 } : undefined;
+ let prior = reuse && !unkeyed ? reuse.cache.pages : undefined;
+ const confirming = prior !== undefined;
+ if (reuse) reuse.cache.pages = undefined;
+ const round = (marking: boolean) => withRoundSnapshot(engine, async exec => {
+ const base = marking ? prior?.mark : undefined;
+ const proof = base ? confirmGuard(timed('confirm', () => proveConfirm(exec, { sourceId, incarnation, passId: reuse!.passId, base, recorded: reuse!.recorded }))) : null;
+ const marked = marking && !base ? confirmGuard(readLevelMark(exec, sourceId, incarnation)) : null;
+ // PGLite has no snapshot: the mark (or the proof, the next round's mark) runs before the reads it vouches for.
+ if (kind === 'pglite') await (proof ?? marked)?.catch(() => undefined);
+ const others = Promise.all([timed('open_work', () => readOpenWork(exec, sourceId, incarnation, worktreeId)), timed('markers', () => readMarkers(exec, sourceId, incarnation)),
timed('pass_row', () => readPassRow(exec, sourceId, incarnation))]);
- return { pages: read.pages, open: work, markers, passRow, statements: read.statements + work.statements + 2 };
+ others.catch(() => undefined);
+ const confirmed = proof ? await confirmPages(exec, { kind, sourceId, incarnation, parser: input.parser, prior: prior!, proof }, timed) : null;
+ // Read whole, the round holds one `I⋈P`, not the reused one beside it.
+ if (!confirmed?.read) prior = undefined;
+ // A failed mark fails what was pipelined after it: the mark's failure is the one to report.
+ const read = confirmed?.read ?? await timed('pages', () => readPages(exec, kind, sourceId, incarnation, input.parser)).catch(async (error: unknown) => { await marked; throw error; });
+ const mark = confirmed?.mark ?? (marked ? await marked : null);
+ const [work, markers, passRow] = await others;
+ if (reuse && mark) reuse.cache.pages = { key, mark, table: read!.pages };
+ const confirm = confirmed?.confirm ?? unkeyed;
+ return { pages: read!.pages, open: work, markers, passRow, statements: read!.statements + work.statements + 2 + (proof || marked ? 1 : 0), ...(confirm ? { confirm } : {}) };
});
+ if (!reuse || reuse.working) return round(false);
+ try { return await round(true); } catch (error) {
+ if (!(error instanceof ConfirmFailure)) throw error;
+ prior = undefined;
+ return { ...await round(false), ...(confirming ? { confirm: { taken: false, reason: 'error', rows: 0 } } : {}) };
+ }
+}
+
+/**
+ * A confirm round's `I⋈P`: with the proof (S2's mark) in hand, the previous round's rows with the pages the pass wrote
+ * re-read into them, when the counts then account for every row (no deletion); else `read: null` and the caller reads
+ * whole. Either way S2's mark is the next round's.
+ */
+async function confirmPages(exec: Exec, input: { kind: 'postgres' | 'pglite'; sourceId: string; incarnation: string; parser: SyncImportParser;
+ prior: NonNullable<PassLevelCache['pages']>; proof: Promise<ConfirmProof> }, timed: <T>(key: string, read: () => Promise<T>) => Promise<T>) {
+ const proof = await input.proof, { table } = input.prior;
+ if (!proof.ok) return { read: null, mark: proof.mark, confirm: { taken: false, reason: proof.reason, rows: 0 } };
+ const want = new Set(proof.pages), slots = new Map<string, number>();
+ const step = loopYield();
+ for (let i = 0; i < table.length && slots.size < want.size; i++) {
+ if (want.has(String(table.id[i]))) slots.set(String(table.id[i]), i);
+ if (step.due()) await step.pause();
+ }
+ // An import record the pass wrote for a page that had none in S1 is a new row; one it rewrote was counted in S1.
+ const newRecords = [...proof.records].filter(id => !slots.has(id) || !table.hasRecord(slots.get(id)!)).length;
+ // `A` is the round's own read (readAttestations, after this): the previous round's proofs leave with it.
+ table.attested.clear();
+ const read = proof.pages.length ? await confirmGuard(timed('pages', () => readPages(exec, input.kind, input.sourceId, input.incarnation, input.parser, { table, ids: proof.pages, slots })))
+ : { pages: table, statements: 0 };
+ if (!read) return { read: null, mark: proof.mark, confirm: { taken: false, reason: 'page_left_level', rows: 0 } };
+ if (!countsMatch(input.prior.mark, proof, { pages: read.pages.length, newRecords })) return { read: null, mark: proof.mark, confirm: { taken: false, reason: 'counts', rows: 0 } };
+ return { read, mark: proof.mark, confirm: { taken: true, reason: null, rows: proof.pages.length } };
}
/** `H`: the source's holds of this incarnation, the retry set less what the pass consumed, and the holds whose basis or drift moved. */
diff --git a/test/e2e/sync-pass-confirm-6712-postgres.test.ts b/test/e2e/sync-pass-confirm-6712-postgres.test.ts
new file mode 100644
index 0000000000..c9df5a801c
--- /dev/null
+++ b/test/e2e/sync-pass-confirm-6712-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-pass-confirm-6712.test.ts'));
diff --git a/test/sync-pass-confirm-6712.test.ts b/test/sync-pass-confirm-6712.test.ts
new file mode 100644
index 0000000000..5d6bbc2cde
--- /dev/null
+++ b/test/sync-pass-confirm-6712.test.ts
@@ -0,0 +1,156 @@
+/**
+ * #6712 PR 4b lane A: the proof-carrying confirm round (sync-pass-confirm.ts). A pass's round after the first reuses the
+ * previous round's `I⋈P` and re-reads only the pages the pass wrote, when the database proves nothing else changed; any
+ * change it cannot attribute to the pass takes the whole read. Each probe forces the change between round 1 and round 2
+ * (the `sync:round_start` seam) and reads each round's verdict at `sync:level_read`.
+ *
+ * Protects:
+ * - the clean case: round 2 reuses `I⋈P` and re-reads only the written pages (one changed file, one new file).
+ * - a foreign page write over a pass import between rounds takes the whole read, and the page is not held (a stale reuse
+ * classifies the import again and holds it concurrent_write).
+ * - another writer moving HEAD between rounds takes the whole read, and the pass imports the new commit.
+ * - a foreign deletion of a hold between rounds takes the whole read.
+ * - #6887 through the confirm round: a both-moved path held file_drift in round 1 stays held in a reused round 2, and a path
+ * that moves on both sides between rounds is held file_drift (a stale reuse holds it concurrent_write), the edit kept.
+ *
+ * PGLite here; Postgres through test/e2e/sync-pass-confirm-6712-postgres.test.ts.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { readGitHold, SYNC_IMPORT_PROVENANCE_OP, writeGitHold } from '../src/core/persistence/sync-holds.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { RECOVERY_VERSION } from '../src/core/markdown.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { waitFor } from './helpers/wait-for.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const slug of ['a', 'b', 'c']) writeFileSync(join(root, `notes/${slug}.md`), note(`notes/${slug}`, `The committed body of notes/${slug}.`));
+ commit(root, 'notes');
+};
+const edit = (root: string, slug: string, body: string) => writeFileSync(join(root, `${slug}.md`), note(slug, body));
+const incarnationOf = async (engine: BrainEngine) => (await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text FROM sources WHERE id='default'"))[0]!.incarnation;
+const bodyOf = async (engine: BrainEngine, slug: string) => (await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth ?? '';
+/** A database-only edit of `slug` (write-through off), committed before it returns. */
+async function dbEdit(engine: BrainEngine, ctx: OperationContext, slug: string, body: string): Promise<void> {
+ await engine.setConfig('sync.write_through', 'false');
+ const requestId = randomUUID();
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: requestId,
+ expected_revision: (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision, content: note(slug, body) } });
+ await waitFor(async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.state === 'committed',
+ { timeoutMs: 30_000, label: `the database-only edit of ${slug} commits` });
+ await engine.setConfig('sync.write_through', 'true');
+}
+type Verdict = { round: number; confirm: { taken: boolean; reason: string | null; rows: number } | null };
+/** One sync with `between` run before round 2 reads its level; the rounds' confirm verdicts and the result. */
+async function pass(engine: BrainEngine, between: () => Promise<void> = async () => {}) {
+ const verdicts: Verdict[] = [];
+ let ran = false;
+ installFaultHook(async (point, detail) => {
+ if (point === 'sync:round_start' && detail.round === 2 && !ran) { ran = true; await between(); }
+ if (point === 'sync:level_read') verdicts.push({ round: detail.round!, confirm: detail.level?.confirm ?? null });
+ });
+ try {
+ const result = await performManagedSync(engine, OPTS);
+ return { status: result.status, held: (result.held ?? []).map(hold => [hold.path, hold.code]), verdicts };
+ } finally { installFaultHook(undefined); }
+}
+const round2 = (run: { verdicts: Verdict[] }) => run.verdicts.find(verdict => verdict.round === 2)?.confirm;
+
+afterEach(() => installFaultHook(undefined));
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ const brain = (run: Parameters<typeof managedBrain>[0]) => managedBrain(run, { ...(databaseUrl ? { databaseUrl } : {}), setup });
+
+ describe(`#6712 PR 4b confirm round (${backend})`, () => {
+ test('clean case: round 2 reuses I⋈P and re-reads only the pages the pass wrote', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ edit(root, 'notes/a', 'A committed change of notes/a.'); commit(root, 'change a');
+ const changed = await pass(engine);
+ expect({ status: changed.status, held: changed.held }).toEqual({ status: 'synced', held: [] });
+ expect(changed.verdicts[0]).toEqual({ round: 1, confirm: null });
+ expect(round2(changed)).toEqual({ taken: true, reason: null, rows: 1 });
+ expect(await bodyOf(engine, 'notes/a')).toContain('A committed change of notes/a.');
+ edit(root, 'notes/d', 'A new file.'); commit(root, 'add d');
+ const added = await pass(engine);
+ expect({ status: added.status, confirm: round2(added) }).toEqual({ status: 'synced', confirm: { taken: true, reason: null, rows: 1 } });
+ expect(await bodyOf(engine, 'notes/d')).toContain('A new file.');
+ expect((await performManagedSync(engine, OPTS)).pass).toBeUndefined();
+ }), 180_000);
+
+ test('a foreign page write over a pass import between rounds takes the whole read, and the page is not held', () => brain(async ({ engine, ctx, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ edit(root, 'notes/a', 'A committed change of notes/a.'); edit(root, 'notes/b', 'A committed change of notes/b.'); commit(root, 'change a and b');
+ const run = await pass(engine, () => dbEdit(engine, ctx, 'notes/b', 'DBONLYMARKER written after the import.'));
+ // The database moved after the file was imported (the file is unchanged since): nothing to import, nothing to hold.
+ expect({ status: run.status, held: run.held }).toEqual({ status: 'synced', held: [] });
+ expect(round2(run)).toEqual({ taken: false, reason: 'foreign_page_write', rows: 0 });
+ expect(await bodyOf(engine, 'notes/b')).toContain('DBONLYMARKER written after the import.');
+ expect(await readGitHold(engine, 'default', await incarnationOf(engine), 'notes/b.md')).toBeNull();
+ }), 180_000);
+
+ test('another writer moving HEAD between rounds takes the whole read, and the pass imports the new commit', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ edit(root, 'notes/a', 'A committed change of notes/a.'); commit(root, 'change a');
+ const run = await pass(engine, async () => { edit(root, 'notes/b', 'A commit landing mid-pass.'); commit(root, 'change b mid-pass'); });
+ expect(round2(run)).toEqual({ taken: false, reason: 'key', rows: 0 });
+ expect({ status: run.status, held: run.held }).toEqual({ status: 'synced', held: [] });
+ expect(await bodyOf(engine, 'notes/b')).toContain('A commit landing mid-pass.');
+ expect((await performManagedSync(engine, OPTS)).pass).toBeUndefined();
+ }), 180_000);
+
+ test('a foreign deletion of a hold between rounds takes the whole read', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ const incarnation = await incarnationOf(engine);
+ const page = (await engine.readPageSnapshot('notes/c', { sourceId: 'default' }))!;
+ await engine.transaction(tx => writeGitHold(tx, { source_id: 'default', incarnation, path: 'notes/c.md', source_path: 'notes/c.md', slug: 'notes/c', page_id: Number(page.page.id),
+ code: 'file_drift', message: 'Synthetic file_drift hold.', upstream_version: null, observed_at: new Date().toISOString(), run_id: null, mode: 'managed',
+ meta: { recovery_version: RECOVERY_VERSION, blob_oid: git(root, 'rev-parse', 'HEAD:notes/c.md'), page_revision: page.revision } } as never));
+ edit(root, 'notes/a', 'A committed change of notes/a.'); commit(root, 'change a');
+ const run = await pass(engine, async () => { await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-hold' AND fingerprint=$1", [`default:${incarnation}:notes/c.md`]); });
+ expect(round2(run)).toEqual({ taken: false, reason: 'holds', rows: 0 });
+ expect(run.status).toBe('synced');
+ expect(await readGitHold(engine, 'default', incarnation, 'notes/c.md')).toBeNull();
+ }), 180_000);
+
+ test('#6887 through the confirm round: a both-moved path held in round 1 stays held file_drift in the reused round 2', () => brain(async ({ engine, ctx, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await dbEdit(engine, ctx, 'notes/b', 'DBONLYMARKER the agent edit.');
+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug='notes/b'");
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_IMPORT_PROVENANCE_OP, `default:${await incarnationOf(engine)}:${page!.id}`]);
+ edit(root, 'notes/a', 'A committed change of notes/a.'); edit(root, 'notes/b', 'The second committed body.'); commit(root, 'change a and b');
+ const run = await pass(engine);
+ expect(round2(run)).toEqual({ taken: true, reason: null, rows: 1 });
+ expect({ status: run.status, held: run.held }).toEqual({ status: 'synced', held: [['notes/b.md', 'file_drift']] });
+ expect(await bodyOf(engine, 'notes/b')).toContain('DBONLYMARKER the agent edit.');
+ expect(readFileSync(join(root, 'notes/b.md'), 'utf8')).toContain('The second committed body.');
+ expect((await readGitHold(engine, 'default', await incarnationOf(engine), 'notes/b.md'))?.code).toBe('file_drift');
+ }), 180_000);
+
+ test('#6887 through the confirm round: a path that moves on both sides between rounds is held file_drift, the edit kept', () => brain(async ({ engine, ctx, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ edit(root, 'notes/a', 'A committed change of notes/a.'); commit(root, 'change a');
+ const run = await pass(engine, async () => {
+ await dbEdit(engine, ctx, 'notes/b', 'DBONLYMARKER a mid-pass edit.');
+ edit(root, 'notes/b', 'A committed change of notes/b mid-pass.'); commit(root, 'change b mid-pass');
+ });
+ expect({ status: run.status, held: run.held }).toEqual({ status: 'synced', held: [['notes/b.md', 'file_drift']] });
+ expect(round2(run)?.taken).toBe(false);
+ expect(await bodyOf(engine, 'notes/b')).toContain('DBONLYMARKER a mid-pass edit.');
+ expect((await readGitHold(engine, 'default', await incarnationOf(engine), 'notes/b.md'))?.code).toBe('file_drift');
+ }), 180_000);
+ });
+}