Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(#6712 PR 4b): pass checkpoint folded into the last import's publication; confirm-round classification reuse

garrytan31bb1b425aa9
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index fc99f874a5..0bb815706b 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -40,6 +40,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
// #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'
+ // #6712 PR 4b (#6926): inside the round's last import's publication, before its folded stamp's checks (sync-pass-fold.ts); a hook
+ // that throws models a failed check statement there: the stamp rolls back to its savepoint and the pass stamps by its checkpoint request.
+ | 'sync:pass_fold'
// #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'
@@ -56,7 +59,7 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
*/
/** `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;
- round?: number; level?: { statements: number; confirm: { taken: boolean; reason: string | null; rows: number } | null } }
+ round?: number; level?: { statements: number; confirm: { taken: boolean; reason: string | null; rows: number } | null; reused?: number } }
/** 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-group.ts b/src/core/persistence/sync-group.ts
index b4539811fb..d67941dacd 100644
--- a/src/core/persistence/sync-group.ts
+++ b/src/core/persistence/sync-group.ts
@@ -89,9 +89,12 @@ async function whole(engine: BrainEngine, env: string, key: string, fallback: nu
return Math.floor(raw);
}
-/** Entries a group may carry: plain page imports and deletes; renames, company plans, streamed pages (Wave B) and the checkpoint stay single. */
+/**
+ * Entries a group may carry: plain page imports and deletes; renames, company plans, streamed pages (Wave B), the checkpoint
+ * and a pass's last import carrying its folded stamp (#6926, folded into 4b: its proof admits its own page alone) stay single.
+ */
export function groupableIntent(intent: SyncIntent): boolean {
- return (intent.kind === 'managed_sync_import' || intent.kind === 'managed_sync_delete') && !intent.renameFrom && !intent.companyApproval && !intent.body_ref;
+ return (intent.kind === 'managed_sync_import' || intent.kind === 'managed_sync_delete') && !intent.renameFrom && !intent.companyApproval && !intent.body_ref && !intent.stamp;
}
/** Apply budgets for a lane group: normally, and while a foreground write on the worktree is queued or just committed. */
diff --git a/src/core/persistence/sync-pass-confirm.ts b/src/core/persistence/sync-pass-confirm.ts
index e5edf2a37a..643b334192 100644
--- a/src/core/persistence/sync-pass-confirm.ts
+++ b/src/core/persistence/sync-pass-confirm.ts
@@ -59,12 +59,15 @@ export async function readLevelMark(exec: Exec, sourceId: string, incarnation: s
/** Whether `col` (an xid) was committed before S1: it is older than S1's `xmin` (`age` of a frozen id is the largest). */
const unchanged = (col: string) => `age(${col}) > x.lo_age`;
-/** One scan of the source's pages and one of the incarnation's op rows: the counts, and the rows S1 does not prove unchanged. */
+/**
+ * One scan of the source's pages and one of the incarnation's op rows: the counts, and the rows S1 does not prove unchanged.
+ * `$6`: the request publishing in this transaction (a folded checkpoint, sync-pass-fold.ts), whose page is not committed yet.
+ */
const PROOF = `WITH x AS MATERIALIZED (SELECT txid_snapshot_xmin(txid_current_snapshot()) AS now_lo, txid_snapshot_xmax(txid_current_snapshot()) AS hi,
age(($4::bigint % 4294967296)::text::xid) AS lo_age),
pg AS (SELECT count(*) FILTER (WHERE p.source_path IS NOT NULL)::int AS n,
COALESCE(jsonb_agg(jsonb_build_array(p.id::text, EXISTS (SELECT 1 FROM persistence_requests r WHERE r.id=p.revision_write_request_id AND r.source_id=$1
- AND r.state='committed' AND r.intent->>'passId'=$5 AND r.outcome->>'revision'=p.knowledge_revision::text), p.knowledge_revision::text))
+ AND (r.id=$6::uuid OR r.state='committed' AND r.intent->>'passId'=$5 AND r.outcome->>'revision'=p.knowledge_revision::text)), p.knowledge_revision::text))
FILTER (WHERE NOT ${unchanged('p.xmin')}), '[]'::jsonb) AS changed
FROM pages p, x WHERE p.source_id=$1),
oc AS (SELECT o.op, count(*)::int AS n, jsonb_agg(jsonb_build_array(o.op, o.fingerprint, o.completed_keys->0->>'revision', o.completed_keys->0->>'run_id'))
@@ -86,14 +89,14 @@ export type ConfirmProof = { ok: true; mark: LevelMark; pages: string[]; records
* 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>; postgres: boolean }): Promise<ConfirmProof> {
+export async function proveConfirm(exec: Exec, input: { sourceId: string; incarnation: string; passId: string; base: LevelMark; recorded?: ReadonlySet<number>; postgres: boolean; self?: string }): Promise<ConfirmProof> {
const scope = `${input.sourceId}:${input.incarnation}`;
// Two plain scans: compiling them (JIT, which the planner's cost picks at 600k) cost more than running them (about 200 ms).
const jit = input.postgres ? exec.executeRaw('SET LOCAL jit = off') : Promise.resolve([]);
jit.catch(() => undefined);
const [row] = await exec.executeRaw<{ xmin: 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.passId]);
+ PROOF, [input.sourceId, CONFIRM_OPS, scope, input.base.xmin, input.passId, input.self ?? null]);
await jit;
const mark: LevelMark = { xmin: row!.xmin, ops: row!.ops ?? {}, holds: row!.holds };
if (!(Number(row!.span) >= 0 && Number(row!.span) < 2 ** 31)) return { ok: false, reason: 'xid_span', mark };
diff --git a/src/core/persistence/sync-pass-fold.ts b/src/core/persistence/sync-pass-fold.ts
new file mode 100644
index 0000000000..0d8b9fdb12
--- /dev/null
+++ b/src/core/persistence/sync-pass-fold.ts
@@ -0,0 +1,105 @@
+/**
+ * #6712 PR 4b: the pass checkpoint folded into the publication of the round's last import (#6926, folded into 4b; GBRA-108
+ * approved it under decision A's flip clause). The stamp rides that import's intent (sync-pass-run.ts `foldStamp`) and
+ * commits in the import's own transaction, after its page and record, only when the database there proves what the next
+ * round would have: every path at the target is settled. It is as conservative as the checkpoint request:
+ * - the checkpoint's own checks: the drain lease (`FOR SHARE`, the pass's token), the pass row still naming this pass, no
+ * recovery row and no other open managed-sync request of the worktree (`findOpenPassWork`), and the commit checkpoint
+ * (`last_commit`, the slug-root pin) still where the pass found it; and no refused checkpoint of the source that no later
+ * checkpoint superseded (#6834): the stamp path's checkpoint request supersedes it, a folded stamp would leave it listed;
+ * - `U_db` as the checkpoint records it: the converged watermark and `open_at_stamp` (`readConvergedWatermark`), read in
+ * the same transaction; this import publishes no file, so no Git effect of its own is left out of them;
+ * - since the round's mark (S1), every change the level reads is this round's own write (sync-pass-confirm.ts
+ * `proveConfirm`, with this request's uncommitted page admitted): exactly one page per import of the round, the pages
+ * past S1's largest id the round's new ones, the counts S1's plus the round's new pages and records, and no hold at S1
+ * or now (a hold at the target keeps the stamp path);
+ * - every page the round wrote classifies `matched` at the level its request froze (sync-pass.ts `passWritesMatched`);
+ * the rest of the level settled in the round's classification (the pass folds only a round whose only unsettled paths
+ * were its imports, sync-pass-run.ts).
+ * Anything else publishes the import alone (`pass_stamp_skipped` names why) and the pass stamps by its checkpoint request
+ * as before. The fold never fails the import on its own account: it runs under a savepoint, and a statement that fails
+ * there (a validation timeout, a lost race) rolls back to it and skips the stamp, as one it cannot prove is skipped. A publication that rolls back takes the stamp with it; one that commits leaves the stamp and the pages
+ * consistent for the next run.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { PreparedMutation } from './coordinator.ts';
+import type { WriteRequest } from './model.ts';
+import { syncLockId } from '../db-lock.ts';
+import { pipelined } from '../page-state/transactions.ts';
+import { findOpenPassWork } from './checkpoint-validation.ts';
+import { countsMatch, proveConfirm, type LevelMark } from './sync-pass-confirm.ts';
+import { passWritesMatched } from './sync-pass.ts';
+import { readConvergedWatermark } from './sync-pass-batch.ts';
+import { OPEN_AT_STAMP_CAP, readPassRow, type ManagedSyncPassValue } from './sync-pass-row.ts';
+import { emptySyncScope } from './sync-slug-mode.ts';
+import { faultPoint } from './fault-points.ts';
+import { supersessionSql } from './terminal-classify.ts';
+import { publishPassStamp, syncGitTopLevel, type SyncIntent } from './sync-prepare.ts';
+
+/** What a folded stamp's proof needs of its round: S1's mark, page count and largest page id, and the round's imports. */
+export interface PassFold {
+ base: LevelMark; pages: number; maxId: string;
+ /** The round's imports, those that create a page, and those whose page had no import record at S1. */
+ imports: number; newPages: number; newRecords: number;
+ episodeFullId: string | null; scope: string;
+ /** The pass row's obligations when the import was frozen: the stamp writes them, as the checkpoint request reads the row's. */
+ obligations?: ManagedSyncPassValue['obligations'];
+}
+
+/** `prepared` (the round's last import) with the stamp folded into its apply; a file write keeps the stamp path. */
+export function foldPassCheckpoint<T extends PreparedMutation>(prepared: T, input: { row: WriteRequest; p: SyncIntent; root: string }): T {
+ if (prepared.file || prepared.noop) return prepared;
+ const apply = prepared.apply.bind(prepared);
+ prepared.sourceExclusive = true;
+ prepared.apply = async (tx, preimage) => {
+ const outcome = await apply(tx, preimage);
+ const skipped = await foldedStamp(tx, input, outcome);
+ return { ...outcome, ...(skipped ? { pass_stamp_skipped: skipped } : { pass_stamp: 'folded' }) };
+ };
+ return prepared;
+}
+
+/** Publishes the stamp in `tx` when its checks hold; else why not (`error`: a statement failed, rolled back to the savepoint). */
+async function foldedStamp(tx: BrainEngine, input: { row: WriteRequest; p: SyncIntent; root: string }, outcome: Record<string, unknown>): Promise<string | null> {
+ await tx.executeRaw('SAVEPOINT gbrain_pass_stamp_fold');
+ try {
+ const skipped = await provenStamp(tx, input, outcome);
+ await tx.executeRaw(skipped ? 'ROLLBACK TO SAVEPOINT gbrain_pass_stamp_fold' : 'RELEASE SAVEPOINT gbrain_pass_stamp_fold');
+ return skipped;
+ } catch {
+ await tx.executeRaw('ROLLBACK TO SAVEPOINT gbrain_pass_stamp_fold');
+ return 'error';
+ }
+}
+
+async function provenStamp(tx: BrainEngine, { row, p, root }: { row: WriteRequest; p: SyncIntent; root: string }, outcome: Record<string, unknown>): Promise<string | null> {
+ const stamp = p.stamp!, fold = stamp.fold!, postgres = tx.kind === 'postgres';
+ const scope = { worktreeId: row.worktree_id!, sourceId: row.source_id, incarnation: row.source_incarnation };
+ await faultPoint('sync:pass_fold', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id });
+ const [lease, pass, blocker, watermark, sources, proof, refused] = await pipelined(tx, [
+ () => tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE', [syncLockId(row.source_id), stamp.leaseToken]),
+ () => readPassRow(tx, row.source_id, stamp.incarnation),
+ () => findOpenPassWork(tx, row.worktree_id!, row.request_id),
+ () => readConvergedWatermark(tx, scope, row.request_id, OPEN_AT_STAMP_CAP),
+ () => tx.executeRaw(`SELECT last_commit, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1 AND incarnation=$2::uuid`, [row.source_id, row.source_incarnation]),
+ () => proveConfirm(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, passId: p.passId!, base: fold.base, postgres, self: row.id }),
+ () => tx.executeRaw(`SELECT 1 FROM persistence_requests r WHERE r.source_id=$1 AND r.slug='__managed_sync_checkpoint__' AND r.intent IS NOT NULL AND NOT r.compacted
+ AND r.operation='submit_job' AND r.intent->>'kind'='managed_sync_checkpoint' AND r.state IN ('failed','conflict','cancelled')
+ AND NOT EXISTS (SELECT 1 FROM persistence_requests c WHERE ${supersessionSql('r', 'c')}) LIMIT 1`, [row.source_id]),
+ ]) as [unknown[], Awaited<ReturnType<typeof readPassRow>>, string | null, Awaited<ReturnType<typeof readConvergedWatermark>>, Array<{ last_commit: string | null; mode: string | null }>,
+ Awaited<ReturnType<typeof proveConfirm>>, unknown[]];
+ if (!lease.length || !pass || pass.value.lease_token !== stamp.leaseToken || pass.value.telemetry.pass_id !== p.passId) return 'lease';
+ if (blocker) return 'open_work';
+ if (refused.length) return 'refused_checkpoint';
+ const emptyScope = stamp.configured ? emptySyncScope(root, syncGitTopLevel(root, p.passId!)) : undefined;
+ const source = sources[0];
+ if (stamp.configured && (!source || (source.last_commit !== p.from && source.last_commit !== p.target) || (!emptyScope && source.mode !== null && source.mode !== p.slugMode))) return 'checkpoint_moved';
+ if (!proof.ok) return proof.reason;
+ if (fold.base.holds.length || proof.mark.holds.length || proof.summary) return 'holds';
+ if (proof.pages.length !== fold.imports || proof.pages.filter(id => BigInt(id) > BigInt(fold.maxId)).length !== fold.newPages) return 'pages';
+ if (!countsMatch(fold.base, proof, { pages: fold.pages + fold.newPages, newRecords: fold.newRecords })) return 'counts';
+ if (!await passWritesMatched(tx, { kind: postgres ? 'postgres' : 'pglite', sourceId: row.source_id, incarnation: row.source_incarnation, pack: stamp.pack, scope: fold.scope,
+ slugMode: p.slugMode, episodeFullId: fold.episodeFullId, ids: proof.pages })) return 'unsettled';
+ await publishPassStamp(tx, row, p, root, async () => {}, fold.obligations ? { value: { ...pass.value, obligations: fold.obligations } } : pass, { changed: stamp.changed + (outcome.noop === true ? 0 : 1), watermark, ...(emptyScope === undefined ? {} : { emptyScope }) });
+ return null;
+}
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 3e17637587..ee8c6ab90a 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -32,7 +32,8 @@ import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP
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 { passFoldBase, passIdleProbe, readShadowLevel, workingIdleChange, type PassLevelCache, type ShadowLevel, type ShadowPath } from './sync-pass.ts';
+import type { PassFold } from './sync-pass-fold.ts';
import { loopYield } from './sync-yield.ts';
import { recallWorkingStatCache, rememberWorkingStatCache, SyncTreeReadIncomplete } from './sync-git-stream.ts';
import { syncPassKind } from './sync-classify.ts';
@@ -512,6 +513,88 @@ function mismatchStreaks(before: ManagedSyncPassValue['obligations']['mismatch']
}
/** The pass of one managed, non-company source (module header). */
+/** The refused request a blocked pass stopped on, when it replays unchanged under the fail policy (#6712 PR 3, L7); else null. */
+async function unchangedBlockedRefusal(engine: BrainEngine, input: { sourceId: string; incarnation: string; root: string; head: string; blocked: { request_id: string; pass_id: string } }):
+ Promise<{ row: WriteRequest; intent: SyncIntent } | null> {
+ if ((await readSyncHoldPolicy(engine)).mode !== 'fail') return null;
+ const [found] = await engine.executeRaw<{ id: string }>('SELECT id FROM persistence_requests WHERE source_id=$1 AND request_id=$2', [input.sourceId, input.blocked.request_id]);
+ const row = found ? await getWriteRequestById(engine, found.id) : null;
+ const intent = row?.intent as unknown as SyncIntent | null | undefined;
+ if (!row || !intent || !['failed', 'conflict', 'cancelled'].includes(row.state)) return null;
+ const recorded = await recordedStop(engine, passFingerprint(input.sourceId, input.incarnation), input.blocked.pass_id);
+ return recorded && replaysUnchangedRefusal(row, recorded, { root: input.root, intent, target: intent.target ?? '', head: () => input.head }) ? { row, intent } : null;
+}
+
+/** Adds each present count of `add` to `counts`. */
+function addCounts(counts: Record<string, number>, add: Record<string, number | undefined>): void {
+ for (const [key, value] of Object.entries(add)) counts[key] = (counts[key] ?? 0) + (value ?? 0);
+}
+
+/** The pass stamp (design v3.2 §3.3): what its converged checkpoint publishes; closing the open episode counts what it released. */
+async function passStampFor(engine: BrainEngine, input: { context: ManagedSyncContext; head: string; slugMode: Cursor['slugMode']; episode: PassEpisode | undefined; selection: SyncSelection;
+ configured: boolean; mode: SyncSelection['mode']; leaseToken: string; retry: string[]; level: ShadowLevel; selectionFp: string; parserFp: string; pack: string | null; full: boolean;
+ counts: { added: number; modified: number; deleted: number; renamed: number; episodeReleased: number }; extract: boolean; since: string; rescreen: boolean }): Promise<PassStamp> {
+ const { context, episode, configured, counts } = input;
+ // Design §6: an open episode closes by inclusion (a) or at the configured selection (b); chunker_version only by (b) over U_config.
+ const closure = episode ? await passEpisodeClosure({ gitRoot: context.gitRoot, root: context.root, head: input.head, slugMode: input.slugMode, episode, pass: input.selection, configured,
+ configuredSelection: passSelection(await selectionPatterns(engine, { sourceId: context.sourceId } as SyncOpts), { sourceId: context.sourceId } as SyncOpts, context, input.mode) }) : null;
+ const closesEpisode = closure?.closes === true;
+ if (closure?.released) counts.episodeReleased = closure.released;
+ return { leaseToken: input.leaseToken, incarnation: context.incarnation, configured, stampChunker: configured && (context.source.last_commit === null || (closesEpisode && !!episode?.full_id && closure!.stampChunker)),
+ closesEpisode, retryTaken: [...input.retry], releasedHolds: input.level.releasableHolds, selectionFp: input.selectionFp, parserFp: input.parserFp, pack: input.pack, full: input.full,
+ changed: counts.added + counts.modified + counts.deleted + counts.renamed, extract: input.extract, since: input.since, ...(input.rescreen ? { rescreen: true as const } : {}) };
+}
+
+/**
+ * #6926, folded into 4b: the round's fold (sync-pass-fold.ts), when its last import may carry the stamp; null keeps the stamp
+ * path. A committed-mode local round folds only when its imports were its only unsettled paths: no delete, rename,
+ * collision, in-flight write, owed or mismatched path, legacy waiver or retry row, no hold at S1 and none on an import, no
+ * marker or spelling on one, and a marked `I⋈P` to prove against.
+ */
+function passFold(level: ShadowLevel, cache: PassLevelCache, round: { imports: ShadowPath[]; entries: PassEntry[]; unsettled: number; remote: boolean; episodeFullId: string | null }): PassFold | null {
+ const base = !round.remote && level.mode === 'committed' && !round.unsettled ? passFoldBase(cache) : null;
+ if (!base || base.mark.holds.length || !round.imports.length || round.entries.length !== round.imports.length || round.entries.some(entry => entry.action !== 'import' || entry.renameFrom)) return null;
+ if (round.imports.some(entry => entry.state.hold || entry.state.marker || entry.state.spelling)) return null;
+ return { base: base.mark, pages: base.pages, maxId: base.maxId, imports: round.imports.length, newPages: round.imports.filter(entry => entry.pageId === null).length,
+ newRecords: round.imports.filter(entry => entry.state.record === null).length, episodeFullId: round.episodeFullId, scope: level.scope };
+}
+
+/** After a folded stamp: the pass row's obligations as the stamp left them (converged, the closed episode and the resets). */
+async function adoptStampedObligations(engine: BrainEngine, value: ManagedSyncPassValue): Promise<void> {
+ const stamped = (await readPassRow(engine, value.source_id, value.incarnation))?.value.obligations;
+ if (!stamped) return;
+ for (const key of Object.keys(value.obligations)) if (!(key in stamped)) delete (value.obligations as Record<string, unknown>)[key];
+ Object.assign(value.obligations, stamped);
+}
+
+/** Pins the pass row under the drain lease; true when a caller abort stopped the pin (a job abort or a lost lease throws, leaving no row). */
+async function pinPassRow(engine: BrainEngine, value: ManagedSyncPassValue, input: SyncPassInput): Promise<boolean> {
+ try {
+ await engine.transaction(async tx => {
+ // The lease check and the clock read share a round trip: a lost lease aborts the transaction before the row is written.
+ [, value.telemetry.started_at] = await Promise.all([assertDrainLease(tx, input.context.sourceId), databaseNow(tx)]);
+ await writePassRow(tx, value, { pin: true });
+ // An interrupt during the pin rolls the pin back with it: no `open` row is left for a pass that never ran.
+ input.assertActive();
+ });
+ return false;
+ } catch (error) {
+ assertSyncDispatchActive();
+ if (input.signal?.aborted && error instanceof Error && error.name === 'AbortError') return true;
+ throw error;
+ }
+}
+
+/** Design §7 (v3 §7): whether this batch crossed the approved envelope, which defers embeddings for the rest of the pass. */
+async function envelopeCrossed(engine: BrainEngine, value: ManagedSyncPassValue, costScope: string, processingOptions: SyncProcessingOptions): Promise<boolean> {
+ const envelope = value.obligations.cost;
+ if (!envelope) return false;
+ envelope.reserved_usd = (await readReservedUsd(engine, value.source_id, value.incarnation, costScope)).usd;
+ if (processingOptions.noEmbed || envelope.approved_usd === null || envelope.reserved_usd <= 0 || envelope.reserved_usd < envelope.approved_usd) return false;
+ processingOptions.noEmbed = true;
+ return true;
+}
+
export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Promise<SyncResult> {
const { opts, context, authority, assertActive } = input;
const { sourceId, incarnation } = context;
@@ -559,6 +642,11 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const rememberLevel = () => { if (lastLevel?.workingCache) rememberWorkingStatCache(cacheKey, lastLevel.workingCache); };
const applied = newPassApplyState();
const readmitted = new Set<string>();
+ // #6926, folded into 4b: the head a round's last import stamped, and what the pass had done by then.
+ let folded: { head: string; done: string } | null = null, batchFolded = false;
+ const doneKey = () => JSON.stringify([counts, passApplyCounts(applied)]);
+ const stampFor = (level: ShadowLevel) => passStampFor(engine, { context, head, slugMode: levelSlugMode, episode, selection, configured, mode, leaseToken: lease.token, retry, level, selectionFp, parserFp,
+ pack, full: kind === 'full', counts, extract: !processingOptions.noExtract, since: value.telemetry.started_at, rescreen: legacyWaived.size > 0 });
const save = async (outcome: PassOutcome, stopReason: string | null, pin = false) => {
const ended = outcome !== 'open';
@@ -579,26 +667,13 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
...(sizeStates ? { size_states: sizeStates } : {}), ...(keptCount() ? { working_tree_kept: keptCount() } : {}),
pass: { pass_id: passId, kind, round: value.telemetry.round, outcome: value.telemetry.outcome, stop_reason: value.telemetry.stop_reason, candidates: candidatesFirst,
settled: S.size + yieldSettled, remaining: value.telemetry.remaining, not_converged_streak: value.obligations.not_converged_streak } });
- try {
- await engine.transaction(async tx => {
- // The lease check and the clock read share a round trip: a lost lease aborts the transaction before the row is written.
- [, value.telemetry.started_at] = await Promise.all([assertDrainLease(tx, sourceId), databaseNow(tx)]);
- await writePassRow(tx, value, { pin: true });
- // An interrupt during the pin rolls the pin back with it: no `open` row is left for a pass that never ran.
- assertActive();
- });
- } catch (error) {
- // A caller abort records the stop on the pass row (the pin it rolled back is replaced); a job abort, a lost lease or a
- // released context leaves no row.
- assertSyncDispatchActive();
- if (input.signal?.aborted && error instanceof Error && error.name === 'AbortError') { await save('resumable', 'timeout', true).catch(() => undefined); return result('partial', 'timeout'); }
- throw error;
- }
+ // A caller abort records the stop on the pass row (the pin it rolled back is replaced).
+ if (await pinPassRow(engine, value, input)) { await save('resumable', 'timeout', true).catch(() => undefined); return result('partial', 'timeout'); }
assertActive();
registerPassCost(passId, { sourceId, incarnation, scope: costScope, pricePerMTok: currentEmbeddingPricePerMTok() });
/** The batch cursor sync-run.ts drains: the discovery shape with no cursor row behind it. */
const batchCursor = (entries: PassEntry[], stamp?: PassStamp): Cursor => ({ binding: { ...context.binding, owner_epoch: String(context.binding.owner_epoch), topology_generation: String(context.binding.topology_generation) },
- root: context.root, gitRoot: context.gitRoot, sourceId, incarnation, from: context.source.last_commit, target: head, entries, slugMode: levelSlugMode, discoveredAt: startedAt,
+ root: context.root, gitRoot: context.gitRoot, sourceId, incarnation, from: folded?.head ?? context.source.last_commit, target: head, entries, slugMode: levelSlugMode, discoveredAt: startedAt,
runId: passId, passId, index: 0, authority, processingOptions, syncOptions: input.syncOptions, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 },
failureKey: passFingerprint(sourceId, incarnation), resumeArgs: passResumeArgs(sourceId, { value, updated_at: startedAt }), ...(episode?.full_id ? { fullEpisode: episode.full_id } : {}), ...(stamp ? { stamp } : {}) });
let levelSlugMode: Cursor['slugMode'] = 'git-root';
@@ -610,9 +685,9 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const drained = await input.drainBatch(key, batch, sliceBase);
if ('entries' in drained) {
const c = drained.counts;
- Object.assign(counts, { added: counts.added + c.added, modified: counts.modified + c.modified, deleted: counts.deleted + c.deleted, renamed: counts.renamed + (c.renamed ?? 0),
- chunks: counts.chunks + c.chunks, waivedImports: counts.waivedImports + (c.waived?.imports ?? 0), waivedDeletes: counts.waivedDeletes + (c.waived?.deletes ?? 0), held: counts.held + (c.held ?? 0),
- skippedContextualMode: counts.skippedContextualMode + (c.skippedContextualMode ?? 0), skippedCanonicalBytes: counts.skippedCanonicalBytes + (c.skippedCanonicalBytes ?? 0) });
+ batchFolded = c.folded === true;
+ addCounts(counts, { added: c.added, modified: c.modified, deleted: c.deleted, renamed: c.renamed, chunks: c.chunks, waivedImports: c.waived?.imports, waivedDeletes: c.waived?.deletes,
+ held: c.held, skippedContextualMode: c.skippedContextualMode, skippedCanonicalBytes: c.skippedCanonicalBytes });
for (const index of drained.passLegacyWaived ?? []) legacyWaived.add(settledKey(entries[index]!.path, entries[index]!.level));
sliceBase.pages += drained.index;
roundSettled += drained.index;
@@ -621,11 +696,17 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
}
return drained;
};
+ /** The pass ended on its stamp; a folded one (sync-pass-fold.ts) saves the round's telemetry beside the obligations it wrote. */
+ const synced = async (onFold: boolean): Promise<SyncResult> => {
+ if (onFold) await save('synced', configured ? null : 'selection_scoped');
+ rememberLevel();
+ await clearPassFailures(engine, sourceId, incarnation);
+ await finishPassApply(engine, sourceId, applied);
+ return result(configured && context.source.last_commit === null ? 'first_sync' : 'synced', configured ? undefined : 'selection_scoped');
+ };
const stop = async (drained: SyncResult): Promise<SyncResult> => {
- Object.assign(counts, { added: counts.added + drained.added, modified: counts.modified + drained.modified, deleted: counts.deleted + drained.deleted,
- renamed: counts.renamed + drained.renamed, chunks: counts.chunks + drained.chunksCreated, waivedImports: counts.waivedImports + (drained.waived?.imports ?? 0),
- waivedDeletes: counts.waivedDeletes + (drained.waived?.deletes ?? 0), skippedContextualMode: counts.skippedContextualMode + (drained.legacySkips?.contextualMode ?? 0),
- skippedCanonicalBytes: counts.skippedCanonicalBytes + (drained.legacySkips?.canonicalBytes ?? 0) });
+ addCounts(counts, { added: drained.added, modified: drained.modified, deleted: drained.deleted, renamed: drained.renamed, chunks: drained.chunksCreated, waivedImports: drained.waived?.imports,
+ waivedDeletes: drained.waived?.deletes, skippedContextualMode: drained.legacySkips?.contextualMode, skippedCanonicalBytes: drained.legacySkips?.canonicalBytes });
sliceBase.pages += drained.filesImported ?? 0;
foldReport(drained.size_states);
// A slice that stops mid-batch (a writer yield, a deadline, an abort) settled the entries its cursor passed: they count as
@@ -648,18 +729,13 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
// Under the hold policy the next pass re-admits it instead, and its refusal settles as a hold.
const blocked = obligations.blocked;
delete obligations.blocked;
- if (blocked && (await readSyncHoldPolicy(engine)).mode === 'fail') {
- const [row] = await engine.executeRaw<{ id: string }>('SELECT id FROM persistence_requests WHERE source_id=$1 AND request_id=$2', [sourceId, blocked.request_id]);
- const failed = row ? await getWriteRequestById(engine, row.id) : null;
- const intent = failed?.intent as unknown as SyncIntent | null | undefined;
- const recorded = failed && intent && ['failed', 'conflict', 'cancelled'].includes(failed.state) ? await recordedStop(engine, passFingerprint(sourceId, incarnation), blocked.pass_id) : null;
- assertActive();
- if (failed && intent && recorded && replaysUnchangedRefusal(failed, recorded, { root: context.root, intent, target: intent.target ?? '', head: () => head })) {
- obligations.blocked = blocked;
- const replay: Cursor = { ...batchCursor([]), runId: blocked.pass_id, pending: { requestId: failed.request_id, slug: failed.slug, pageId: failed.page_id, intent } };
- const drained = await input.drainBatch(`${PASS_BATCH_KEY_PREFIX}${passId}:${batchNo++}`, replay, sliceBase);
- if (!('entries' in drained)) return await stop(drained);
- }
+ const failed = blocked ? await unchangedBlockedRefusal(engine, { sourceId, incarnation, root: context.root, head, blocked }) : null;
+ assertActive();
+ if (failed) {
+ obligations.blocked = blocked;
+ const replay: Cursor = { ...batchCursor([]), runId: blocked!.pass_id, pending: { requestId: failed.row.request_id, slug: failed.row.slug, pageId: failed.row.page_id, intent: failed.intent } };
+ const drained = await input.drainBatch(`${PASS_BATCH_KEY_PREFIX}${passId}:${batchNo++}`, replay, sliceBase);
+ if (!('entries' in drained)) return await stop(drained);
}
// The pass's level cache: its next round at the same commit reuses the tree; it dies with the pass.
const levelCache: PassLevelCache = {};
@@ -673,7 +749,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
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, passId, recorded: applied.recorded } });
- await faultPoint('sync:level_read', { sourceId, round, level: level ? { statements: level.statements, confirm: level.confirm ?? null } : undefined });
+ await faultPoint('sync:level_read', { sourceId, round, level: level ? { statements: level.statements, confirm: level.confirm ?? null, reused: level.reused ?? 0 } : 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
@@ -744,23 +820,14 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
await finishPassApply(engine, sourceId, applied);
return { ...result('up_to_date'), fromCommit: remote ? null : head };
}
- // Design §6: an open episode closes by inclusion (a) or at the configured selection (b); chunker_version only by (b) over U_config.
- const closure = episode ? await passEpisodeClosure({ gitRoot: context.gitRoot, root: context.root, head, slugMode: levelSlugMode, episode, pass: selection, configured,
- configuredSelection: passSelection(await selectionPatterns(engine, { sourceId } as SyncOpts), { sourceId } as SyncOpts, context, mode) }) : null;
- const closesEpisode = closure?.closes === true;
- if (closure?.released) counts.episodeReleased = closure.released;
- const stamp: PassStamp = { leaseToken: lease.token, incarnation, configured, stampChunker: configured && (context.source.last_commit === null || (closesEpisode && !!episode?.full_id && closure!.stampChunker)),
- closesEpisode, retryTaken: [...retry], releasedHolds: level.releasableHolds, selectionFp, parserFp, pack, full: kind === 'full',
- changed: counts.added + counts.modified + counts.deleted + counts.renamed, extract: !processingOptions.noExtract, since: value.telemetry.started_at,
- ...(legacyWaived.size ? { rescreen: true as const } : {}) };
+ // #6926: a round after a folded stamp that confirmed the level and did nothing more ends on that stamp.
+ if (folded?.head === head && level.confirm?.taken && !applied.recorded.size && folded.done === doneKey()) return synced(true);
+ const stamp = await stampFor(level);
await save('open', null);
const stopped = await drain([], stamp);
if (stopped) return stop(stopped);
value.telemetry = { ...value.telemetry, outcome: 'synced', stop_reason: configured ? null : 'selection_scoped', remaining: 0 };
- rememberLevel();
- await clearPassFailures(engine, sourceId, incarnation);
- await finishPassApply(engine, sourceId, applied);
- return result(configured && context.source.last_commit === null ? 'first_sync' : 'synced', configured ? undefined : 'selection_scoped');
+ return synced(false);
}
const built = await batchEntries(engine, level, deletes, imports).catch(async (error: unknown) => {
if ((error as { code?: string }).code === 'page_identity_changed') await save('blocked', 'page_identity_changed');
@@ -774,17 +841,16 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (optOutEpisode && !value.obligations.episode && built.entries.length) value.obligations.episode = episode = optOutEpisode;
// #6694: the mode this pass publishes pages under is recorded before the first of them, so a pin changed before the stamp refuses there.
if (level.scope && built.entries.length && !value.obligations.slug_mode) { value.obligations.slug_mode = level.slugMode; await save('open', null); }
+ const fold = passFold(level, levelCache, { imports, entries: built.entries, unsettled: deletes.length + inFlight.length + owed.length + mismatch.length + legacyWaived.size + retry.length,
+ remote, episodeFullId: episode?.full_id ?? null });
for (let i = 0; i < built.entries.length; i += PASS_BATCH_MAX) {
- const chunk = built.entries.slice(i, i + PASS_BATCH_MAX);
- const stopped = await drain(chunk);
+ const chunk = built.entries.slice(i, i + PASS_BATCH_MAX), last = !!fold && i + chunk.length >= built.entries.length;
+ // A folded stamp writes the pass row with the obligations as they stand when its import is frozen.
+ const stopped = await drain(chunk, last ? { ...await stampFor(level), fold: { ...fold, obligations: structuredClone(value.obligations) } } : undefined);
if (stopped) return stop(stopped);
value.telemetry.remaining = Math.max(0, built.entries.length - i - chunk.length) + inFlight.length + owed.length + mismatch.length;
- // Design §7 (v3 §7): crossing the approved envelope defers embeddings for the rest of the pass.
- const envelope = value.obligations.cost;
- if (envelope) {
- envelope.reserved_usd = (await readReservedUsd(engine, sourceId, incarnation, costScope)).usd;
- if (!processingOptions.noEmbed && envelope.approved_usd !== null && envelope.reserved_usd > 0 && envelope.reserved_usd >= envelope.approved_usd) { processingOptions.noEmbed = true; counts.costDeferred = 1; }
- }
+ if (await envelopeCrossed(engine, value, costScope, processingOptions)) counts.costDeferred = 1;
+ if (last && batchFolded) { await adoptStampedObligations(engine, value); folded = { head, done: doneKey() }; continue; } // the stamp wrote the pass row
await save('open', null);
}
// Every candidate of the round settled: committed, waived, held, deferred to a hold, a collision, or (a rename's
@@ -804,7 +870,11 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
} catch (error) {
assertSyncDispatchActive();
if (error instanceof SyncAdmissionPaused) { await save('resumable', 'admission_paused').catch(() => undefined); return result('partial', 'admission_paused'); }
- if (input.signal?.aborted && error instanceof Error && error.name === 'AbortError') { await save('resumable', 'timeout').catch(() => undefined); return result('partial', 'timeout'); }
+ if (input.signal?.aborted && error instanceof Error && error.name === 'AbortError') {
+ // A folded stamp with nothing since ended the pass: the abort stops nothing it owes.
+ if (folded?.done === doneKey()) return synced(true);
+ await save('resumable', 'timeout').catch(() => undefined); return result('partial', 'timeout');
+ }
// A Git listing that did not finish cleanly classifies nothing (design v3.2 §9): the pass stops blocked, having written nothing for that round.
if (error instanceof SyncTreeReadIncomplete) { await save('blocked', 'reconcile_read_incomplete').catch(() => undefined); return result('blocked_by_failures', 'reconcile_read_incomplete'); }
throw error;
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index 6c41cf897b..0e4cf62acf 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -74,12 +74,13 @@ export interface PassLevelInput {
/** PGLite's keyset page size (design v3.2 §2.1). */
const PGLITE_KEYSET_ROWS = 2_000;
/**
- * Rows per `FETCH` of Postgres's `I⋈P` cursor, `POSTGRES_FETCHES_AHEAD` in flight. A result decodes in one stretch the
- * event loop cannot break (about 4 µs a row: one 25k-row fetch held timers for about 100 ms at 600k pages), and the read
- * yields a timer turn between results, so fetches that arrived together still decode one stretch each; the fetches queued
- * behind keep their round trips off the read's critical path.
+ * Rows per `FETCH` of Postgres's `I⋈P` cursor, `POSTGRES_FETCHES_AHEAD` in flight. The driver decodes every row that
+ * reached the socket in one read as one stretch the event loop cannot break (about 4.4 µs a row), and the read's decode is
+ * slower than the server, so the results in flight arrive together: their rows bound the stretch. 16k rows in flight
+ * decode in about 70 ms (4 × 8k held timers for 135 ms at 600k pages and 5 ms RTT) and still take longer to decode than a
+ * 57 ms round trip, so the queued fetches keep the round trips off the read's critical path.
*/
-const POSTGRES_FETCH_ROWS = 8_000, POSTGRES_FETCHES_AHEAD = 4;
+const POSTGRES_FETCH_ROWS = 4_000, POSTGRES_FETCHES_AHEAD = 4;
/** Blob bytes read for adoption by hash and the screen, per blob. */
const LEVEL_BLOB_MAX_BYTES = 8 * 1024 * 1024;
const SYNC_WRITE_KINDS = ['managed_sync_import', 'managed_sync_delete'];
@@ -89,6 +90,8 @@ 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 };
+ /** The last committed-mode round's classified paths, keyed by every level-wide input the classifier reads (`classifiedKey`). */
+ classified?: { key: string; treeKey: string; paths: ShadowPath[] };
}
/**
@@ -135,7 +138,7 @@ export interface ShadowPath { path: string; slug: string | null; pageId: number
*/
class MatchedPath implements ShadowPath {
constructor(public path: string, public slug: string | null, public pageId: number | null, public revision: string, public result: SyncClassified,
- private readonly treeOid: string | null, private readonly levelOid: string, private readonly dirty: SyncPathState['dirty'], private readonly diskRecorded: boolean,
+ readonly treeOid: string | null, readonly levelOid: string, private readonly dirty: SyncPathState['dirty'], private readonly diskRecorded: boolean,
private readonly shared: { mode: SyncPathState['mode']; fullObligation: boolean }) {}
/** Whether `state` is the one `state` would rebuild for a page at `revision`. */
@@ -163,6 +166,69 @@ class MatchedPath implements ShadowPath {
/** Whether `entry` is a compact converged `matched` path: its state is a live page at its level, with no marker, hold or open work. */
export const isCompactMatched = (entry: ShadowPath): boolean => entry instanceof MatchedPath;
+/**
+ * A taken confirm round's classification reuse: the previous round's compact `matched` path, kept when nothing the
+ * classifier reads for it can have changed; any other path is classified again. The level-wide inputs are the cache key
+ * (`classified.key`: the commit and selection, the mode, the episode and full obligation, mirror and keep_db, the schema
+ * pack, the baseline commit, the bootstrap and the ':' refusals). The per-path inputs are `unchanged`'s test, each read
+ * from this round (`matchedUnchanged`). The entry's result must be the classifier's own (frozen; one the previous round's
+ * apply settled over is not). The walk follows both rounds' sorted order.
+ */
+function reusableMatched(prior: ShadowPath[], unchanged: (entry: MatchedPath) => boolean): (path: string) => MatchedPath | undefined {
+ let k = 0;
+ return path => {
+ while (k < prior.length && prior[k]!.path < path) k++;
+ const entry = prior[k];
+ return entry instanceof MatchedPath && entry.path === path && Object.isFrozen(entry.result) && entry.result.cls === 'matched' && unchanged(entry) ? entry : undefined;
+ };
+}
+
+/**
+ * The per-path inputs of a reused `matched` path, as this round read them:
+ * - `I⋈P`: the confirm round did not re-read the origin's page (`changed`: a rewritten page's old and new origin, a new
+ * page's), the origin has one claimant and it is the entry's page, and this round's `A` read nothing for it;
+ * - `T`: the tree entry is the entry's (the same commit, so it is; checked anyway);
+ * - `X`: the index does not differ from `T` at the path (a staged path is a dirtiness candidate);
+ * - `U_db`: no open request or pending Git effect names the page or the origin;
+ * - holds and markers: none at the path or its origin (a hold's re-screen, retry and moved basis come with it);
+ * - spelling: the path is no spelling twin and no settled legacy spelling.
+ * A `matched` path has no attestation, disk bytes, baseline or withheld delete, and its episode, keep_db and parser
+ * verdicts come from its page and the key.
+ */
+function matchedUnchanged(level: { pages: PageTable; tree: Map<string, GitTreeEntry>; byOrigin: Map<string, number>; claimants: Map<string, number[]>; changed: Set<string>;
+ holds: Map<string, unknown>; markers: Map<string, unknown>; open: { pageIds: Set<number>; origins: Set<string> }; indexDelta: Map<string, unknown> | null;
+ spelled: (path: string) => boolean; originOf: (path: string) => string }): (entry: MatchedPath) => boolean {
+ return entry => {
+ const path = entry.path, at = level.byOrigin.get(path);
+ if (at === undefined || Number(level.pages.id[at]) !== entry.pageId || level.pages.attested.has(at) || level.claimants.has(path) || level.changed.has(path)) return false;
+ if (level.tree.get(path)?.oid !== entry.levelOid || entry.treeOid !== entry.levelOid) return false;
+ if (level.holds.has(path) || level.indexDelta?.has(path) || level.spelled(path) || level.open.pageIds.has(entry.pageId!)) return false;
+ if (!level.markers.size && !level.open.origins.size) return true;
+ const origin = level.originOf(path);
+ return !level.markers.has(origin) && !level.open.origins.has(origin);
+ };
+}
+
+/** The origins (`keyOf`) whose page a confirm round re-read: a rewritten page's previous and current one, and each new page's. */
+function confirmChangedPaths(pages: PageTable, changed: { rewritten: Array<{ slot: number; sourcePath: string; slug: string }>; from: number }, keyOf: (sourcePath: string, slug: string) => string): Set<string> {
+ const paths = new Set<string>();
+ for (const row of changed.rewritten) { paths.add(keyOf(row.sourcePath, row.slug)); paths.add(keyOf(pages.sourcePath[row.slot]!, pages.slug[row.slot]!)); }
+ for (let i = changed.from; i < pages.length; i++) paths.add(keyOf(pages.sourcePath[i]!, pages.slug[i]!));
+ return paths;
+}
+
+/** The path's level `L`: committed mode's tree blob, working mode's probe verdict (design v3.2 §2.1). */
+function levelReader(mode: 'committed' | 'working', tree: Map<string, GitTreeEntry>, root: string, scope: string) {
+ return (path: string, probe: { dp: string; rawOid: string | null; rawSha256: string | null } | undefined): string | null => {
+ const committed = tree.get(path) ?? null;
+ return mode === 'committed' ? committed?.oid ?? null
+ : !probe || probe.dp === 'deleted' ? null
+ : ['clean', 'clean_eol', 'clean_lfs'].includes(probe.dp) ? committed?.oid ?? probe.rawOid
+ // A path in neither T nor the index (untracked) or only staged has no `deleted` verdict: no bytes and no file is absent.
+ : probe.rawOid ?? (probe.rawSha256 === null && !readPresent(root, path, scope) ? null : `unreadable:${path}`);
+ };
+}
+
export interface ShadowLevel {
sourceId: string; incarnation: string; root: string; gitRoot: string; scope: string; slugMode: 'git-root' | 'source-root';
mode: 'committed' | 'working'; head: string; baselineCommit: string | null; full: boolean;
@@ -187,6 +253,8 @@ export interface ShadowLevel {
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 taken confirm round: the paths whose previous-round classification it kept (`reusableMatched`). */
+ reused?: 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. */
@@ -518,6 +586,9 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
// A commit's tree never changes: the pass's next round at the same commit and selection reuses the eligible tree.
const treeKey = JSON.stringify([gitRoot, head, scope, slugMode, strategy, exclude, includeHidden]);
const cache = input.pass?.cache;
+ // The previous round's classification leaves the cache before anything can fail (only a complete round's is stored).
+ let priorClassified = cache?.classified?.treeKey === treeKey ? cache.classified : undefined;
+ if (cache) cache.classified = undefined;
// The tree's ':' paths (#5032) are kept apart: they are refused, never part of the level.
const eligibleTree = async (): Promise<{ tree: Map<string, GitTreeEntry>; colon: string[] }> => {
if (cache?.tree?.key === treeKey) return cache.tree;
@@ -594,14 +665,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const probes = hashed?.probes ?? new Map();
timings.Dp = t();
- const levelOf = (path: string, probe: { dp: string; rawOid: string | null; rawSha256: string | null } | undefined): string | null => {
- const committed = tree.get(path) ?? null;
- return mode === 'committed' ? committed?.oid ?? null
- : !probe || probe.dp === 'deleted' ? null
- : ['clean', 'clean_eol', 'clean_lfs'].includes(probe.dp) ? committed?.oid ?? probe.rawOid
- // A path in neither T nor the index (untracked) or only staged has no `deleted` verdict: no bytes and no file is absent.
- : probe.rawOid ?? (probe.rawSha256 === null && !readPresent(root, path, scope) ? null : `unreadable:${path}`);
- };
+ const levelOf = levelReader(mode, tree, root, scope);
// `A` only matters where the file or the database moved (no row settles on `fileSame ∧ dbSame` with a proof): read it
// for those pages alone, so a converged source reads none. The same walk finds whether any path needs the baseline tree.
t = timer();
@@ -693,13 +757,21 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
}).then(found => { timings.legacy = t(); return found; })
: new Map<string, string>();
+ const classifiedKey = JSON.stringify([treeKey, mode, input.pass?.episodeFullId ?? null, input.full === true, mirror, keepDbPrefixes, pack?.identity ?? null, baselineCommit, !!input.pass?.bootstrap, [...colonRefused].sort()]);
+ const reuse = snapshot.changed && priorClassified?.key === classifiedKey ? reusableMatched(priorClassified.paths, matchedUnchanged({ pages, tree, byOrigin, claimants, holds: holdByGitPath, markers, open,
+ changed: confirmChangedPaths(pages, snapshot.changed, (sourcePath, slug) => gitPathOf(pageOrigin(sourcePath, slug))), indexDelta, spelled: path => twins.has(path) || legacySpelling.has(path), originOf })) : null;
+ // A round that reuses nothing lets the previous round's paths go before it builds its own: one level held, not two.
+ if (!reuse) priorClassified = undefined;
t = timer();
const paths: ShadowPath[] = [];
+ let reused = 0;
const candidates: string[] = [], candidateAt: number[] = [];
const settledBeforeDirtiness = new Set(['held', 'spelling', 'untracked', 'kept', 'delete', 'delete_drift', 'gone', 'deleted_same', 'deleted_edited', 'legacy_same', 'matched']);
const shared = { mode, fullObligation: input.pass ? !!input.pass.episodeFullId : input.full === true };
for (const path of await sortYielding([...domain], step)) {
if (step.due()) await step.pause();
+ const kept = reuse?.(path);
+ if (kept) { byOrigin.delete(path); paths.push(kept); reused++; continue; }
const probe = probes.get(path);
const { state, at, legacyPageless } = stateOf(path, mode === 'committed' && tree.has(path) ? 'clean' : null, probe);
const result = sharedResult(classifySyncPath(state));
@@ -757,10 +829,11 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
retryRow: retry.size > 0, notConvergedStreak: 0, mismatchStreak: 0, requestNewer: false, openAtStampFinished: false, workingChange: false,
rescreenDueHold: holds.some(hold => holdRescreenDue(hold, retry.has(hold.path))), full: input.full === true });
timings.total = total();
+ if (cache && mode === 'committed') cache.classified = { key: classifiedKey, treeKey, paths };
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, ...(confirm ? { confirm } : {}), pack: pack?.identity ?? null,
+ paths, reconcilable, ...(colon.refusals.size ? { fileRefusals: [...colon.refusals.values()] } : {}), timings_ms: timings, statements: statements + attestationStatements + 3, ...(confirm ? { confirm } : {}), ...(reuse ? { reused } : {}), 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 };
}
@@ -822,7 +895,8 @@ async function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres'
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 + (marked ? 1 : proof ? (kind === 'postgres' ? 2 : 1) : 0), ...(confirm ? { confirm } : {}) };
+ return { pages: read!.pages, open: work, markers, passRow, statements: read!.statements + work.statements + 2 + (marked ? 1 : proof ? (kind === 'postgres' ? 2 : 1) : 0), ...(confirm ? { confirm } : {}),
+ ...(confirmed?.read ? { changed: confirmed.changed } : {}) };
});
if (!reuse || reuse.working) return round(false);
try { return await round(true); } catch (error) {
@@ -851,11 +925,55 @@ async function confirmPages(exec: Exec, input: { kind: 'postgres' | 'pglite'; so
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();
+ // What the re-read replaces, for the classification reuse: the rewritten slots' previous origins, and where new slots start.
+ const changed = { rewritten: [...slots.values()].map(slot => ({ slot, sourcePath: table.sourcePath[slot]!, slug: table.slug[slot]! })), from: table.length };
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 } };
+ return { read, mark: proof.mark, confirm: { taken: true, reason: null, rows: proof.pages.length }, changed };
+}
+
+/**
+ * #6926, folded into 4b: what a folded checkpoint needs of the round's `I⋈P` (S1): its mark, its page count and its largest
+ * page id (a page past it is one the pass created). Null when the round left no marked `I⋈P` (working mode, a failed mark).
+ */
+export function passFoldBase(cache: PassLevelCache): { mark: LevelMark; pages: number; maxId: string } | null {
+ const table = cache.pages?.table;
+ if (!table || !cache.pages) return null;
+ let maxId = 0;
+ for (let i = 0; i < table.length; i++) maxId = Math.max(maxId, Number(table.id[i]));
+ return { mark: cache.pages.mark, pages: table.length, maxId: String(maxId) };
+}
+
+/**
+ * #6926, folded into 4b: whether every page a pass's round wrote (`ids`) classifies `matched` at the level its request froze,
+ * read inside the folded checkpoint's transaction. The state is the one `readShadowLevel` builds for a committed-mode path
+ * in `T` at that level; the classifier reaches `matched` before it reads a hold, marker, attestation, baseline, keep_db or
+ * open work (sync-classify.ts), and the fold refuses on any hold or open request beside it. A legacy-spelled origin, which
+ * the level resolves with `sameSyncOrigin`, is not matched here: that fold takes the stamp path.
+ */
+export async function passWritesMatched(exec: Exec, input: { kind: 'postgres' | 'pglite'; sourceId: string; incarnation: string; pack: string | null; scope: string;
+ slugMode: 'git-root' | 'source-root'; episodeFullId: string | null; ids: string[] }): Promise<boolean> {
+ const parser = syncImportParser(input.pack);
+ const read = await readPages(exec, input.kind, input.sourceId, input.incarnation, parser, { table: new PageTable(parser), ids: input.ids, slots: new Map() });
+ if (!read || read.pages.length !== input.ids.length) return false;
+ const writers = new Map((await exec.executeRaw<{ id: string; level: string | null; path: string | null }>(`SELECT p.id::text AS id, r.intent->>'level' AS level, r.intent->>'path' AS path
+ FROM pages p JOIN persistence_requests r ON r.id=p.revision_write_request_id WHERE p.source_id=$1 AND p.id = ANY($2::bigint[])`, [input.sourceId, input.ids])).map(row => [row.id, row]));
+ const pages = read.pages, parserFor = parserByKind(input.pack);
+ for (let i = 0; i < pages.length; i++) {
+ const writer = writers.get(String(pages.id[i])), level = writer?.level ?? null, sourcePath = pages.sourcePath[i]!;
+ if (!writer?.path || level === null || pages.deleted(i) || !pages.hasRecord(i)) return false;
+ if (input.slugMode === 'source-root' && input.scope && sourcePath.startsWith(`${input.scope}/`)) return false;
+ const recordRevision = pages.recordRevisionOf(i);
+ const state: SyncPathState = { mode: 'committed', tree: level, level, present: true, dirty: 'clean', diskOid: null,
+ page: { live: true, revision: pages.revision[i]!, originMatches: syncOriginPath(pages.origin.get(i) ?? sourcePath) === syncOriginPath(sourcePath) },
+ record: { blobOids: pages.oids(i, level), revision: recordRevision != null ? String(recordRevision) : null, parserSame: sameParser(pages.parserOf(i), parserFor(writer.path)) },
+ attested: null, levelSha256: null, published: false, hold: null, marker: null, baseline: null, spelling: false,
+ episodeUnsatisfied: !!input.episodeFullId && pages.fullEpisode[i] !== input.episodeFullId, fullObligation: !!input.episodeFullId, keepDb: false, openWork: false };
+ if (classifySyncPath(state).cls !== 'matched') return false;
+ }
+ return true;
}
/** `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/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 3a13d261dd..2b0a78deb1 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -52,6 +52,7 @@ import { readPassRow, writePassRow, OPEN_AT_STAMP_CAP, type ManagedSyncPassValue
import { admissionAllows, readSyncAdmission } from './sync-admission.ts';
import { syncLockId } from '../db-lock.ts';
import { readConvergedWatermark } from './sync-pass-batch.ts';
+import { foldPassCheckpoint, type PassFold } from './sync-pass-fold.ts';
import { frontmatterSlugConflictMessage } from './verb-errors.ts';
import { chunkerStamp } from '../chunkers/code.ts';
import { addFencesNormalized, clearGitHold, clearGitHoldRetryPaths, countGitHolds, recordSyncImportProvenance, type FencesTally, syncDiskProvenance, syncImportParser, syncImportParserFor, type SyncImportProvenanceBase } from './sync-holds.ts';
@@ -134,6 +135,8 @@ export interface PassStamp {
since?: string;
/** #5751: the pass settled paths only by a legacy kernel waiver (they record no import), so the next tick re-screens them: no idle. */
rescreen?: true;
+ /** #6926, folded into 4b: the stamp rides the round's last import (sync-pass-fold.ts), with what its proof needs of the round. */
+ fold?: PassFold;
}
/**
* #5984: the source-wide part of sync validation (managed mode, configured
@@ -509,8 +512,19 @@ async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIn
`Sync request ${open} of ${row.source_id} is still open or needs recovery, so checkpoint request ${row.request_id} did not commit. Let it finish; do not resubmit it. `
+ `Then run: ${checkpointRetryCommand({ sourceId: row.source_id, processingOptions: p.processingOptions, syncOptions: p.syncOptions, repoPath: p.repoPath })}`,
{ fix: syncInspectFix(row, open, false) });
+ return publishPassStamp(tx, row, p, root, releaseHold, pass, { changed: stamp.changed });
+}
+
+/**
+ * The pass stamp's writes, under the checks its caller made: the checkpoint's (`applyPassCheckpoint`) or a folded
+ * checkpoint's inside the round's last import (sync-pass-fold.ts), which passes the tail's `changed` (that import counted)
+ * and the watermark and source scope it already read.
+ */
+export async function publishPassStamp(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, releaseHold: (tx: BrainEngine, path: string | null) => Promise<void>,
+ pass: { value: ManagedSyncPassValue }, read: { changed: number; watermark?: Awaited<ReturnType<typeof readConvergedWatermark>>; emptyScope?: boolean }): Promise<Record<string, unknown>> {
+ const stamp = p.stamp!;
if (stamp.configured) {
- const emptyScope = emptySyncScope(root, syncGitTopLevel(root, p.passId!));
+ const emptyScope = read.emptyScope ?? emptySyncScope(root, syncGitTopLevel(root, p.passId!));
const changed = await tx.executeRaw(`UPDATE sources SET last_commit=$3,last_sync_at=now(),
config=jsonb_set(${SOURCE_CONFIG_OBJECT_SQL},'{slug_root_mode}',to_jsonb(CASE WHEN $6::boolean THEN COALESCE(config->>'slug_root_mode',$5::text) ELSE $5::text END)),
newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL)
@@ -523,11 +537,11 @@ async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIn
`Another sync moved the commit checkpoint of ${row.source_id} while this pass published.`);
if (stamp.stampChunker) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, chunkerStamp()]);
}
- await recordPassTail(tx, row.source_id, p.passId!, { changed: stamp.changed, extract: stamp.extract, ...(stamp.since ? { since: stamp.since } : {}) });
+ await recordPassTail(tx, row.source_id, p.passId!, { changed: read.changed, extract: stamp.extract, ...(stamp.since ? { since: stamp.since } : {}) });
await recordPassFenceTrend(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, passId: p.passId!, since: pass.value.obligations.converged?.request_hwm ?? null });
for (const path of stamp.releasedHolds) await releaseHold(tx, path);
if (stamp.retryTaken.length) await clearGitHoldRetryPaths(tx, row.source_id, stamp.incarnation, stamp.retryTaken);
- const watermark = await readConvergedWatermark(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, incarnation: row.source_incarnation }, row.request_id, OPEN_AT_STAMP_CAP);
+ const watermark = read.watermark ?? await readConvergedWatermark(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, incarnation: row.source_incarnation }, row.request_id, OPEN_AT_STAMP_CAP);
const value: ManagedSyncPassValue = structuredClone(pass.value);
const at = new Date().toISOString(), prior = value.obligations.converged;
value.obligations.converged = { target: p.target, at, ...watermark, ...(stamp.rescreen ? { open_at_stamp: null } : {}),
@@ -620,8 +634,20 @@ export type SyncPreparedMutation = PreparedMutation & { importProvenance?: SyncI
/** The import leaves the page as it is (only a canonical writeback of the file may remain); #6712 drift baseline check in sync-run.ts. */
pageUnchanged?: boolean };
-export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock?: ClaimPhaseClock,
+/**
+ * A managed-sync preparation. #6926, folded into 4b: an import whose intent carries the pass stamp (the round's last) takes
+ * it into its own publication (`foldPassCheckpoint`).
+ */
+export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WriteRequest, config: GBrainConfig, clock?: ClaimPhaseClock,
screening?: { unsaved: true }): Promise<SyncPreparedMutation> {
+ const at: { root?: string } = {};
+ const prepared = await prepareSyncMutation(unbounded, row, config, clock, screening, at);
+ const p = row.intent as SyncIntent | null;
+ return p?.kind === 'managed_sync_import' && p.stamp?.fold && at.root && !screening ? foldPassCheckpoint(prepared, { row, p, root: at.root }) : prepared;
+}
+
+async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock: ClaimPhaseClock | undefined,
+ screening: { unsaved: true } | undefined, at: { root?: string }): Promise<SyncPreparedMutation> {
const engine = boundedReads(unbounded, clock);
const p = row.intent as SyncIntent | null;
if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw syncPublicationRefusal('invalid_params', 'Unsupported internal sync intent.', row, p,
@@ -648,7 +674,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
const binding = await getWorktreeBinding(engine, row.source_id);
if (!binding?.local_path || String(binding.owner_epoch) !== p.ownerEpoch) throw syncPublicationRefusal('owner_unavailable', 'The accepted sync owner changed.', row, p,
`The canonical owner of ${row.source_id} changed, or lost its local path, after this sync was admitted. Do not claim or transfer the source to repair content.`, true);
- const root = join(binding.local_path, binding.relative_path);
+ const root = at.root = join(binding.local_path, binding.relative_path);
enterClaimStep(clock, 'configured_root', undefined, 'db');
const [configuredSource] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [row.source_id]);
assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 3f6c3a9d3f..9347bdcc19 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -104,7 +104,7 @@ export interface Held { hold: HeldEntry; overtaken?: true }
export interface Settled { settled: { path: string; request_id: string } }
export interface Cursor extends SyncDiscovery { runId: string; index: number; authority: SyncAuthority; pending?: Pending; done?: boolean; companyReceiptId?: string;
processingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions; overtaken?: true;
- counts: { added: number; modified: number; deleted: number; chunks: number; renamed?: number;
+ counts: { added: number; modified: number; deleted: number; chunks: number; renamed?: number; folded?: true;
/** #5751: unchanged working-tree files skipped only because a no-op publication could never resolve their admit reason. */
skippedContextualMode?: number; skippedCanonicalBytes?: number;
/** DX-A7: entries advanced without an admission because their publication would change nothing. */
@@ -474,7 +474,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
...(!entry ? { syncOptions: cursor.syncOptions ?? run.syncOptions, ...(run.repoPath ? { repoPath: run.repoPath } : {}) } : {}),
...(!entry && cursor.overtaken ? { overtaken: true } : {}),
ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority, ...cursorIntent(cursor, key),
- ...(cursor.passId ? { level: passLevel ?? null, ...(!entry && cursor.stamp ? { stamp: cursor.stamp } : {}) } : {}),
+ ...(cursor.passId ? { level: passLevel ?? null, ...(cursor.stamp && (!entry || cursor.index === cursor.entries.length - 1) ? { stamp: cursor.stamp } : {}) } : {}),
slugMode: cursor.slugMode, from: cursor.from, target: cursor.target, working: entry?.working ?? false,
...(cursor.companyPlan ? { companyApproval: { schema: cursor.companyPlan.schema!, planDigest: cursor.companyPlan.plan_digest, extractorVersion: cursor.companyPlan.extractor_version,
policyFingerprint: currentCompanyBrainSync(cursor.sourceId)!.policyFingerprint } } : {}) } });
@@ -845,7 +845,7 @@ function countCommitted(counts: Cursor['counts'], pending: Pending, outcome: Wri
else if (pending.intent.renameFrom) counts.renamed = (counts.renamed ?? 0) + 1;
else if (pending.pageId === null) counts.added++; else counts.modified++;
}
- counts.chunks += Number(outcome?.chunks ?? 0);
+ counts.chunks += Number(outcome?.chunks ?? 0); if (outcome?.pass_stamp === 'folded') counts.folded = true;
if ((outcome?.recovered_frontmatter || outcome?.comment_value) && pending.intent.path) counts.recovered = addRecovered(counts.recovered,
{ paths: outcome.recovered_frontmatter ? [pending.intent.path] : [], commentValues: outcome.comment_value ? 1 : 0 });
const sizeState = outcome?.size_state as PageSizeState | undefined;
@@ -1430,8 +1430,8 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
opts.onProgress?.({ phase: 'managed_sync.start', bankedFiles: cursor.index, total: cursor.entries.length });
while (!cursor.done) {
assertActive();
- // #6712 PR 4b: a pass's round batch ends at its last entry; the pass classifies again (its stamp is its own batch).
- if (cursor.passId && !cursor.stamp && !cursor.pending && cursor.index >= cursor.entries.length && !cursor.deferred?.length) return cursor;
+ // #6712 PR 4b: a pass's batch ends at its last entry; its stamp is its own batch or rides the last import (#6926, `folded`).
+ if (cursor.passId && (!cursor.stamp || cursor.entries.length > 0) && !cursor.pending && cursor.index >= cursor.entries.length && !cursor.deferred?.length) return cursor;
if (!cursor.pending) {
// A source remains fair in both directions: foreground gets service, then sync earns one bounded batch even if new interactive work keeps arriving.
if (creditedPages && performance.now() - creditStarted >= 250) creditedPages = 0;
@@ -1551,7 +1551,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
const next: Cursor = committedPast({ ...cursor, ...committedBreaker(cursor), counts: { ...cursor.counts }, progress: stampProgress(cursor.progress, cursor.index, cursor.index + 1, drainStartedAt) }, pending);
countCommitted(next.counts, pending, done.outcome);
cursor = await saveCursor(engine, key, cursor, next);
- opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length });
+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length }); if (next.counts.folded) return cursor;
// F4b: PGLite plans the rest of a large sync against fresh statistics (spec Addendum A item 2).
if (analyzeEvery > 0 && cursor.index % analyzeEvery === 0) await maybeRefreshPlannerStats(engine, 'managed_sync', { throttle: false }).catch(() => undefined);
assertActive();
diff --git a/test/e2e/sync-pass-fold-6712-postgres.test.ts b/test/e2e/sync-pass-fold-6712-postgres.test.ts
new file mode 100644
index 0000000000..2b26c5b7b8
--- /dev/null
+++ b/test/e2e/sync-pass-fold-6712-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-pass-fold-6712.test.ts'));
diff --git a/test/fix-wave-4-journeys.test.ts b/test/fix-wave-4-journeys.test.ts
index c053a19dc9..7c7f80569f 100644
--- a/test/fix-wave-4-journeys.test.ts
+++ b/test/fix-wave-4-journeys.test.ts
@@ -38,6 +38,7 @@ import { managedBrain } from './helpers/managed-brain.ts';
import { put } from './helpers/wave-fixture.ts';
import { testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
+import { stampByCheckpoint } from './helpers/pass-fold.ts';
import { __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
/** The embedding provider, simulated like the network: the printed sync commands run as on a brain with a working key. */
@@ -271,14 +272,18 @@ test('journey (c): a checkpoint timeout with a dropped index recovers with the r
const j = journey('checkpoint timeout with a dropped index');
const restore = timeoutOnce(engine);
let refused: { text: string; exit: number };
+ // The checkpoint request's validation times out: this run stamps by its request, not folded into its last import (#6926).
try {
- refused = await j.run(engine, `gbrain sync --source ${id} --no-pull --no-embed --no-extract`);
- // A real 5 s statement timeout outlasts the sync's own wait; the terminal refusal is then reported by the same command's receipt.
- for (let waited = 0; !refused.text.includes('checkpoint_validation_timeout') && waited < 30_000; waited += 500) {
- await new Promise(resolve => setTimeout(resolve, 500));
- const [row] = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint'", [id]);
- if (row?.state === 'failed') refused = await j.run(engine, `gbrain sync --source ${id} --no-pull --no-embed --no-extract`);
- }
+ refused = await stampByCheckpoint(async () => {
+ let ran = await j.run(engine, `gbrain sync --source ${id} --no-pull --no-embed --no-extract`);
+ // A real 5 s statement timeout outlasts the sync's own wait; the terminal refusal is then reported by the same command's receipt.
+ for (let waited = 0; !ran.text.includes('checkpoint_validation_timeout') && waited < 30_000; waited += 500) {
+ await new Promise(resolve => setTimeout(resolve, 500));
+ const [row] = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint'", [id]);
+ if (row?.state === 'failed') ran = await j.run(engine, `gbrain sync --source ${id} --no-pull --no-embed --no-extract`);
+ }
+ return ran;
+ });
} finally { restore(); }
expect(refused.text).toContain('checkpoint_validation_timeout');
expect((await j.run(engine, printed(refused.text, 'gbrain repair request-indexes'))).exit).toBe(0);
diff --git a/test/helpers/pass-fold.ts b/test/helpers/pass-fold.ts
new file mode 100644
index 0000000000..47f7fb311c
--- /dev/null
+++ b/test/helpers/pass-fold.ts
@@ -0,0 +1,11 @@
+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
+
+/**
+ * #6926 (folded into 4b): runs `run` with each pass's folded stamp refused at its `sync:pass_fold` seam, so the pass stamps
+ * by its checkpoint request, as a build before the fold did. For tests of that request, of a released brain's receipts, or of
+ * the window between a pass's last import and its checkpoint, which a folded stamp closes.
+ */
+export async function stampByCheckpoint<T>(run: () => Promise<T>): Promise<T> {
+ installFaultHook(point => { if (point === 'sync:pass_fold') throw new Error('The test refuses the folded stamp.'); });
+ try { return await run(); } finally { installFaultHook(undefined); }
+}
diff --git a/test/managed-sync-drain.test.ts b/test/managed-sync-drain.test.ts
index a898588309..fa15bd4614 100644
--- a/test/managed-sync-drain.test.ts
+++ b/test/managed-sync-drain.test.ts
@@ -53,8 +53,9 @@ test('a drain re-enters sliced passes over one cursor until it is synced and rec
expect(result.added).toBe(5);
expect(result.drain).toMatchObject({ outcome: 'synced', written: 5, waived: 0, remaining: 0 });
expect(result.drain!.passes).toBeGreaterThanOrEqual(5);
- const requests = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1', [f.id]);
- expect(requests[0]!.n).toBe(6);
+ // Five imports; the last carries the checkpoint (#6926, folded into 4b).
+ const requests = await engine.executeRaw<{ kind: string; stamp: string | null }>("SELECT intent->>'kind' AS kind, outcome->>'pass_stamp' AS stamp FROM persistence_requests WHERE source_id=$1 ORDER BY sequence", [f.id]);
+ expect(requests).toEqual([...Array.from({ length: 4 }, () => ({ kind: 'managed_sync_import', stamp: null })), { kind: 'managed_sync_import', stamp: 'folded' }]);
}
}), 180_000);
diff --git a/test/overwritten-edits-6712.test.ts b/test/overwritten-edits-6712.test.ts
index 99ea654610..09b96b198c 100644
--- a/test/overwritten-edits-6712.test.ts
+++ b/test/overwritten-edits-6712.test.ts
@@ -51,6 +51,7 @@ import { categorizeCheck } from '../src/core/doctor-categories.ts';
import { localHostId } from '../src/core/persistence/identity.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { waitFor } from './helpers/wait-for.ts';
+import { stampByCheckpoint } from './helpers/pass-fold.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); };
@@ -93,6 +94,7 @@ async function seedOverwrite(engine: BrainEngine, ctx: OperationContext, root: s
const incarnation = await incarnationOf(engine);
const [earlier] = await engine.executeRaw<{ id: string; principal_kind: string; principal_id: string }>(`SELECT id::text AS id, principal_kind, principal_id FROM persistence_requests
WHERE source_id='default' AND slug=$1 AND state='committed' AND intent->>'kind'='managed_sync_import' ORDER BY sequence DESC LIMIT 1`, [slug]);
+ // A released cursor run's checkpoint receipt: the test's first sync stamps by its request (`stampByCheckpoint`, #6926).
const [checkpoint] = await engine.executeRaw<{ id: string }>(`SELECT id::text AS id FROM persistence_requests
WHERE source_id='default' AND state='committed' AND intent->>'kind'='managed_sync_checkpoint' ORDER BY sequence DESC LIMIT 1`);
const importId = randomUUID(), checkpointId = randomUUID();
@@ -131,7 +133,7 @@ const repair = async (engine: BrainEngine, opts: { expect?: string; slugs?: stri
for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATABASE_URL] : [undefined]) describe(`#6712 overwritten database edits (${databaseUrl ? 'postgres' : 'pglite'})`, () => {
test('a seeded overwrite is detected and restored without publishing over the committed file', () => managedBrain(async ({ engine, ctx, root }) => {
- expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ expect((await stampByCheckpoint(() => performManagedSync(engine, OPTS))).status).toBe('first_sync');
await seedOverwrite(engine, ctx, root, 'notes/a');
const scan = await scanOverwrittenEdits(engine, 'default');
@@ -236,7 +238,7 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DAT
}, { setup, databaseUrl }), 180_000);
test('a page that moved after the preview is refused and nothing is restored or held', () => managedBrain(async ({ engine, ctx, root }) => {
- expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ expect((await stampByCheckpoint(() => performManagedSync(engine, OPTS))).status).toBe('first_sync');
await seedOverwrite(engine, ctx, root, 'notes/a');
const preview = await repair(engine, { slugs: ['notes/a'] });
expect(preview.listing?.map(entry => entry.class)).toEqual(['restore_database_edit']);
@@ -250,7 +252,7 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DAT
}, { setup, databaseUrl }), 180_000);
test('an apply interrupted after its restore committed replays it and writes the hold', () => managedBrain(async ({ engine, root }) => {
- expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ expect((await stampByCheckpoint(() => performManagedSync(engine, OPTS))).status).toBe('first_sync');
const ctx = { engine, config: { engine: engine.kind }, logger, dryRun: false, remote: false, sourceId: 'default' } as unknown as OperationContext;
await seedOverwrite(engine, ctx, root, 'notes/a');
const preview = await repair(engine, { slugs: ['notes/a'] });
@@ -271,7 +273,7 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DAT
}, { setup, databaseUrl }), 180_000);
test('a restore on a host that does not own the checkout reports the file left unheld and names the owner host command', () => managedBrain(async ({ engine, ctx, root }) => {
- expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ expect((await stampByCheckpoint(() => performManagedSync(engine, OPTS))).status).toBe('first_sync');
await seedOverwrite(engine, ctx, root, 'notes/a');
const preview = await repair(engine, { slugs: ['notes/a'] });
expect(preview.warnings?.join(' ')).toContain("Only the host that owns the source's checkout compares the file");
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index ad813ed9c5..e7ef959945 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -22,6 +22,7 @@ import { disposePersistenceConsumer, registerMutationPreparer } from '../src/cor
import { UNFINISHED_PAGE_REQUEST_SQL } from '../src/core/persistence/sync-waivers.ts';
import { waitFor } from './helpers/wait-for.ts';
import { withEnv } from './helpers/with-env.ts';
+import { stampByCheckpoint } from './helpers/pass-fold.ts';
import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
import { loadSyncFailures, syncFailuresPath } from '../src/core/sync-failure-ledger.ts';
@@ -81,9 +82,10 @@ test('imports files without rewriting bytes and checkpoints only committed page
expect(readFileSync(join(f.root,'notes/example.md'),'utf8')).toBe(bytes);
expect((await engine.getPage('notes/example',{sourceId:f.id}))?.source_path).toBe('notes/example.md');
const [source] = await engine.executeRaw<{last_commit:string}>('SELECT last_commit FROM sources WHERE id=$1',[f.id]); expect(source.last_commit).toBe(f.head);
- const requests = await engine.executeRaw<{state:string}>('SELECT state FROM persistence_requests WHERE source_id=$1',[f.id]); expect(requests).toHaveLength(2); expect(requests.every(r=>r.state==='committed')).toBe(true);
+ // #6926 (folded into 4b): the checkpoint commits inside the import's own publication, so the import is the one receipt.
+ const requests = await engine.executeRaw<{state:string;stamp:string|null}>("SELECT state, outcome->>'pass_stamp' AS stamp FROM persistence_requests WHERE source_id=$1",[f.id]); expect(requests).toEqual([{state:'committed',stamp:'folded'}]);
expect((await performManagedSync(engine,{sourceId:f.id,noPull:true})).status).toBe('up_to_date');
- expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1',[f.id])).toHaveLength(2);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1',[f.id])).toHaveLength(1);
}
}),120_000);
@@ -169,8 +171,9 @@ test('managed sync refreshes quiet-source freshness only after a complete up-to-
commit(f.root, 'changed content');
await backdateLastSync(engine, f.id);
const abort = new AbortController();
- const partial = await performManagedSync(engine, { sourceId: f.id, noPull: true, signal: abort.signal,
- onProgress: progress => { if (progress.bankedFiles === 1) abort.abort(); } });
+ // Stopped between the import and its checkpoint request: a folded stamp has no such window (#6926).
+ const partial = await stampByCheckpoint(() => performManagedSync(engine, { sourceId: f.id, noPull: true, signal: abort.signal,
+ onProgress: progress => { if (progress.bankedFiles === 1) abort.abort(); } }));
expect(partial.status).toBe('partial');
expect(await lastSyncMs(engine, f.id)).toBe(Date.parse(OLD_SYNC_AT));
}
diff --git a/test/persistence-sync-checkpoint-validation.test.ts b/test/persistence-sync-checkpoint-validation.test.ts
index e339152a07..320fe3d658 100644
--- a/test/persistence-sync-checkpoint-validation.test.ts
+++ b/test/persistence-sync-checkpoint-validation.test.ts
@@ -19,6 +19,7 @@ import { printManagedSyncDiagnostic } from '../src/commands/sync-diagnostics.ts'
import { WRITE_ERROR_CODES } from '../src/core/persistence/types.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
+import { stampByCheckpoint } from './helpers/pass-fold.ts';
// #5762: the managed sync checkpoint validation ran one OR predicate with a
// correlated sub-select over all of persistence_requests under the
@@ -112,17 +113,20 @@ function failValidation(engine: BrainEngine, failure: 'timeout' | 'lock'): () =>
return () => { engine.transaction = transaction; };
}
-/** Runs the fixture's sync until its checkpoint validation times out terminally. */
+/**
+ * Runs the fixture's sync until its checkpoint validation times out terminally. The validation under test is the checkpoint
+ * request's, so the pass stamps by that request rather than folding the stamp into its import (#6926).
+ */
async function timedOutSync(engine: BrainEngine, f: Awaited<ReturnType<typeof fixture>>) {
const restore = failValidation(engine, 'timeout');
let result: Awaited<ReturnType<typeof performManagedSync>>;
try {
- result = await performManagedSync(engine, f.opts);
+ result = await stampByCheckpoint(() => performManagedSync(engine, f.opts));
// A real 5 s statement timeout outlasts the sync's own 5 s wait; the same options then report the terminal outcome.
for (let waited = 0; result.status === 'partial' && waited < 30_000; waited += 250) {
await new Promise(resolve => setTimeout(resolve, 250));
const [row] = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint' ORDER BY sequence DESC LIMIT 1", [f.id]);
- if (row?.state === 'failed') result = await performManagedSync(engine, f.opts);
+ if (row?.state === 'failed') result = await stampByCheckpoint(() => performManagedSync(engine, f.opts));
}
} finally { restore(); }
return result;
diff --git a/test/persistence-sync-failures.serial.test.ts b/test/persistence-sync-failures.serial.test.ts
index bf8ce7130d..ef7afac42b 100644
--- a/test/persistence-sync-failures.serial.test.ts
+++ b/test/persistence-sync-failures.serial.test.ts
@@ -27,6 +27,7 @@ import type { OperationContext } from '../src/core/ops/contract.ts';
import { testBackends } from './helpers/test-backends.ts';
import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';
import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { stampByCheckpoint } from './helpers/pass-fold.ts';
import { renderFactsTable, parseFactsFence } from '../src/core/facts-fence.ts';
const backends = testBackends();
@@ -510,7 +511,8 @@ test('a new failed admission increments attempts but repeating retry during repa
expect(await performManagedSync(engine, options)).toEqual(replayOf(second));
writeFileSync(join(f.root, 'bad.md'), 'Repaired successful second observation.\n'); commit(f.root);
const slice = { maxPages: 1, maxMs: 1000 };
- const start = await performManagedSync(engine, options, slice);
+ // The slice stops after the import, before its checkpoint request: a folded stamp would converge in it (#6926).
+ const start = await stampByCheckpoint(() => performManagedSync(engine, options, slice));
expect(start.status).toBe('partial'); expect(start.filesImported).toBe(1);
expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(1);
// #6712 PR 4b: the retry is the next pass. It does not re-admit the import the interrupted pass committed, and it
diff --git a/test/sync-checkpoint-moved-6834.test.ts b/test/sync-checkpoint-moved-6834.test.ts
index 1a47234590..b6fa96985c 100644
--- a/test/sync-checkpoint-moved-6834.test.ts
+++ b/test/sync-checkpoint-moved-6834.test.ts
@@ -30,6 +30,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
+import { stampByCheckpoint } from './helpers/pass-fold.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
@@ -89,7 +90,8 @@ describe('#6834 a managed-sync checkpoint whose source checkpoint moved', () =>
/** Stops the run after its page writes and before its checkpoint publishes. */
async function beforeCheckpoint(engine: BrainEngine, f: Fixture, variant: 'entries' | 'zero') {
const abort = new AbortController();
- const partial = await outcome(performManagedSync(engine, { ...f.opts, signal: abort.signal, onProgress: p => { if (variant === 'zero' || p.bankedFiles === 1) abort.abort(); } }));
+ // A folded stamp has no window between the last import and the checkpoint (#6926): this run stamps by its request.
+ const partial = await outcome(stampByCheckpoint(() => performManagedSync(engine, { ...f.opts, signal: abort.signal, onProgress: p => { if (variant === 'zero' || p.bankedFiles === 1) abort.abort(); } })));
expect(partial.status).toBe('partial');
}
const superseded = async (engine: BrainEngine, id: string) => (await engine.executeRaw(
diff --git a/test/sync-pass-fold-6712.test.ts b/test/sync-pass-fold-6712.test.ts
new file mode 100644
index 0000000000..be27da83cf
--- /dev/null
+++ b/test/sync-pass-fold-6712.test.ts
@@ -0,0 +1,211 @@
+/**
+ * #6712 PR 4b lane A: the pass checkpoint folded into the round's last import (#6926, folded into 4b; sync-pass-fold.ts),
+ * and the confirm round's reuse of round 1's classification (sync-pass.ts `matchedUnchanged`).
+ *
+ * Protects:
+ * - fold probe 1: the last import's publication fails after its folded stamp ran (`publication:before_commit`): the stamp
+ * rolls back with it, so the checkpoint and the pass row stay where they were, and later runs converge.
+ * - fold probe 2: a hold at the target when the last import publishes: the import publishes alone (`pass_stamp_skipped`),
+ * the checkpoint has not moved when it commits, and the pass stamps by its checkpoint request as before.
+ * - fold probe 3: a kill right after the folded import commits: the checkpoint and the pass row both name HEAD, the page
+ * carries HEAD's bytes, and the next run converges with no new request (no double import).
+ * - reuse probes: open work names an unchanged `matched` path between rounds: round 2 confirms the level, reuses the other
+ * matched paths and classifies that one again. And a hold appears on an unchanged `matched` path between rounds: round 2 classifies that path again (held)
+ * instead of reusing round 1's verdict, so the hold stands and the pass reports it.
+ *
+ * PGLite here; Postgres through test/e2e/sync-pass-fold-6712-postgres.test.ts.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { readGitHold, writeGitHold } from '../src/core/persistence/sync-holds.ts';
+import { admitWrite } from '../src/core/persistence/journal.ts';
+import { preparePageAdmission } from '../src/core/persistence/page-mutations.ts';
+import { waitFor } from './helpers/wait-for.ts';
+import { randomUUID } from 'node:crypto';
+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';
+
+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 ?? '';
+const lastSequence = async (engine: BrainEngine) => Number((await engine.executeRaw<{ s: number }>('SELECT COALESCE(max(sequence),0) AS s FROM persistence_requests'))[0]!.s);
+/** The commit checkpoint and the commit the pass row records as converged. */
+async function checkpoint(engine: BrainEngine): Promise<{ last_commit: string | null; converged: string | null }> {
+ const [source] = await engine.executeRaw<{ last_commit: string | null }>("SELECT last_commit FROM sources WHERE id='default'");
+ const [pass] = await engine.executeRaw<{ at: string | null }>("SELECT completed_keys->0->'obligations'->'converged'->>'target' AS at FROM op_checkpoints WHERE op='managed-sync-pass'");
+ return { last_commit: source?.last_commit ?? null, converged: pass?.at ?? null };
+}
+/** Whether the request carries the pass stamp (its intent's `stamp`: a checkpoint request or the import that folds it). */
+const carriesStamp = async (engine: BrainEngine, requestId: string) =>
+ (await engine.executeRaw<{ stamp: boolean }>("SELECT intent ? 'stamp' AS stamp FROM persistence_requests WHERE request_id=$1::uuid", [requestId]))[0]?.stamp === true;
+const outcomeOf = async (engine: BrainEngine, requestId: string) => (await engine.executeRaw<{ state: string; stamp: string | null; skipped: string | null }>(
+ "SELECT state, outcome->>'pass_stamp' AS stamp, outcome->>'pass_stamp_skipped' AS skipped FROM persistence_requests WHERE request_id=$1::uuid", [requestId]))[0];
+/** Runs syncs until one converges (at most five); each run's status. */
+async function settle(engine: BrainEngine): Promise<string[]> {
+ const statuses: string[] = [];
+ while (statuses.length < 5 && !['synced', 'up_to_date'].includes(statuses.at(-1) ?? '')) {
+ statuses.push(await performManagedSync(engine, OPTS).then(result => result.status as string, (error: Error) => `threw: ${error.message}`));
+ }
+ return statuses;
+}
+
+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 folded pass checkpoint (${backend})`, () => {
+ test('fold probe 1: a failed publication of the last import rolls its folded stamp back; later runs converge', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ const before = await checkpoint(engine), after = await lastSequence(engine);
+ edit(root, 'notes/a', 'A committed change of notes/a.'); commit(root, 'change a');
+ const stamped = new Set<string>();
+ let failed = null as string | null, seen = null as Awaited<ReturnType<typeof checkpoint>> | null;
+ installFaultHook(async (point, detail) => {
+ // The publication transaction is open at `publication:before_commit`: the stamp is read before it, the checkpoint after it.
+ if (point === 'consumer:prepared' && detail.requestId && await carriesStamp(engine, detail.requestId)) stamped.add(detail.requestId);
+ if (point === 'publication:before_commit' && !failed && detail.requestId && stamped.has(detail.requestId)) {
+ failed = detail.requestId;
+ throw Object.assign(new Error('Connection terminated unexpectedly'), { code: '08006' });
+ }
+ if (failed && !seen && !point.startsWith('publication:')) seen = await checkpoint(engine);
+ });
+ const statuses = await settle(engine);
+ installFaultHook(undefined);
+ expect(failed).not.toBeNull();
+ expect(seen).toEqual(before);
+ expect(statuses.at(-1)).toMatch(/^(synced|up_to_date)$/);
+ const head = git(root, 'rev-parse', 'HEAD');
+ expect(await checkpoint(engine)).toEqual({ last_commit: head, converged: head });
+ expect(await bodyOf(engine, 'notes/a')).toContain('A committed change of notes/a.');
+ const imports = await engine.executeRaw<{ slug: string; n: number }>("SELECT slug, count(*)::int AS n FROM persistence_requests WHERE intent->>'kind'='managed_sync_import' AND state='committed' AND sequence>$1 GROUP BY slug", [after]);
+ expect(imports.map(row => [row.slug, Number(row.n)])).toEqual([['notes/a', 1]]);
+ }), 180_000);
+
+ test('fold probe 2: a hold at the target keeps the stamp path; the last import publishes alone', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ const before = await checkpoint(engine), incarnation = await incarnationOf(engine);
+ edit(root, 'notes/a', 'A committed change of notes/a.'); commit(root, 'change a');
+ const page = (await engine.readPageSnapshot('notes/c', { sourceId: 'default' }))!;
+ let last = null as string | null, seen = null as Awaited<ReturnType<typeof checkpoint>> | null;
+ installFaultHook(async (point, detail) => {
+ if (point === 'consumer:prepared' && !last && detail.requestId && await carriesStamp(engine, detail.requestId)) {
+ last = detail.requestId;
+ // Another writer holds an unchanged path at the target before the last import publishes.
+ 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));
+ }
+ if (point === 'publication:after_commit' && detail.requestId === last && !seen) seen = await checkpoint(engine);
+ });
+ const run = await performManagedSync(engine, OPTS);
+ installFaultHook(undefined);
+ // The hold is a write of the round the pass did not make: the fold's proof refuses it before its own hold check.
+ expect(await outcomeOf(engine, last!)).toEqual({ state: 'committed', stamp: null, skipped: 'foreign_checkpoint_write' });
+ expect(seen).toEqual(before);
+ const head = git(root, 'rev-parse', 'HEAD');
+ const stamps = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE intent->>'kind'='managed_sync_checkpoint' AND intent->>'target'=$1", [head]);
+ expect({ status: run.status, stamps, checkpoint: await checkpoint(engine) }).toEqual({ status: 'synced', stamps: [{ state: 'committed' }], checkpoint: { last_commit: head, converged: head } });
+ }), 180_000);
+
+ test('fold probe 3: a kill right after the folded import commits leaves the checkpoint and the page consistent; the next run imports nothing', () => 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 stamped = new Set<string>();
+ let folded = false, killed = false;
+ installFaultHook(async (point, detail) => {
+ if (point === 'consumer:prepared' && detail.requestId && await carriesStamp(engine, detail.requestId)) stamped.add(detail.requestId);
+ if (point === 'publication:after_commit' && detail.requestId && stamped.has(detail.requestId)) folded = true;
+ if (point === 'sync:mid_checkpoint' && folded && !killed) { killed = true; throw new Error('killed right after the folded import committed'); }
+ });
+ const dead = await performManagedSync(engine, OPTS).then(result => result.status as string, (error: Error) => error.message);
+ installFaultHook(undefined);
+ expect(killed).toBe(true);
+ expect(dead).toContain('killed right after the folded import committed');
+ await disposePersistenceConsumer(engine);
+ const head = git(root, 'rev-parse', 'HEAD');
+ expect(await checkpoint(engine)).toEqual({ last_commit: head, converged: head });
+ expect(await bodyOf(engine, 'notes/a')).toContain('A committed change of notes/a.');
+ // The next run owes the killed run's tail and stamps it; it imports nothing.
+ const after = await lastSequence(engine);
+ const next = await performManagedSync(engine, OPTS);
+ expect({ status: next.status, added: next.added, modified: next.modified }).toEqual({ status: next.status === 'up_to_date' ? 'up_to_date' : 'synced', added: 0, modified: 0 });
+ expect(await engine.executeRaw("SELECT slug FROM persistence_requests WHERE intent->>'kind'='managed_sync_import' AND sequence>$1", [after])).toEqual([]);
+ expect((await performManagedSync(engine, OPTS)).pass).toBeUndefined();
+ }), 180_000);
+ });
+
+ describe(`#6712 PR 4b confirm-round classification reuse (${backend})`, () => {
+ test('reuse probe: a hold appearing on an unchanged path between rounds classifies it again, and the hold stands', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ const incarnation = await incarnationOf(engine), page = (await engine.readPageSnapshot('notes/c', { sourceId: 'default' }))!;
+ edit(root, 'notes/a', 'A committed change of notes/a.'); commit(root, 'change a');
+ let wrote = false;
+ const verdicts: Array<{ round: number; reused: number }> = [];
+ installFaultHook(async (point, detail) => {
+ if (point === 'sync:round_start' && detail.round === 2 && !wrote) {
+ wrote = true;
+ // Another writer holds notes/c (unchanged in Git and in the database, `matched` in round 1).
+ 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));
+ }
+ if (point === 'sync:level_read') verdicts.push({ round: detail.round!, reused: detail.level?.reused ?? 0 });
+ });
+ const run = await performManagedSync(engine, OPTS);
+ installFaultHook(undefined);
+ expect(wrote).toBe(true);
+ expect(run.status).toBe('synced');
+ expect((await readGitHold(engine, 'default', incarnation, 'notes/c.md'))?.code).toBe('file_drift');
+ expect(await bodyOf(engine, 'notes/a')).toContain('A committed change of notes/a.');
+ // The hold changed what round 2 reads, so it read whole and reused nothing.
+ expect(verdicts.find(verdict => verdict.round === 2)?.reused).toBe(0);
+ }), 180_000);
+
+ test('reuse probe: open work naming an unchanged path between rounds classifies that path again, and reuses the rest', () => brain(async ({ engine, ctx, root }) => {
+ await engine.setConfig('sync.write_through', 'false');
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ edit(root, 'notes/a', 'A committed change of notes/a.'); commit(root, 'change a');
+ let open = null as string | null, release: () => void = () => {};
+ const parked = new Promise<void>(resolve => { release = resolve; });
+ const verdicts: Array<{ round: number; taken: boolean | null; reused: number }> = [];
+ installFaultHook(async (point, detail) => {
+ if (point === 'sync:round_start' && detail.round === 2 && !open) {
+ // An agent's write of notes/c (unchanged in Git and in the database, `matched` in round 1) is admitted and stays unpublished.
+ const current = (await engine.readPageSnapshot('notes/c', { sourceId: 'default' }))!;
+ const prepared = await preparePageAdmission(ctx, { operation: 'put_page', params: { slug: 'notes/c', request_id: randomUUID(), expected_revision: current.revision, content: note('notes/c', 'An agent edit in flight.') } });
+ open = (await admitWrite(engine, prepared.admission!)).request_id;
+ }
+ if (point === 'consumer:prepared' && detail.requestId === open) await parked;
+ if (point === 'sync:level_read') verdicts.push({ round: detail.round!, taken: detail.level?.confirm?.taken ?? null, reused: detail.level?.reused ?? 0 });
+ });
+ let run: Awaited<ReturnType<typeof performManagedSync>>;
+ try { run = await performManagedSync(engine, OPTS); } finally { release(); }
+ installFaultHook(undefined);
+ expect(open).not.toBeNull();
+ expect(run.status).toBe('synced');
+ // Round 2 confirms the level and reuses notes/b; notes/c, named by open work, is classified again.
+ expect(verdicts.find(verdict => verdict.round === 2)).toEqual({ round: 2, taken: true, reused: 1 });
+ await waitFor(async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [open]))[0]?.state === 'committed',
+ { timeoutMs: 30_000, label: 'the agent write of notes/c commits' });
+ expect(await bodyOf(engine, 'notes/c')).toContain('An agent edit in flight.');
+ }), 180_000);
+ });
+}
diff --git a/test/sync-pass-live-6712.test.ts b/test/sync-pass-live-6712.test.ts
index 61c0f4a312..df3bb9f878 100644
--- a/test/sync-pass-live-6712.test.ts
+++ b/test/sync-pass-live-6712.test.ts
@@ -244,8 +244,9 @@ describe('#6712 PR 4b live pass fences (pglite)', () => {
let late: string | null = null;
installFaultHook(async (point, detail) => {
if (point !== 'consumer:prepared' || late || detail.operation !== 'submit_job') return;
- const [row] = await engine.executeRaw<{ kind: string }>("SELECT intent->>'kind' AS kind FROM persistence_requests WHERE request_id=$1::uuid", [detail.requestId]);
- if (row?.kind !== 'managed_sync_checkpoint') return;
+ // The request that carries the pass stamp: its checkpoint, or the last import it folded into (#6926).
+ const [row] = await engine.executeRaw<{ stamp: boolean }>("SELECT intent ? 'stamp' AS stamp FROM persistence_requests WHERE request_id=$1::uuid", [detail.requestId]);
+ if (!row?.stamp) return;
const current = (await engine.readPageSnapshot('notes/c', { sourceId: 'default' }))!;
const prepared = await preparePageAdmission(ctx, { operation: 'put_page', params: { slug: 'notes/c', request_id: randomUUID(), expected_revision: current.revision, content: note('notes/c', 'A late agent edit.') } });
late = (await admitWrite(engine, prepared.admission!)).request_id;
diff --git a/test/sync-slug-root-mode-6694.test.ts b/test/sync-slug-root-mode-6694.test.ts
index 2179860799..fde0cfe1ff 100644
--- a/test/sync-slug-root-mode-6694.test.ts
+++ b/test/sync-slug-root-mode-6694.test.ts
@@ -16,6 +16,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
+import { stampByCheckpoint } from './helpers/pass-fold.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
@@ -71,7 +72,8 @@ describe('#6694 managed-sync checkpoint under a pinned slug_root_mode', () => {
/** Runs until every page committed and stops before the checkpoint publishes. */
async function beforeCheckpoint(engine: BrainEngine, f: Fixture, pages: number) {
const abort = new AbortController();
- const partial = await performManagedSync(engine, { ...f.opts, signal: abort.signal, onProgress: p => { if (p.bankedFiles === pages) abort.abort(); } });
+ // A folded stamp has no window between the last import and the checkpoint (#6926): this run stamps by its request.
+ const partial = await stampByCheckpoint(() => performManagedSync(engine, { ...f.opts, signal: abort.signal, onProgress: p => { if (p.bankedFiles === pages) abort.abort(); } }));
expect(partial).toMatchObject({ status: 'partial', filesImported: pages });
}
/** A checkpoint column only the owner publishes; the test edits it with managed persistence switched off for the statement. */