Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(#6712 PR 4b lane A): pass batch seam, pass intents, pass stamp publication

garrytan9df3b1ebfa5c
diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.ts
index 4ff818e756..5480362651 100644
--- a/src/core/persistence/checkpoint-validation.ts
+++ b/src/core/persistence/checkpoint-validation.ts
@@ -81,6 +81,31 @@ export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRa
}
}
+/**
+ * #6712 PR 4b (design v3.2 §3.3, clause 2): a live pass's stamp commits only with no recovery row on the worktree and no
+ * other open managed-sync request of it (page kinds and the checkpoint, filtered on the row). The open read is served by
+ * `persistence_requests_pending` (`worktree_id, sequence`, partial on `queued|running|recovering`); the recovery read by
+ * `persistence_requests_recovery`. Returns the blocking request id, or null. A statement timeout is the typed
+ * `checkpoint_validation_timeout`, as clause 1 of the cursor validation.
+ */
+export async function findOpenPassWork(tx: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, selfRequestId: string): Promise<string | null> {
+ try {
+ const [row] = await tx.executeRaw<{ request_id: string }>(`(SELECT r.request_id::text AS request_id FROM persistence_requests r
+ WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT 1)
+ UNION ALL (SELECT r.request_id::text FROM persistence_requests r
+ WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running','recovering') AND r.request_id<>$2::uuid
+ AND r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete','managed_sync_checkpoint') LIMIT 1)
+ LIMIT 1`, [worktreeId, selfRequestId]);
+ return row?.request_id ?? null;
+ } catch (error) {
+ const failure = error as { code?: string; message?: string };
+ if (failure?.code !== '57014' || !/statement timeout/.test(String(failure.message))) throw error;
+ throw opError(CHECKPOINT_VALIDATION_TIMEOUT, CHECKPOINT_VALIDATION_TIMEOUT_MESSAGE,
+ 'Page writes this sync pass already committed stay committed; only its stamp did not. This usually means the request table lacks its lookup indexes: preview that repair and apply it after the user approves, then sync again.',
+ { fix: { argv: ['gbrain', 'repair', 'request-indexes', '--json'], consent: [], actor: 'agent', why: 'Previews the missing request-table indexes without changing anything.', requires_exclusive: false } });
+ }
+}
+
/**
* #6735: `findIncompleteSyncReceipt` as a resume asks it, outside the coordinator: a timeout reads as no known blocker,
* so the revived checkpoint is validated again inside its own publication instead of the manifest being rediscovered.
diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.ts
index 549a0d952d..e6dd265b20 100644
--- a/src/core/persistence/sync-group.ts
+++ b/src/core/persistence/sync-group.ts
@@ -22,6 +22,7 @@ import { pipelined } from '../page-state/transactions.ts';
import type { SyncIntent } from './sync-prepare.ts';
import type { SyncAuthority } from './sync-authority.ts';
import { assertDrainLease } from './sync-lease.ts';
+import { assertPassAdmission } from './sync-pass-batch.ts';
/** What sets a drain's lane ceiling: lanes off, the configured maximum, or the connection pool. */
export type LanesCap = 'disabled' | 'maximum' | 'pool';
@@ -164,6 +165,7 @@ export async function admitGroup(engine: BrainEngine, members: WaiverEntry[], cu
]) as [unknown, WriteRequest[]];
if (!await cursorHolds(tx)) throw new GroupMoved();
await assertDrainLease(tx, cursor.sourceId);
+ await assertPassAdmission(tx, members.map(member => member.intent));
return rows;
}), undefined, error => engine.reconnect({ error })).catch(error => { if (error instanceof GroupMoved) return null; throw error; });
}
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index a99b0ac37f..cf9c0334fc 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -853,6 +853,8 @@ export interface SyncImportProvenance {
revision?: string;
/** What parsed the bytes: the import parser version, the Markdown chunker and the schema pack in effect (null for none). Absent on older records. */
parser?: SyncImportParser;
+ /** #6712 PR 4b: the open `--full` episode this import was written under (design §6); a live pass's `matched` requires it while the episode is open. */
+ full_episode?: string;
}
/**
diff --git a/src/core/persistence/sync-pass-batch.ts b/src/core/persistence/sync-pass-batch.ts
new file mode 100644
index 0000000000..21d8a91da8
--- /dev/null
+++ b/src/core/persistence/sync-pass-batch.ts
@@ -0,0 +1,78 @@
+/**
+ * #6712 PR 4b (design v3.2 §3.1): the in-memory round batch of a live pass and its request identity. Kept free of heavy
+ * imports: sync-run.ts, sync-waivers.ts and the pass (sync-pass-run.ts) all read it.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import type { SyncEntry } from './sync-discovery.ts';
+import { assertDrainLease } from './sync-lease.ts';
+import { admissionAllows, readSyncAdmission, type SyncAdmission } from './sync-admission.ts';
+
+/**
+ * #6712 PR 4b (design v3.2 §3.1): a live pass admits each round batch through the cursor machinery of sync-run.ts with no
+ * persisted cursor behind it. The batch lives in this process under a key with this prefix, held only while the pass
+ * holds the source's drain lease; every step that would compare-and-swap a cursor row asserts the lease instead
+ * (`passBatchStep`).
+ */
+export const PASS_BATCH_KEY_PREFIX = 'pass:';
+export const isPassBatchKey = (key: string | null | undefined): key is string => typeof key === 'string' && key.startsWith(PASS_BATCH_KEY_PREFIX);
+type BatchHead = { sourceId: string; runId: string; index: number; pending?: { requestId: string } | null };
+const passBatches = new Map<string, { value: BatchHead; header: string }>();
+/** The in-memory batch under `key` (null: none, or the pass ended). */
+export function readPassBatch<T>(key: string): T | null { return (passBatches.get(key)?.value as T | undefined) ?? null; }
+/** Replaces (or, with null, drops) the in-memory batch under `key`; `header` is its serialized header, the compare-and-swap's operand. */
+export function setPassBatch(key: string, value: BatchHead | null, header = ''): void {
+ if (value) passBatches.set(key, { value, header }); else passBatches.delete(key);
+}
+/**
+ * One step of an in-memory batch inside `tx`: the drain lease fences it (the pass that holds the lease is the batch's only
+ * writer), and it lands only while the batch's header still is `beforeHeader` (the cursor row's compare-and-swap contract).
+ * Returns false when it did not land.
+ */
+export async function passBatchStep<T extends Pick<BrainEngine, 'executeRaw'>>(tx: T, key: string, beforeHeader: string | null, next: BatchHead, nextHeader: string,
+ inTx?: (tx: T) => Promise<unknown>): Promise<boolean> {
+ await assertDrainLease(tx, next.sourceId);
+ const holds = () => (passBatches.get(key)?.header ?? null) === beforeHeader;
+ if (!holds()) return false;
+ // What rides the step (a hold write or clear) commits in its transaction; the batch moves only after it ran.
+ await inTx?.(tx);
+ if (!holds()) return false;
+ passBatches.set(key, { value: next, header: nextHeader });
+ return true;
+}
+/** The batch's head as the waivers' cursor-row read returns it, fenced by the drain lease. */
+export async function passBatchHead(tx: Pick<BrainEngine, 'executeRaw'>, key: string, sourceId: string): Promise<{ run_id: string | null; index: number | null; request_id: string | null } | undefined> {
+ await assertDrainLease(tx, sourceId);
+ const batch = passBatches.get(key)?.value;
+ return batch ? { run_id: batch.runId, index: batch.index, request_id: batch.pending?.requestId ?? null } : undefined;
+}
+
+/** RFC 4122 namespace of pass request ids (fixed forever: changing it re-admits a same-pass replay). */
+const NS_SYNC_PASS = Buffer.from('5f0c6712b4a84e0b9d1a2c3e4f5a6712', 'hex');
+/** `request_id = uuidv5(NS_SYNC_PASS, passId‖path‖level)` (design v3.2 §3.1): a same-pass replay reads the existing receipt. */
+export function passRequestId(passId: string, path: string, level: string | null): string {
+ const hash = createHash('sha1').update(NS_SYNC_PASS).update(`sync_pass:v1:${passId.toLowerCase()}\0${path}\0${level ?? ''}`).digest();
+ hash[6] = (hash[6]! & 0x0f) | 0x50;
+ hash[8] = (hash[8]! & 0x3f) | 0x80;
+ const hex = hash.subarray(0, 16).toString('hex');
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+}
+
+/** A round batch's entry: the discovery shape plus the level `L` it was classified at (the request identity's third part). */
+export interface PassEntry extends SyncEntry { level: string | null }
+
+/** `sync.admission` no longer admits what a pass froze (design v3.2 §8.1): the pass stops `resumable`, `admission_paused`. */
+export class SyncAdmissionPaused extends Error {
+ constructor(readonly admission: SyncAdmission) { super(`sync.admission is ${admission}, so this sync admits no more writes of that kind.`); this.name = 'SyncAdmissionPaused'; }
+}
+/**
+ * Fencing 1 (design v3.2 §8): a pass's admission transaction re-reads `sync.admission` and admits nothing it no longer
+ * allows (a delete needs `normal`; an import or the stamp needs `normal` or `imports_only`). Cursor intents are unaffected.
+ */
+export async function assertPassAdmission(tx: Pick<BrainEngine, 'executeRaw'>, intents: ReadonlyArray<{ passId?: string; kind: string }>): Promise<void> {
+ if (!intents.some(intent => intent.passId)) return;
+ const admission = await readSyncAdmission(tx);
+ for (const intent of intents) {
+ if (intent.passId && !admissionAllows(admission, intent.kind === 'managed_sync_delete' ? 'destructive' : 'import')) throw new SyncAdmissionPaused(admission);
+ }
+}
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index 3246ca7f62..864bfea089 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -37,9 +37,20 @@ import { probeDirtiness, readBlobs, readIndexLevel, readTreeLevel, type GitTreeE
import { classifySyncPath, syncPassKind, type SyncClassified, type SyncIdleBlocker, type SyncPathState } from './sync-classify.ts';
import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceReceipt, type ConvergenceScreen } from './sync-convergence.ts';
import { readManagedMode } from './ownership.ts';
-import { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP } from './sync-pass-row.ts';
+import { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP, type SyncSelection } from './sync-pass-row.ts';
export { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP };
+
+/** What a live pass feeds the level read (sync-pass-run.ts): its episode, the retry paths it already re-screened, and its selection. */
+export interface PassLevelInput {
+ /** The open episode's `full_id`: a live page whose record carries another is `episodeUnsatisfied`. Null: no full obligation. */
+ episodeFullId: string | null;
+ /** Hold paths (source-relative) whose retry row this pass already re-screened: no longer `retried` in its later rounds. */
+ retryConsumed?: ReadonlySet<string>;
+ exclude?: readonly string[];
+ includeHidden?: readonly string[];
+ strategy?: string;
+}
/** PGLite's keyset page size (design v3.2 §2.1); Postgres reads `I⋈P` in one statement of its snapshot. */
const PGLITE_KEYSET_ROWS = 2_000;
/** Blob bytes read for adoption by hash and the screen, per blob. */
@@ -56,6 +67,11 @@ export interface ShadowLevel {
mode: 'committed' | 'working'; head: string; baselineCommit: string | null; full: boolean;
kind: 'idle' | 'hold_only' | 'full'; kindBlockers: SyncIdleBlocker[];
paths: ShadowPath[];
+ /** The schema pack in effect (the pass's `pack` fingerprint) and the selection the level read (design §6). */
+ pack: string | null;
+ selection: SyncSelection;
+ /** Re-screen-due hold paths (Git-root paths): a hold-only round's candidates. */
+ rescreenDue: string[];
/** Live file-backed pages whose origin is eligible: the mass-delete valve's denominator (#2828). */
reconcilable: number;
timings_ms: Record<string, number>;
@@ -64,7 +80,7 @@ export interface ShadowLevel {
/** 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. */
interface PageRow { id: number | string; slug: string; source_path: string; revision: string; deleted: boolean; request_id: string | null;
- record: Pick<SyncImportProvenance, 'origin' | 'blob_oid' | 'disk_blob_oid' | 'revision' | 'parser'> | null; arm1: boolean | null; attested_hash: string | null }
+ record: (Pick<SyncImportProvenance, 'origin' | 'blob_oid' | 'disk_blob_oid' | 'revision' | 'parser'> & { full_episode?: string | null }) | null; arm1: boolean | null; attested_hash: string | null }
const recordOids = (record: PageRow['record']): string[] =>
record ? [record.blob_oid, record.disk_blob_oid].filter((oid): oid is string => typeof oid === 'string' && oid.length > 0) : [];
@@ -93,15 +109,17 @@ async function readPages(exec: Exec, kind: 'postgres' | 'pglite', sourceId: stri
const select = `SELECT p.id, p.slug, p.source_path, p.knowledge_revision::text AS revision, p.deleted_at IS NOT NULL AS deleted,
p.revision_write_request_id::text AS request_id,
c.completed_keys IS NOT NULL AS has_record, c.completed_keys->0->>'origin' AS rec_origin, c.completed_keys->0->>'blob_oid' AS rec_blob_oid,
- c.completed_keys->0->>'disk_blob_oid' AS rec_disk_blob_oid, c.completed_keys->0->>'revision' AS rec_revision, c.completed_keys->0->'parser' AS rec_parser
+ c.completed_keys->0->>'disk_blob_oid' AS rec_disk_blob_oid, c.completed_keys->0->>'revision' AS rec_revision, c.completed_keys->0->'parser' AS rec_parser,
+ c.completed_keys->0->>'full_episode' AS rec_full_episode
FROM pages p LEFT JOIN op_checkpoints c ON c.op=$2 AND c.fingerprint=$3||p.id::text
WHERE p.source_id=$1 AND p.source_path IS NOT NULL`;
const params = [sourceId, SYNC_IMPORT_PROVENANCE_OP, `${sourceId}:${incarnation}:`];
type Raw = Omit<PageRow, 'record' | 'arm1' | 'attested_hash'> & { has_record: boolean; rec_origin: string | null; rec_blob_oid: string | null;
- rec_disk_blob_oid: string | null; rec_revision: string | null; rec_parser: SyncImportProvenance['parser'] | null };
+ rec_disk_blob_oid: string | null; rec_revision: string | null; rec_parser: SyncImportProvenance['parser'] | null; rec_full_episode: string | null };
const rows: PageRow[] = [];
- const take = (page: Raw[]) => { for (const { has_record, rec_origin, rec_blob_oid, rec_disk_blob_oid, rec_revision, rec_parser, ...row } of page) rows.push({ ...row, arm1: null, attested_hash: null,
- record: has_record ? { origin: rec_origin ?? '', blob_oid: rec_blob_oid ?? undefined, disk_blob_oid: rec_disk_blob_oid, revision: rec_revision ?? undefined, parser: rec_parser ?? undefined } : null }); };
+ const take = (page: Raw[]) => { for (const { has_record, rec_origin, rec_blob_oid, rec_disk_blob_oid, rec_revision, rec_parser, rec_full_episode, ...row } of page) rows.push({ ...row, arm1: null, attested_hash: null,
+ record: has_record ? { origin: rec_origin ?? '', blob_oid: rec_blob_oid ?? undefined, disk_blob_oid: rec_disk_blob_oid, revision: rec_revision ?? undefined, parser: rec_parser ?? undefined,
+ full_episode: rec_full_episode } : null }); };
if (kind === 'postgres') { take(await exec.executeRaw<Raw>(select, params)); return { rows, statements: 1 }; }
let after = 0, statements = 0;
for (;;) {
@@ -191,7 +209,7 @@ const timer = () => { const started = performance.now(); return () => Math.round
* The shadow level of a managed source: every path classified, nothing written. Null for a company-brain source, which
* keeps its frozen manifest (design v3.2 §3.6).
*/
-export async function readShadowLevel(engine: BrainEngine, input: { sourceId: string; full?: boolean; workingTree?: boolean; context?: ManagedSyncContext }): Promise<ShadowLevel | null> {
+export async function readShadowLevel(engine: BrainEngine, input: { sourceId: string; full?: boolean; workingTree?: boolean; context?: ManagedSyncContext; pass?: PassLevelInput }): Promise<ShadowLevel | null> {
const total = timer();
const timings: Record<string, number> = {};
let t = timer();
@@ -206,7 +224,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const [company, slugModeRead, excludeRead, includeHiddenRead, workingRead, packRead, mirrorRead] = await Promise.allSettled([
currentCompanyBrainSync(sourceId) ? Promise.resolve(true) : getCompanyBrainProfile(engine, sourceId).then(profile => !!profile),
scope ? resolveSlugRootMode(engine, { sourceId, explicitGitRoot: false, slugPrefix: resolveSlugForPath(join(scope, 'x.md')).slice(0, -2), dryRun: true }) : Promise.resolve('git-root' as const),
- syncExcludePatterns(engine),
+ syncExcludePatterns(engine, [...input.pass?.exclude ?? []]),
engine.getConfig('sync.include_hidden'),
input.workingTree === undefined ? engine.getConfig('sync.include_working_tree') : Promise.resolve(null),
loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null),
@@ -216,8 +234,8 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const settled = <T>(read: PromiseSettledResult<T>): T => { if (read.status === 'rejected') throw read.reason; return read.value; };
if (settled(company)) return null;
const slugMode = settled(slugModeRead), exclude = settled(excludeRead), pack = settled(packRead), mirror = settled(mirrorRead);
- const strategy = (context.source.config?.strategy as string | undefined) ?? 'markdown';
- const includeHidden = [...new Set((settled(includeHiddenRead) ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean).map(v => v.endsWith('/') ? `${v}**` : v))];
+ const strategy = input.pass?.strategy ?? (context.source.config?.strategy as string | undefined) ?? 'markdown';
+ const includeHidden = [...new Set([...input.pass?.includeHidden ?? [], ...(settled(includeHiddenRead) ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))];
const keepDbPrefixes = (() => { try { return loadStorageConfig(root)?.keep_db ?? []; } catch { return []; } })();
const sourceRelative = (gitPath: string) => (scope ? gitPath.slice(scope.length + 1) : gitPath);
// Pure per path and asked several times per path in a round, so each is computed once.
@@ -256,7 +274,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const holds = (sourceHolds[0]?.holds ?? []).filter(hold => hold.incarnation === incarnation);
const holdByPath = new Map(holds.map(hold => [hold.path, hold]));
const [basisMoved, driftMoved] = await Promise.all([holdBasisMoved(engine, sourceId, holdByPath, [...holdByPath.keys()]), movedDriftHolds(engine, sourceId, holds)]);
- return { holds, retry: new Set(retryPaths), moved: [...basisMoved, ...driftMoved] };
+ return { holds, retry: new Set(retryPaths.filter(path => !input.pass?.retryConsumed?.has(path))), moved: [...basisMoved, ...driftMoved] };
}),
]);
timings.reads = t();
@@ -345,7 +363,8 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
hold: hold ? { atLevel: holdAtLevel(hold, level, probe?.rawSha256 ?? null) && !moved.has(path), rescreenDue: holdRescreenDue(hold, retry.has(hold.path)), retried: retry.has(hold.path) } : null,
marker: marker ?? virtualMarker, baseline: needsBaseline ? await baselineOf(path) : null,
spelling: (spellings.get(fold(path)) ?? 0) > 1,
- episodeUnsatisfied: input.full === true && !!row && !row.deleted,
+ episodeUnsatisfied: input.pass ? !!input.pass.episodeFullId && !!row && !row.deleted && record?.full_episode !== input.pass.episodeFullId
+ : input.full === true && !!row && !row.deleted,
keepDb: !mirror && keepDbPrefixes.length > 0 && !!row && isKeepDbSlug(row.slug, keepDbPrefixes),
openWork: !!row && open.pageIds.has(Number(row.id)) || open.origins.has(originOf(path)),
};
@@ -402,7 +421,9 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
void passRow;
timings.total = total();
return { sourceId, incarnation, root, gitRoot, scope, slugMode, mode, head, baselineCommit, full: input.full === true, kind: kind.kind, kindBlockers: kind.blockers,
- paths, reconcilable, timings_ms: timings, statements: statements + attestationStatements + 3 };
+ paths, reconcilable, timings_ms: timings, statements: statements + attestationStatements + 3, 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)) };
}
/** `workingTreeFilePresent` (sync-discovery.ts) for a Git-root path: a file that exists, or one that cannot be read (fail closed). */
@@ -450,47 +471,4 @@ export async function idleTickProbe(engine: BrainEngine, input: { sourceId: stri
t = timer();
const [probe] = await engine.executeRaw<{ pass_row: Record<string, unknown> | null; newer: boolean; pending: boolean }>(`WITH pass AS (
SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND fingerprint=$2)
- SELECT (SELECT value FROM pass) AS pass_row,
- EXISTS (SELECT 1 FROM persistence_requests WHERE sequence > COALESCE($3::bigint, ((SELECT value FROM pass)->'converged'->>'request_hwm')::bigint, 0) AND worktree_id = $4) AS newer,
- EXISTS (SELECT 1 FROM persistence_requests WHERE worktree_id = $4 AND state IN ('queued','running','recovering')) AS pending`,
- [MANAGED_SYNC_PASS_OP, `${context.sourceId}:${context.incarnation}`, input.assumeConverged?.requestHwm ?? null, context.binding.worktree_id]);
- timings.probes = t();
- const row = probe?.pass_row ?? null;
- const converged = input.assumeConverged ?? (row?.converged as { target: string; request_hwm: number } | undefined
- ? { target: String((row!.converged as Record<string, unknown>).target), requestHwm: Number((row!.converged as Record<string, unknown>).request_hwm) } : null);
- const newer = probe?.newer === true, pending = probe?.pending === true;
- const kind = syncPassKind({ converged: converged ? { target: converged.target, parserFp: '', pack: null, selectionFp: '', passesSinceFull: 0, lastFullAt: Date.now() } : null,
- head: head ?? '', parserFp: '', pack: null, selectionFp: '', now: Date.now(), openEpisode: false, owedTail: false, retryRow: false, notConvergedStreak: 0, mismatchStreak: 0,
- requestNewer: newer, openAtStampFinished: pending && !input.assumeConverged, workingChange: false, rescreenDueHold: false, full: false });
- timings.total = total();
- return { idle: kind.kind === 'idle', reasons: kind.blockers, timings_ms: timings, rows: (newer ? 1 : 0) + (pending ? 1 : 0) + (row ? 1 : 0) };
-}
-
-/**
- * `gbrain sync --dry-run --json`'s `convergence` for one source: the receipt with the read-only screen, undefined
- * on a brain that is not managed or for a company-brain source; a read that cannot run reports why instead of failing
- * the dry run.
- */
-export async function dryRunConvergence(engine: BrainEngine, input: { sourceId: string; full: boolean; workingTree?: boolean; redactPaths: boolean;
- noEmbed: boolean; noExtract: boolean; noSchemaPack: boolean }): Promise<ConvergenceReceipt | { dry_run: true; status: 'unavailable'; code: string; message: string } | undefined> {
- if (!await readManagedMode(engine)) return undefined;
- try {
- const context = await resolveManagedSyncContext(engine, { sourceId: input.sourceId, noPull: true, dryRun: true });
- return await shadowConvergence(engine, { sourceId: input.sourceId, full: input.full, workingTree: input.workingTree, redactPaths: input.redactPaths, context,
- screen: readOnlySameContentScreen(engine, context, { noEmbed: input.noEmbed, noExtract: input.noExtract, noSchemaPack: input.noSchemaPack }) }) ?? undefined;
- } catch (error) {
- const code = (error as { code?: unknown }).code;
- return { dry_run: true, status: 'unavailable', code: typeof code === 'string' ? code : 'convergence_read_failed', message: error instanceof Error ? error.message : String(error) };
- }
-}
-
-/** \`sync status --detail\`'s \`convergence\`: the receipt without the screen (status never prepares an import). */
-export async function statusConvergence(engine: BrainEngine, sourceId: string): Promise<ConvergenceReceipt | { dry_run: true; status: 'unavailable'; code: string; message: string } | null> {
- if (!await readManagedMode(engine)) return null;
- try {
- return await shadowConvergence(engine, { sourceId, screen: false });
- } catch (error) {
- const code = (error as { code?: unknown }).code;
- return { dry_run: true, status: 'unavailable', code: typeof code === 'string' ? code : 'convergence_read_failed', message: error instanceof Error ? error.message : String(error) };
- }
-}
+ SELECT (SELECT value FROM pass) AS pass_row,
\ No newline at end of file
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index f7a7ffcccc..cdc39e0b43 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -43,13 +43,16 @@ import type { CompanyBrainPlan } from '../company-brain/types.ts';
import { companyBrainProfile } from '../company-brain/profile.ts';
import { companyBrainPolicyFingerprint } from '../company-brain/policy.ts';
import { isUnboundSourcePage, UNBOUND_COLLISION_MESSAGE } from './unbound-source.ts';
-import { checkpointRetryCommand, findIncompleteSyncReceipt, type SyncSettledIndexes } from './checkpoint-validation.ts';
+import { checkpointRetryCommand, findIncompleteSyncReceipt, findOpenPassWork, type SyncSettledIndexes } from './checkpoint-validation.ts';
import { CURSOR_CHANGED_REFUSAL_MESSAGE, SYNC_CURSOR_FENCE_ORIGIN } from './sync-knock-on.ts';
import { checkpointCursorReplaced } from './sync-checkpoint-replaced.ts';
-import { recordSyncTail } from './sync-tail-record.ts';
+import { recordPassTail, recordSyncTail } from './sync-tail-record.ts';
+import { readPassRow, writePassRow, OPEN_AT_STAMP_CAP, type ManagedSyncPassValue } from './sync-pass-row.ts';
+import { admissionAllows, readSyncAdmission } from './sync-admission.ts';
+import { syncLockId } from '../db-lock.ts';
import { frontmatterSlugConflictMessage } from './verb-errors.ts';
import { chunkerStamp } from '../chunkers/code.ts';
-import { clearGitHold, countGitHolds, recordSyncImportProvenance, syncDiskProvenance, syncImportParser, syncImportParserFor, type SyncImportProvenanceBase } from './sync-holds.ts';
+import { clearGitHold, clearGitHoldRetryPaths, countGitHolds, recordSyncImportProvenance, syncDiskProvenance, syncImportParser, syncImportParserFor, type SyncImportProvenanceBase } from './sync-holds.ts';
import { clearSyncSlice, writeSyncSlice, type SyncSliceState } from './sync-slices.ts';
import { CHECKPOINT_MOVED_MESSAGE, emptySyncScope, pinnedSlugModeMismatch, slugModeMismatchCause } from './sync-slug-mode.ts';
import { readPagePurgeTombstones } from './page-purge.ts';
@@ -92,8 +95,36 @@ export interface SyncIntent extends Record<string, unknown> {
supersededRequests?: string[];
/** #6643 checkpoint only: the indexes the cursor passed without a commit (waived or held), from the index it began recording them. */
settled?: SyncSettledIndexes;
- syncAuthority: SyncAuthority; cursorKey: string; runId: string; index: number;
- from: string | null; target: string; total: number; slugMode: 'git-root' | 'source-root';
+ /**
+ * A cursor intent's key, run and position (company and legacy cursors). #6712 PR 4b: a pass intent (`passId`) carries none
+ * of them; it keeps `kind`, `slug`, `page_id` and `renameFrom`, which the #6862 FIFO guard reads.
+ */
+ cursorKey?: string; runId?: string; index?: number; total?: number;
+ syncAuthority: SyncAuthority; from: string | null; target: string; slugMode: 'git-root' | 'source-root';
+ /** #6712 PR 4b: the live pass that admitted this request (sync-pass-run.ts), and the level `L` it classified the path at. */
+ passId?: string; level?: string | null;
+ /** #6712 PR 4b: the open `--full` episode an import records as its record's `full_episode` (design §6). */
+ fullEpisode?: string;
+ /** #6712 PR 4b, a pass's checkpoint only: what its stamp publishes. */
+ stamp?: PassStamp;
+}
+/**
+ * #6712 PR 4b (design v3.2 §3.3): what a converged pass's `managed_sync_checkpoint` publishes. `configured`: the pass ran at
+ * the source's configured selection, so it advances `last_commit`; a scoped pass stamps its converged state only.
+ */
+export interface PassStamp {
+ leaseToken: string; incarnation: string; configured: boolean;
+ /** `chunker_version` is stamped: a first sync, or a full episode this stamp closes at the configured selection. */
+ stampChunker: boolean;
+ /** The open episode closes with this stamp. */
+ closesEpisode: boolean;
+ /** `sources retry-held` paths this pass re-screened (compare-and-delete) and held paths that left the source. */
+ retryTaken: string[]; releasedHolds: string[];
+ selectionFp: string; parserFp: string; pack: string | null;
+ /** The pass ran a full round (resets `passes_since_full`). */
+ full: boolean;
+ /** The tail obligation: pages the pass changed, and whether their links are extracted. */
+ changed: number; extract: boolean;
}
/**
* #5984: the source-wide part of sync validation (managed mode, configured
@@ -135,7 +166,7 @@ async function sourceSyncChecks(tx: BrainEngine, row: WriteRequest, p: SyncInten
const [configuredSource] = await tx.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1 FOR SHARE', [row.source_id]);
assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);
},
- () => readSyncCursorFence(tx, p.cursorKey),
+ () => p.passId || !p.cursorKey ? Promise.resolve(undefined) : readSyncCursorFence(tx, p.cursorKey),
async () => {
const current = await getWorktreeBinding(tx, row.source_id);
if (!current || String(current.owner_epoch) !== p.ownerEpoch) throw syncPublicationRefusal('owner_unavailable', 'The accepted sync owner epoch changed.', row, p,
@@ -328,7 +359,7 @@ async function resolveSyncOrigin(engine: BrainEngine, row: WriteRequest, p: Sync
if (typeof p.path !== 'string' || typeof p.sourcePath !== 'string') throw syncPublicationRefusal('storage_error', 'The accepted sync origin is missing.', row, p,
'The stored intent has no recorded file path for this page.');
let working = p.working;
- if (p.kind === 'managed_sync_delete' && working === undefined) {
+ if (p.kind === 'managed_sync_delete' && working === undefined && !p.passId) {
enterClaimStep(clock, 'manifest_entry', undefined, 'db');
const [manifest] = await engine.executeRaw<{ entry: { path: string; sourcePath: string; action: string; working: boolean; pageId?: number | null } }>(
"SELECT completed_keys->$2::integer AS entry FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [p.runId, p.index]);
@@ -342,7 +373,7 @@ async function resolveSyncOrigin(engine: BrainEngine, row: WriteRequest, p: Sync
}
const origin = { path: p.path, sourcePath: p.sourcePath, action: p.kind === 'managed_sync_delete' ? 'delete' as const : 'import' as const, working };
enterClaimStep(clock, 'git_rev_parse', undefined, 'git');
- const originContext = { root, gitRoot: syncGitTopLevel(root, p.runId), target: p.target, slugMode: p.slugMode };
+ const originContext = { root, gitRoot: syncGitTopLevel(root, p.passId ?? p.runId ?? row.request_id), target: p.target, slugMode: p.slugMode };
assertSyncEntryOrigin(originContext, origin);
const originScope = syncOriginScope({ ...originContext, sourceId: row.source_id });
enterClaimStep(clock, 'origin_check', undefined, 'db');
@@ -429,7 +460,7 @@ function syncFileProvenance(row: WriteRequest, p: SyncIntent, root: string, rawS
function publishedSyncNoop(row: WriteRequest, p: SyncIntent, root: string, snapshot: Snapshot | null, schemaPack: string | null,
validate: (tx: BrainEngine) => Promise<void>, releaseHold: (tx: BrainEngine) => Promise<void>): SyncPreparedMutation {
const importProvenance: SyncImportProvenanceBase = { source_id: row.source_id, incarnation: row.source_incarnation, origin: p.sourcePath!, raw_sha256: p.rawHash!,
- working: true, gbrain_version: VERSION, parser: syncImportParser(schemaPack) };
+ working: true, gbrain_version: VERSION, parser: syncImportParser(schemaPack), ...(p.fullEpisode ? { full_episode: p.fullEpisode } : {}) };
return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate, importProvenance,
apply: async tx => {
await releaseHold(tx);
@@ -446,6 +477,64 @@ export function syncDiskBytes(root: string, path: string, content: string, rawHa
return rawHash !== null && rawHash === sha256(content) ? Buffer.from(content) : readSyncFile(root, path);
}
+/** A pass's stamp is refused because the pass no longer holds the source (its lease went, or another pass pinned since). */
+export const PASS_LEASE_LOST_MESSAGE = 'The sync pass that admitted this checkpoint no longer holds the source.';
+
+/**
+ * #6712 PR 4b (design v3.2 §3.3; v3 §3.3): a converged pass's stamp. Clause 1: the drain lease that admitted it is live
+ * (`FOR SHARE` on the lock row with the pass's token) and the pass row still names this pass. Clause 2: no recovery row and no
+ * other open managed-sync request of the worktree (`findOpenPassWork`). Then, at the configured selection only,
+ * `last_commit`, `last_sync_at` and the slug-root pin under `WHERE id AND incarnation` (and `chunker_version`); the tail
+ * obligation, hold release, the retry compare-and-delete, and the pass row's converged state (`request_hwm`,
+ * `open_at_stamp`, fingerprints), written under the lease token. The cursor checkpoint (`applyManagedSyncCheckpoint`) is unchanged.
+ */
+async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, releaseHold: (tx: BrainEngine, path: string | null) => Promise<void>): Promise<Record<string, unknown>> {
+ const stamp = p.stamp!;
+ const lease = await 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]);
+ const pass = lease.length ? await readPassRow(tx, row.source_id, stamp.incarnation) : null;
+ if (!pass || pass.value.lease_token !== stamp.leaseToken || pass.value.telemetry.pass_id !== p.passId) throw syncPublicationRefusal('revision_conflict', PASS_LEASE_LOST_MESSAGE, row, p,
+ `The pass that admitted checkpoint ${row.request_id} of ${row.source_id} lost the source's drain lease, or another pass started since, so nothing was stamped.`);
+ const open = await findOpenPassWork(tx, row.worktree_id!, row.request_id);
+ if (open) throw opError('recovery_required', `An unfinished sync request (request ${open}) still blocks the sync checkpoint.`,
+ `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) });
+ if (stamp.configured) {
+ const 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)
+ WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR last_commit=$3)
+ AND ($6::boolean OR config->>'slug_root_mode' IS NULL OR config->>'slug_root_mode'=$5) RETURNING id`,
+ [row.source_id, row.source_incarnation, p.target, p.from, p.slugMode, emptyScope]);
+ const pinned = !changed.length && !emptyScope ? await pinnedSlugModeMismatch(tx, row.source_id, row.source_incarnation, p.slugMode) : null;
+ if (pinned) throw syncPublicationRefusal('slug_root_mode_mismatch', `The source pins slug_root_mode=${pinned}, but this sync ran under ${p.slugMode}.`, row, p, slugModeMismatchCause(row.source_id, pinned, p.slugMode));
+ if (!changed.length) throw syncPublicationRefusal('revision_conflict', CHECKPOINT_MOVED_MESSAGE, row, p,
+ `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 });
+ 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 [hwm] = await tx.executeRaw<{ hwm: string | null }>('SELECT max(sequence)::text AS hwm FROM persistence_requests WHERE worktree_id=$1::uuid', [row.worktree_id]);
+ const openIds = await tx.executeRaw<{ id: string }>(`(SELECT 'r:'||request_id::text AS id FROM persistence_requests
+ WHERE worktree_id=$1::uuid AND state IN ('queued','running','recovering') AND request_id<>$2::uuid LIMIT $3)
+ UNION ALL (SELECT 'e:'||e.id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
+ WHERE r.worktree_id=$1::uuid AND e.kind='git' AND e.state IN ('queued','running') LIMIT $3)`, [row.worktree_id, row.request_id, OPEN_AT_STAMP_CAP + 1]);
+ const value: ManagedSyncPassValue = structuredClone(pass.value);
+ const at = new Date().toISOString(), prior = value.obligations.converged;
+ value.obligations.converged = { target: p.target, at, request_hwm: hwm?.hwm ?? '0', open_at_stamp: openIds.length > OPEN_AT_STAMP_CAP ? null : openIds.map(open => open.id),
+ parser_fp: stamp.parserFp, pack: stamp.pack, selection_fp: stamp.selectionFp, last_full_at: stamp.full || !prior ? at : prior.last_full_at,
+ passes_since_full: stamp.full || !prior ? 0 : prior.passes_since_full + 1 };
+ if (stamp.closesEpisode) delete value.obligations.episode;
+ Object.assign(value.obligations, { not_converged_streak: 0, mismatch: {}, faults: {} });
+ value.telemetry = { ...value.telemetry, outcome: 'synced', stop_reason: stamp.configured ? null : 'selection_scoped', ended_at: at, remaining: 0,
+ duration_ms: Date.parse(at) - Date.parse(value.telemetry.started_at) };
+ if (!await writePassRow(tx, value)) throw syncPublicationRefusal('revision_conflict', PASS_LEASE_LOST_MESSAGE, row, p,
+ `Another pass of ${row.source_id} started while checkpoint ${row.request_id} published, so nothing was stamped.`);
+ return { status: 'synced', source_id: row.source_id, pass_id: p.passId, configured: stamp.configured };
+}
+
/** The checkpoint request's publication: the whole run committed, so `last_commit` (and the slug-root pin) advance under the guard. */
async function applyManagedSyncCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, releaseHold: (tx: BrainEngine, path: string | null) => Promise<void>): Promise<Record<string, unknown>> {
const [cursor] = await tx.executeRaw<{ completed_keys: [{ runId: string; index: number; total: number }] }>(
@@ -568,6 +657,12 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
}
},
async () => { if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(tx, row, p.path === null ? undefined : { root, path: join(root, p.path) }); },
+ async () => {
+ // #6712 PR 4b (design v3.2 §8, fencing 2): a pass's deletion re-reads sync.admission at publication.
+ if (p.passId && p.kind === 'managed_sync_delete' && !admissionAllows(await readSyncAdmission(tx), 'destructive')) throw syncPublicationRefusal('admission_paused',
+ 'sync.admission paused destructive sync writes before this deletion published.', row, p,
+ `sync.admission is not normal, so the deletion of ${row.slug} in ${row.source_id} published nothing; the page stays live and the next pass re-reads the level.`);
+ },
async () => {
if (p.path !== null && syncRawHash(root, p.path) !== p.rawHash) throw syncPublicationRefusal('source_changed', 'The imported file changed after sync admission.', row, p,
`The file of ${row.slug} changed on disk after this sync was admitted; review the change and commit it.`);
@@ -592,7 +687,8 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
await checkApprovedSchemaForEngine(tx, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest }, { remote: false, sourceId: row.source_id });
}
};
- if (p.kind === 'managed_sync_checkpoint') return { sourceExclusive: true, observedRevision: null, validate, apply: tx => applyManagedSyncCheckpoint(tx, row, p, root, releaseHold) };
+ if (p.kind === 'managed_sync_checkpoint') return { sourceExclusive: true, observedRevision: null, validate,
+ apply: tx => p.passId ? applyPassCheckpoint(tx, row, p, root, releaseHold) : applyManagedSyncCheckpoint(tx, row, p, root, releaseHold) };
const source = { sourceId: row.source_id };
enterClaimStep(clock, 'page_snapshot', undefined, 'db');
const snapshot = await materializedSnapshot(engine, await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true }));
@@ -709,7 +805,8 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
enterClaimStep(clock, 'canonical_projections', undefined, 'db');
const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');
const importProvenance: SyncImportProvenanceBase = { source_id: row.source_id, incarnation: row.source_incarnation, origin: p.sourcePath!, raw_sha256: sha256(p.content!),
- ...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}), parser: syncImportParser(pack?.identity ?? null) };
+ ...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}), parser: syncImportParser(pack?.identity ?? null),
+ ...(p.fullEpisode ? { full_episode: p.fullEpisode } : {}) };
// afterCommit follows the import that published: a rename publishes its re-preparation at the new slug.
let published = ready;
const preparedImport: SyncPreparedMutation = { observedRevision: snapshot?.revision ?? null, trust: await ownerImportTrust(engine, row, ready.parsedPage.frontmatter, p.sourcePath), importProvenance,
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index d8a5d029ca..7c4130ee54 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -68,6 +68,9 @@ import { withSyncTail } from './sync-tail.ts';
import { assertDrainLease, currentDrainLease, leaseHeldResult, readDrainHolder, withDrainLease } from './sync-lease.ts';
import { LockStolenError, LockUnavailableError, syncLockId } from '../db-lock.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
+import { assertPassAdmission, isPassBatchKey, passBatchStep, passRequestId, readPassBatch, type PassEntry } from './sync-pass-batch.ts';
+import type { PassStamp } from './sync-prepare.ts';
+import { runSyncPass } from './sync-pass-run.ts';
export interface ManagedSyncWriteDiagnostic {
source_id: string;
@@ -135,7 +138,14 @@ export interface Cursor extends SyncDiscovery { runId: string; index: number; au
* after one that did not commit lead the window too, so every admitted request's identity stays in the cursor until
* its own receipt is read, whenever it commits.
*/
- window?: Pending[][]; }
+ window?: Pending[][];
+ /**
+ * #6712 PR 4b: a live pass's round batch (sync-pass-run.ts), held in memory under a `pass:` key with no cursor row. Its
+ * intents carry `passId` (no cursor fields) and a request id derived from `(passId, path, level)`; `stamp`: the batch is
+ * the pass's stamp (no entries; its checkpoint publishes the stamp). `fullEpisode`: the open `--full` episode its imports
+ * record. `failureKey`: the key a recorded failure of the batch is filed under (the pass row's fingerprint).
+ */
+ passId?: string; stamp?: PassStamp; fullEpisode?: string; failureKey?: string; }
export interface CursorProgress { startedAt: number; startIndex: number; lastAt: number; lastIndex: number }
/**
* #6278 (1.5): the breaker state a run carries in its cursor. `stalled` lists the `preparation_stalled` receipts this run
@@ -204,6 +214,7 @@ class MissingSyncManifest extends OperationError {
constructor(readonly cursor: CursorHeader) { super('storage_error', 'The durable sync manifest is unavailable.'); }
}
async function readCursor(engine: BrainEngine, key: string, cached?: Cursor): Promise<Cursor | null> {
+ if (isPassBatchKey(key)) return readPassBatch<Cursor>(key);
const [row] = await engine.executeRaw<{ completed_keys: [CursorHeader] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [OP, key]);
const value = row?.completed_keys?.[0];
if (!value) return null;
@@ -248,6 +259,7 @@ async function writeCursor(tx: BrainEngine, key: string, before: Cursor | null,
// #6643: a cursor records the indexes it settles without a commit from its first save by this build on; a cursor saved
// before (a run that began on an older build) starts recording at the index it had then.
if (!next.settled) next.settled = before && before.runId === next.runId ? { from: before.settled?.from ?? before.index, ranges: before.settled?.ranges ?? [] } : { from: 0, ranges: [] };
+ if (isPassBatchKey(key)) return await passBatchStep(tx, key, before && JSON.stringify(header(before)), next, JSON.stringify(header(next)), inTx) ? next : currentCursor(tx, key, next);
if (before === null) {
if (synchronous) await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);
@@ -454,7 +466,8 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
await validateSyncAuthority(engine, cursor.authority, slug);
assertActive();
if (entry?.action === 'import') await faultPoint('sync:after_freeze', { sourceId: cursor.sourceId, slug, path: entry.path });
- return remember(frozenSnapshot, { requestId: randomUUID(), slug, pageId, ...(occupantRebound ? { rebound: true as const } : {}), intent: { kind: !entry ? 'managed_sync_checkpoint' : entry.action === 'import' ? 'managed_sync_import' : 'managed_sync_delete',
+ const passLevel = cursor.passId ? (entry as PassEntry | undefined)?.level ?? (entry ? null : cursor.target) : undefined;
+ return remember(frozenSnapshot, { requestId: cursor.passId ? passRequestId(cursor.passId, entry?.path ?? slug, passLevel!) : randomUUID(), slug, pageId, ...(occupantRebound ? { rebound: true as const } : {}), intent: { kind: !entry ? 'managed_sync_checkpoint' : entry.action === 'import' ? 'managed_sync_import' : 'managed_sync_delete',
expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly,
...(entry?.unownedDeletion ? { unownedDeletion: true } : {}),
...(entry?.renameFrom ? { renameFrom: entry.renameFrom } : {}),
@@ -466,8 +479,9 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
// A cursor created before its options were recorded has the same key, so this run's options are its options.
...(!entry ? { syncOptions: cursor.syncOptions ?? run.syncOptions, ...(run.repoPath ? { repoPath: run.repoPath } : {}) } : {}),
...(!entry && cursor.overtaken ? { overtaken: true } : {}), ...(!entry && cursor.slice ? { slice: cursor.slice } : {}),
- ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority, cursorKey: key, runId: cursor.runId,
- slugMode: cursor.slugMode, index: cursor.index, total: cursor.entries.length, from: cursor.from, target: cursor.target, working: entry?.working ?? false,
+ ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority, ...cursorIntent(cursor, key),
+ ...(cursor.passId ? { level: passLevel ?? null, ...(!entry && cursor.stamp ? { 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 } } : {}) } });
}
@@ -856,7 +870,7 @@ async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor;
const revived = await reviveCheckpoint(engine, input);
if (revived) { input.assertActive(); return { cursor: revived }; }
const fault = receiptClass(done);
- if (fault === 'transport' || isSyncKnockOn(done) || (fault === 'systemic' && resumableStop(done) && pending.intent.kind !== 'managed_sync_checkpoint' && await stopRecorded(engine, key, cursor.runId))) {
+ if (fault === 'transport' || isSyncKnockOn(done) || (fault === 'systemic' && resumableStop(done) && pending.intent.kind !== 'managed_sync_checkpoint' && await stopRecorded(engine, cursor.failureKey ?? key, cursor.runId))) {
const refrozen = await refreezeInPlace(engine, input);
if (refrozen) { input.assertActive(); return { cursor: refrozen }; }
}
@@ -870,7 +884,7 @@ async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor;
const { failure, ledgerRecorded } = await recordManagedSyncFailure(engine, { source_id: cursor.sourceId, source_incarnation: cursor.incarnation, path: pending.intent.path ?? '<checkpoint>',
code: done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'), message: done.error_message ?? 'The accepted sync request did not commit.',
...(rootCause ? { root_cause: rootCause } : {}),
- request_id: pending.requestId, run_id: cursor.runId, target: cursor.target, cursor_key: key,
+ request_id: pending.requestId, run_id: cursor.runId, target: cursor.target, cursor_key: cursor.failureKey ?? key,
syncOptions: cursor.syncOptions ?? syncOptions, processingOptions: cursor.processingOptions ?? processingOptions,
phase: pending.intent.kind === 'managed_sync_checkpoint' ? 'checkpoint' : 'receipt', state: done.state, observation_id: pending.requestId,
first_seen: new Date(done.completed_at ?? done.updated_at).toISOString(), ...(done.error_detail ? { write_error_detail: publicFailureDetail(done.error_detail) } : {}) });
@@ -914,7 +928,7 @@ async function sameContentAtOrigin(engine: BrainEngine, cursor: Cursor, entry: C
if (!snapshot || snapshot.page.deleted_at != null) return false;
const intent: SyncIntent = { kind: 'managed_sync_import', expected_revision: snapshot.revision, sourcePath: entry.sourcePath, path: entry.path, rawHash, content, lineEndingOnly,
processingOptions: cursor.processingOptions, ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority,
- cursorKey: key, runId: cursor.runId, slugMode: cursor.slugMode, index: cursor.index, total: cursor.entries.length, from: cursor.from, target: cursor.target, working: entry.working ?? false };
+ ...cursorIntent(cursor, key), slugMode: cursor.slugMode, from: cursor.from, target: cursor.target, working: entry.working ?? false };
try {
const budgetMs = await syncPreparationBudgetMs(engine);
const prepared = await raceSyncBudget(prepareManagedSyncMutation(engine, screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: snapshot.page.slug,
@@ -926,6 +940,15 @@ async function sameContentAtOrigin(engine: BrainEngine, cursor: Cursor, entry: C
}
}
+/**
+ * The cursor fields of a frozen intent: a cursor's key, run and position, or (#6712 PR 4b) a pass batch's `passId` and the
+ * open episode its import records (`fullEpisode`); the #6862 FIFO guard reads neither (it keys on kind, slug, page and `renameFrom`).
+ */
+function cursorIntent(cursor: Cursor, key: string): Pick<SyncIntent, 'cursorKey' | 'runId' | 'index' | 'total' | 'passId' | 'fullEpisode'> {
+ return cursor.passId ? { passId: cursor.passId, ...(cursor.fullEpisode ? { fullEpisode: cursor.fullEpisode } : {}) }
+ : { cursorKey: key, runId: cursor.runId, index: cursor.index, total: cursor.entries.length };
+}
+
/** Counts a committed page into the cursor, as the single path does. */
function countCommitted(counts: Cursor['counts'], pending: Pending, outcome: WriteRequest['outcome']): void {
if (outcome?.noop !== true) {
@@ -1076,6 +1099,7 @@ function groupSize(cursor: Cursor, bulk: BulkPass): number {
async function admitAndSave(engine: BrainEngine, key: string, before: Cursor, next: Cursor, members: Pending[], assertActive: () => void): Promise<Cursor | null> {
const rows = await admitGroup(engine, members, before, async tx => {
assertActive();
+ if (isPassBatchKey(key)) return passBatchStep(tx, key, JSON.stringify(header(before)), next, JSON.stringify(header(next)));
const [saved] = await pipelined(tx, [
() => tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now()
WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb RETURNING fingerprint`, [OP, key, JSON.stringify([header(before)]), JSON.stringify([header(next)])]),
@@ -1185,6 +1209,7 @@ async function admitWindowGroup(engine: BrainEngine, cursor: Cursor, key: string
const members = cursor.window![slot]!;
if ((await readAdmitted(engine, cursor, members)).length >= members.length) return true;
const rows = await admitGroup(engine, members, cursor, async tx => {
+ if (isPassBatchKey(key)) return readPassBatch<Cursor>(key)?.window?.[slot]?.[0]?.requestId === members[0]!.requestId;
const [held] = await tx.executeRaw<{ request_id: string | null }>(`SELECT completed_keys->0->'window'->($3::int)->0->>'requestId' AS request_id FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key, slot]);
return held?.request_id === members[0]!.requestId;
}).catch(() => null);
@@ -1483,7 +1508,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
let key = managedCursorKey(context.incarnation, company); // #6712 PR 1: one per incarnation; resolvePassCursor may pick an older key's cursor
let cursor: Cursor | null = null;
let missingManifestCursor: CursorHeader | null = null;
- if (!company) Object.assign(state, { sourceId: context.sourceId, incarnation: context.incarnation, remote: authority.writer.remote, cursor: () => cursor });
+ if (!company) Object.assign(state, { sourceId: context.sourceId, incarnation: context.incarnation, remote: authority.writer.remote, cursor: () => live.cursor ?? cursor });
const dryRun = (value: Cursor, base: Cursor = value) => managedDryRun(engine, value, base, { company: !!company, processingOptions, syncOptions, repoPath: frozenRun.repoPath, remote: authority.writer.remote });
let phase: ManagedSyncFailure['phase'] = 'resume';
let discoveryTarget: string | null = null;
@@ -1498,8 +1523,185 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
// #6696 C4: the checkpoint commit is the run's last commit. #6712 PR 2 (L5): its tail (statistics, links) is owed from that
// commit (sync-tail.ts) and runs after the lease is released, outside this governed pass.
const finishing = (done: Cursor) => { opts.onProgress?.({ phase: 'managed_sync.finish', bankedFiles: done.index, total: done.entries.length }); };
+ /** One cursor's drain (or, #6712 PR 4b, one round batch of a live pass): the freeze, screen, waive, group, admit, await and settle loop. */
+ const live: { cursor: Cursor | null } = { cursor: null };
+ const drainCursor = async (from: Cursor, startupConfig: Awaited<ReturnType<typeof preparationConfigView>>, retried: boolean,
+ sliceBase?: { started: number; pages: number }): Promise<SyncResult | Cursor> => {
+ let cursor = from;
+ try {
+ frozenRun.screen = company ? null : await loadSyncScreenRun(startupConfig, cursor.sourceId, cursor.processingOptions ?? processingOptions, authority.writer.remote);
+ const observedAt = frozenRun.observedAt = cursor.discoveredAt ?? runStartedAt;
+ if (frozenRun.screen && !retried && cursor.pending && !cursor.done) {
+ phase = 'freeze';
+ cursor = await convertBlockedCursor(engine, cursor, key, assertActive, frozenRun);
+ }
+ const config = loadConfig() ?? { engine: engine.kind }, analyzeEvery = await importAnalyzeEveryPages(engine);
+ let batchStart = performance.now(), batchPages = 0, foregroundWaitStart = 0, foregroundBaseline = 0;
+ let creditedPages = 0, creditStarted = 0, foregroundQueued = false;
+ const sliceStarted = sliceBase?.started ?? performance.now(), sliceFirstIndex = cursor.index - (sliceBase?.pages ?? 0), drainStartedAt = opts.drainStartedAt ?? Date.now();
+ const bulk: BulkPass = { settings: opts.bulk && !company ? opts.bulk : { enabled: false, reason: null, size: 1, maxTxnMs: 0 }, perMemberMs: null, foregroundFirst: await foregroundPriority(engine) };
+ const waiveBatch = noopWaiversEnabled() && await waiverBatchEnabled(startupConfig), prescreen = { missed: new Set<number>(), limit: Infinity, drainStartedAt, assertActive, signal, onProgress: opts.onProgress,
+ embeddingRequested: !(cursor.processingOptions ?? processingOptions).noEmbed && !opts.embedDeferred && !config.embedding_disabled && !!config.embedding_model?.trim() };
+ if (opts.capacityPreflight && !cursor.done) await preflightSyncCapacity(engine, { root: cursor.root, writer: cursor.authority.writer, entries: cursor.entries.slice(cursor.index) });
+ 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;
+ 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;
+ const [foreground] = await engine.executeRaw(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid
+ AND state IN ('queued','running','recovering') AND NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%') LIMIT 1`, [cursor.binding.worktree_id]);
+ assertActive();
+ if ((foregroundQueued = Boolean(foreground))) bulk.foregroundAt = performance.now();
+ if (foreground && creditedPages === 0 && !bulk.foregroundFirst) {
+ startPersistenceConsumer(engine, config);
+ if (!foregroundWaitStart) {
+ foregroundWaitStart = performance.now();
+ foregroundBaseline = foregroundWriteCompletions(engine, cursor.binding.worktree_id);
+ }
+ const completed = foregroundWriteCompletions(engine, cursor.binding.worktree_id) - foregroundBaseline;
+ if (completed < 25 && performance.now() - foregroundWaitStart < 1000) {
+ await new Promise(resolve => setTimeout(resolve, 25));
+ continue;
+ }
+ creditedPages = 25; creditStarted = performance.now();
+ }
+ foregroundWaitStart = 0;
+ const prescreened = await prescreenRun(engine, cursor, key, { ...prescreen, limit: slice ? slice.maxPages - (cursor.index - sliceFirstIndex) : Infinity });
+ if (prescreened && slice && (prescreened.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(prescreened, 'partial', 'writer_yield');
+ if (prescreened) { cursor = prescreened; continue; }
+ phase = 'freeze'; stampDrainStep('freeze', signal);
+ const next = await freezeNext(engine, cursor, key, assertActive, frozenRun, observedAt);
+ if ('saved' in next) {
+ cursor = next.saved;
+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, ...(next.held ? {} : { total: cursor.entries.length, waived: true }) }); assertActive();
+ if (next.held && slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
+ continue;
+ }
+ const { frozen, deferredAt } = next;
+ const waived: Cursor | null = waiveBatch && !frozen.rebound && deferredAt === undefined ? await waiveRun(engine, cursor, frozen, key, config, assertActive, frozenRun, drainStartedAt,
+ slice ? slice.maxPages - (cursor.index - sliceFirstIndex) : WAIVER_RUN_MAX, opts.onProgress) : null;
+ if (waived && slice && (waived.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(waived, 'partial', 'writer_yield');
+ if (waived) { cursor = waived; continue; }
+ cursor = await saveCursor(engine, key, cursor, { ...cursor, ...(frozen.rebound ? { overtaken: true as const } : {}), pending: frozen }, false, assertActive);
+ }
+ if (!cursor.pending) continue; // another owner-loop advanced the cursor
+ const pending: Pending = cursor.pending;
+ phase = 'admission'; stampDrainStep('admission', signal);
+ const prior = await getWriteRequest(engine, admittedBy(pending, cursor), pending.requestId);
+ assertActive();
+ // #5470/#5984: a frozen entry whose publication would change nothing advances the cursor without an admission.
+ const screened: Cursor = cursor;
+ const waived: Cursor | null = prior ? null : await waiveNoopEntry(engine, screened, pending, config, key,
+ (tx, noop) => writeCursor(tx, key, screened, { ...waivedCursor(screened, noop, indexOf(screened, pending)), progress: stampProgress(screened.progress, screened.index, screened.index + 1, drainStartedAt) },
+ holdClear(screened, pending.intent.path, observedAt)), tx => currentCursor(tx, key, screened), signal);
+ if (waived) {
+ cursor = waived;
+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length, waived: true });
+ assertActive();
+ // A skipped entry still counts toward the caller's slice, so a sliced run yields at the same positions.
+ if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
+ continue;
+ }
+ const freezeAt: FreezeAt = base => async index => { if (base.entries[index]?.prescreened && !prescreen.missed.has(index)) return null; const frozen = await freezeEntry(engine, { ...base, index }, key, assertActive, frozenRun); return 'requestId' in frozen ? frozen : null; };
+ if (bulk.settings.enabled && (bulk.foregroundFirst || !foregroundQueued) && !prior && !cursor.group && !pending.rebound && indexOf(cursor, pending) === cursor.index && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);
+ if (cursor.group?.[0]?.requestId === pending.requestId && cursor.pending?.requestId === pending.requestId) {
+ const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000 }, drainStartedAt, opts.onProgress,
+ opts.drainStartedAt ? next => admitAhead(engine, next, key, bulk, config, freezeAt, assertActive) : undefined);
+ if ('result' in step) return step.result;
+ cursor = step.cursor;
+ assertActive();
+ continue;
+ }
+ const admitting = cursor;
+ const row = prior ?? await retryWriteAdmission(pending.requestId, remaining => engine.transaction(async tx => {
+ assertActive();
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",
+ [`${Math.min(1000, remaining)}ms`, `${remaining}ms`]);
+ const accepted = await admitWriteInTransaction(tx, { requestId: pending.requestId, operation: 'submit_job',
+ sourceId: admitting.sourceId, sourceIncarnation: admitting.incarnation, slug: pending.slug, pageId: pending.pageId,
+ worktreeId: admitting.binding.worktree_id, topologyGeneration: admitting.binding.topology_generation,
+ principal: admitting.authority.writer.principal, authority: admitting.authority.writer, callerIntent: pending.intent, intent: pending.intent });
+ // ENG-A7: after the counter locks (the publication lock order), admit only while the cursor still holds this entry
+ // with this intent (#6075: a bulk pass may have grouped the head since this pass read it).
+ if (isPassBatchKey(key)) {
+ // #6712 PR 4b: a pass batch has no cursor row; the lease (below) fences it, and the batch must still hold this entry.
+ const head = readPassBatch<Cursor>(key)?.pending;
+ if (head?.requestId !== pending.requestId || digest(head.intent) !== digest(pending.intent)) throw new CursorMoved();
+ } else {
+ const [held] = await tx.executeRaw<{ request_id: string | null; same: boolean | null }>(`SELECT completed_keys->0->'pending'->>'requestId' AS request_id,
+ completed_keys->0->'pending'->'intent' = $3::text::jsonb AS same FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key, JSON.stringify(pending.intent)]);
+ if (held?.request_id !== pending.requestId || held.same !== true) throw new CursorMoved();
+ }
+ await assertDrainLease(tx, admitting.sourceId);
+ await assertPassAdmission(tx, [pending.intent]);
+ assertActive();
+ return accepted;
+ }), undefined, error => engine.reconnect({ error })).catch(error => cursorMovedAdmission(engine, key, admitting, pending, error));
+ if (!row) { cursor = await currentCursor(engine, key, cursor); continue; }
+ await validateSyncAuthority(engine, cursor.authority, pending.slug);
+ assertSyncDispatchActive(); stampDrainStep('await_receipt', signal);
+ // #5762: a checkpoint's validation runs under the coordinator's 5 s statement timeout, so its wait outlasts that
+ // budget; a timed-out checkpoint then reports its terminal refusal and hint in this run instead of the next.
+ // #5984: a drain re-enters anyway, so it waits longer per page instead of paying a full re-entry; its stop signal bounds the wait.
+ const waited = await awaitWrite(engine, row, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: pending.intent.kind === 'managed_sync_checkpoint' ? 8000 : 5000 });
+ const done = waited.row;
+ assertSyncDispatchActive();
+ if (!isTerminalWriteState(done.state)) {
+ return { ...result(cursor, 'partial', signal?.aborted ? 'timeout' : 'writer_pending'),
+ ...(authority.writer.remote ? {} : { managedWrite: writeDiagnostic(cursor, pending, done), writeWait: writeWaitOf(waited) }) };
+ }
+ // #6712 PR 4b: a pass's refused stamp, or a write sync.admission paused at publication, ends the pass, never the page.
+ if (done.state !== 'committed' && cursor.passId && (pending.intent.kind === 'managed_sync_checkpoint' || done.error_code === 'admission_paused')) {
+ return { ...result(cursor, done.error_code === 'admission_paused' ? 'partial' : 'blocked_by_failures', done.error_code === 'admission_paused' ? 'admission_paused' : undefined),
+ ...(authority.writer.remote ? {} : { managedWrite: writeDiagnostic(cursor, pending, done) }) };
+ }
+ if (done.state !== 'committed') {
+ const settled = await settleFailedRequest(engine, { cursor, key, pending, done, assertActive, run: frozenRun, syncOptions, processingOptions,
+ remote: authority.writer.remote, waitMs: opts.drainStartedAt ? 30_000 : 5000, signal });
+ if ('result' in settled) return settled.result;
+ cursor = settled.cursor;
+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length });
+ continue;
+ }
+ if (pending.intent.kind === 'managed_sync_checkpoint' && cursor.passId) return { ...cursor, pending: undefined, done: true };
+ if (pending.intent.kind === 'managed_sync_checkpoint') {
+ cursor = (await readCursor(engine, key))!;
+ if (!cursor?.done) throw syncRunRefusal('storage_error', 'Committed sync checkpoint lost its cursor.',
+ { sourceId: context.sourceId, processingOptions: pending.intent.processingOptions, syncOptions: pending.intent.syncOptions ?? syncOptions, repoPath: pending.intent.repoPath ?? frozenRun.repoPath },
+ `The final checkpoint request ${pending.requestId} of this sync committed, but its cursor could not be read back to finish the run.`);
+ finishing(cursor); return finishCheckpoint(engine, key, cursor, !!company, assertActive);
+ }
+ // The frozen manifest is shared; only the cursor header changes per page.
+ 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 });
+ // 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();
+ if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
+ batchPages++;
+ if (creditedPages) creditedPages--;
+ if (batchPages >= 25 || performance.now() - batchStart >= 250) {
+ opts.onProgress?.({ phase: 'managed_sync.yield', bankedFiles: cursor.index });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ batchPages = 0; batchStart = performance.now();
+ }
+ }
+ finishing(cursor); return result(cursor, cursor.from === null ? 'first_sync' : 'synced');
+ } finally { live.cursor = cursor; }
+ };
try {
assertActive();
+ // #6712 PR 4b (design v3.2 §3.1): a non-company source syncs by the live level-triggered pass; company brains and dry
+ // runs keep the frozen manifest and its cursor.
+ if (!company && !opts.dryRun) {
+ return await runSyncPass(engine, { opts, slice, context, authority, processingOptions, syncOptions, assertActive, signal, state, runStartedAt,
+ drainBatch: async (batchKey, batch, sliceBase) => { key = batchKey; return drainCursor(batch, await preparationConfigView(engine), false, sliceBase); } });
+ }
const resolved = await resolvePassCursor(engine, { sourceId: context.sourceId, incarnation: context.incarnation, company, remote: authority.writer.remote, dryRun: !!opts.dryRun, assertActive, state });
key = resolved.key;
if (resolved.waiting) return resolved.waiting;
@@ -1582,156 +1784,10 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
`The unfinished sync cursor of source ${cursor.sourceId} was written under an older binding (its owner epoch, topology generation, worktree or root changed since), so this run stopped without importing; the retry rediscovers against the current binding.`);
}
if (opts.dryRun) return dryRun(cursor);
- frozenRun.screen = company ? null : await loadSyncScreenRun(startupConfig, cursor.sourceId, cursor.processingOptions ?? processingOptions, authority.writer.remote);
- const observedAt = frozenRun.observedAt = cursor.discoveredAt ?? runStartedAt;
- if (frozenRun.screen && !retried && cursor.pending && !cursor.done) {
- phase = 'freeze';
- cursor = await convertBlockedCursor(engine, cursor, key, assertActive, frozenRun);
- }
- const config = loadConfig() ?? { engine: engine.kind }, analyzeEvery = await importAnalyzeEveryPages(engine);
- let batchStart = performance.now(), batchPages = 0, foregroundWaitStart = 0, foregroundBaseline = 0;
- let creditedPages = 0, creditStarted = 0, foregroundQueued = false;
- const sliceStarted = performance.now(), sliceFirstIndex = cursor.index, drainStartedAt = opts.drainStartedAt ?? Date.now();
- const bulk: BulkPass = { settings: opts.bulk && !company ? opts.bulk : { enabled: false, reason: null, size: 1, maxTxnMs: 0 }, perMemberMs: null, foregroundFirst: await foregroundPriority(engine) };
- const waiveBatch = noopWaiversEnabled() && await waiverBatchEnabled(startupConfig), prescreen = { missed: new Set<number>(), limit: Infinity, drainStartedAt, assertActive, signal, onProgress: opts.onProgress,
- embeddingRequested: !(cursor.processingOptions ?? processingOptions).noEmbed && !opts.embedDeferred && !config.embedding_disabled && !!config.embedding_model?.trim() };
- if (opts.capacityPreflight && !cursor.done) await preflightSyncCapacity(engine, { root: cursor.root, writer: cursor.authority.writer, entries: cursor.entries.slice(cursor.index) });
- opts.onProgress?.({ phase: 'managed_sync.start', bankedFiles: cursor.index, total: cursor.entries.length });
- while (!cursor.done) {
- assertActive();
- 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;
- const [foreground] = await engine.executeRaw(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid
- AND state IN ('queued','running','recovering') AND NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%') LIMIT 1`, [cursor.binding.worktree_id]);
- assertActive();
- if ((foregroundQueued = Boolean(foreground))) bulk.foregroundAt = performance.now();
- if (foreground && creditedPages === 0 && !bulk.foregroundFirst) {
- startPersistenceConsumer(engine, config);
- if (!foregroundWaitStart) {
- foregroundWaitStart = performance.now();
- foregroundBaseline = foregroundWriteCompletions(engine, cursor.binding.worktree_id);
- }
- const completed = foregroundWriteCompletions(engine, cursor.binding.worktree_id) - foregroundBaseline;
- if (completed < 25 && performance.now() - foregroundWaitStart < 1000) {
- await new Promise(resolve => setTimeout(resolve, 25));
- continue;
- }
- creditedPages = 25; creditStarted = performance.now();
- }
- foregroundWaitStart = 0;
- const prescreened = await prescreenRun(engine, cursor, key, { ...prescreen, limit: slice ? slice.maxPages - (cursor.index - sliceFirstIndex) : Infinity });
- if (prescreened && slice && (prescreened.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(prescreened, 'partial', 'writer_yield');
- if (prescreened) { cursor = prescreened; continue; }
- phase = 'freeze'; stampDrainStep('freeze', signal);
- const next = await freezeNext(engine, cursor, key, assertActive, frozenRun, observedAt);
- if ('saved' in next) {
- cursor = next.saved;
- opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, ...(next.held ? {} : { total: cursor.entries.length, waived: true }) }); assertActive();
- if (next.held && slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
- continue;
- }
- const { frozen, deferredAt } = next;
- const waived: Cursor | null = waiveBatch && !frozen.rebound && deferredAt === undefined ? await waiveRun(engine, cursor, frozen, key, config, assertActive, frozenRun, drainStartedAt,
- slice ? slice.maxPages - (cursor.index - sliceFirstIndex) : WAIVER_RUN_MAX, opts.onProgress) : null;
- if (waived && slice && (waived.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(waived, 'partial', 'writer_yield');
- if (waived) { cursor = waived; continue; }
- cursor = await saveCursor(engine, key, cursor, { ...cursor, ...(frozen.rebound ? { overtaken: true as const } : {}), pending: frozen }, false, assertActive);
- }
- if (!cursor.pending) continue; // another owner-loop advanced the cursor
- const pending: Pending = cursor.pending;
- phase = 'admission'; stampDrainStep('admission', signal);
- const prior = await getWriteRequest(engine, admittedBy(pending, cursor), pending.requestId);
- assertActive();
- // #5470/#5984: a frozen entry whose publication would change nothing advances the cursor without an admission.
- const screened: Cursor = cursor;
- const waived: Cursor | null = prior ? null : await waiveNoopEntry(engine, screened, pending, config, key,
- (tx, noop) => writeCursor(tx, key, screened, { ...waivedCursor(screened, noop, indexOf(screened, pending)), progress: stampProgress(screened.progress, screened.index, screened.index + 1, drainStartedAt) },
- holdClear(screened, pending.intent.path, observedAt)), tx => currentCursor(tx, key, screened), signal);
- if (waived) {
- cursor = waived;
- opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length, waived: true });
- assertActive();
- // A skipped entry still counts toward the caller's slice, so a sliced run yields at the same positions.
- if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
- continue;
- }
- const freezeAt: FreezeAt = base => async index => { if (base.entries[index]?.prescreened && !prescreen.missed.has(index)) return null; const frozen = await freezeEntry(engine, { ...base, index }, key, assertActive, frozenRun); return 'requestId' in frozen ? frozen : null; };
- if (bulk.settings.enabled && (bulk.foregroundFirst || !foregroundQueued) && !prior && !cursor.group && !pending.rebound && indexOf(cursor, pending) === cursor.index && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);
- if (cursor.group?.[0]?.requestId === pending.requestId && cursor.pending?.requestId === pending.requestId) {
- const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000 }, drainStartedAt, opts.onProgress,
- opts.drainStartedAt ? next => admitAhead(engine, next, key, bulk, config, freezeAt, assertActive) : undefined);
- if ('result' in step) return step.result;
- cursor = step.cursor;
- assertActive();
- continue;
- }
- const admitting = cursor;
- const row = prior ?? await retryWriteAdmission(pending.requestId, remaining => engine.transaction(async tx => {
- assertActive();
- await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",
- [`${Math.min(1000, remaining)}ms`, `${remaining}ms`]);
- const accepted = await admitWriteInTransaction(tx, { requestId: pending.requestId, operation: 'submit_job',
- sourceId: admitting.sourceId, sourceIncarnation: admitting.incarnation, slug: pending.slug, pageId: pending.pageId,
- worktreeId: admitting.binding.worktree_id, topologyGeneration: admitting.binding.topology_generation,
- principal: admitting.authority.writer.principal, authority: admitting.authority.writer, callerIntent: pending.intent, intent: pending.intent });
- // ENG-A7: after the counter locks (the publication lock order), admit only while the cursor still holds this entry
- // with this intent (#6075: a bulk pass may have grouped the head since this pass read it).
- const [held] = await tx.executeRaw<{ request_id: string | null; same: boolean | null }>(`SELECT completed_keys->0->'pending'->>'requestId' AS request_id,
- completed_keys->0->'pending'->'intent' = $3::text::jsonb AS same FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key, JSON.stringify(pending.intent)]);
- if (held?.request_id !== pending.requestId || held.same !== true) throw new CursorMoved();
- await assertDrainLease(tx, admitting.sourceId);
- assertActive();
- return accepted;
- }), undefined, error => engine.reconnect({ error })).catch(error => cursorMovedAdmission(engine, key, admitting, pending, error));
- if (!row) { cursor = await currentCursor(engine, key, cursor); continue; }
- await validateSyncAuthority(engine, cursor.authority, pending.slug);
- assertSyncDispatchActive(); stampDrainStep('await_receipt', signal);
- // #5762: a checkpoint's validation runs under the coordinator's 5 s statement timeout, so its wait outlasts that
- // budget; a timed-out checkpoint then reports its terminal refusal and hint in this run instead of the next.
- // #5984: a drain re-enters anyway, so it waits longer per page instead of paying a full re-entry; its stop signal bounds the wait.
- const waited = await awaitWrite(engine, row, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: pending.intent.kind === 'managed_sync_checkpoint' ? 8000 : 5000 });
- const done = waited.row;
- assertSyncDispatchActive();
- if (!isTerminalWriteState(done.state)) {
- return { ...result(cursor, 'partial', signal?.aborted ? 'timeout' : 'writer_pending'),
- ...(authority.writer.remote ? {} : { managedWrite: writeDiagnostic(cursor, pending, done), writeWait: writeWaitOf(waited) }) };
- }
- if (done.state !== 'committed') {
- const settled = await settleFailedRequest(engine, { cursor, key, pending, done, assertActive, run: frozenRun, syncOptions, processingOptions,
- remote: authority.writer.remote, waitMs: opts.drainStartedAt ? 30_000 : 5000, signal });
- if ('result' in settled) return settled.result;
- cursor = settled.cursor;
- opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length });
- continue;
- }
- if (pending.intent.kind === 'managed_sync_checkpoint') {
- cursor = (await readCursor(engine, key))!;
- if (!cursor?.done) throw syncRunRefusal('storage_error', 'Committed sync checkpoint lost its cursor.',
- { sourceId: context.sourceId, processingOptions: pending.intent.processingOptions, syncOptions: pending.intent.syncOptions ?? syncOptions, repoPath: pending.intent.repoPath ?? frozenRun.repoPath },
- `The final checkpoint request ${pending.requestId} of this sync committed, but its cursor could not be read back to finish the run.`);
- finishing(cursor); return finishCheckpoint(engine, key, cursor, !!company, assertActive);
- }
- // The frozen manifest is shared; only the cursor header changes per page.
- 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 });
- // 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();
- if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
- batchPages++;
- if (creditedPages) creditedPages--;
- if (batchPages >= 25 || performance.now() - batchStart >= 250) {
- opts.onProgress?.({ phase: 'managed_sync.yield', bankedFiles: cursor.index });
- await new Promise(resolve => setTimeout(resolve, 0));
- batchPages = 0; batchStart = performance.now();
- }
- }
- finishing(cursor); return result(cursor, cursor.from === null ? 'first_sync' : 'synced');
+ return await drainCursor(cursor, startupConfig, retried !== null);
} catch (error) {
assertSyncDispatchActive();
+ if (live.cursor) cursor = live.cursor;
if (signal?.aborted && error instanceof Error && error.name === 'AbortError') {
if (cursor) return result(cursor, 'partial', 'timeout');
if (missingManifestCursor) return result(missingManifestCursor, 'partial', 'timeout');
@@ -1750,7 +1806,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
const failedCursor = cursor ?? stored?.completed_keys?.[0];
const { failure } = await recordManagedSyncFailure(engine, { source_id: context.sourceId, source_incarnation: context.incarnation, path: cursor?.entries[cursor.index]?.path ?? failedCursor?.pending?.intent.path ?? `<${phase}>`, code,
message: error instanceof Error ? error.message : String(error), request_id: failedCursor?.pending?.requestId ?? null,
- run_id: failedCursor?.runId ?? discoveryRun, target: failedCursor?.target ?? discoveryTarget, cursor_key: key,
+ run_id: failedCursor?.runId ?? discoveryRun, target: failedCursor?.target ?? discoveryTarget, cursor_key: cursor?.failureKey ?? key,
syncOptions: failedCursor?.syncOptions ?? syncOptions, processingOptions: failedCursor?.processingOptions ?? processingOptions, phase, state: 'failed',
observation_id: failedCursor ? `${failedCursor.runId}:${failedCursor.index}:${phase}:${code}` : `${key}:discovery:${discoveryTarget}:${code}` });
if (error instanceof Error) error.message = authority.writer.remote ? 'Managed sync is blocked; ask the host operator to inspect doctor.' : `${formatManagedSyncFailure(failure)} Fix the cause, then run: ${managedSyncRetryCommand(failure, frozenRun.repoPath)}`;
diff --git a/src/core/persistence/sync-tail-record.ts b/src/core/persistence/sync-tail-record.ts
index 081c82c691..a94c673c52 100644
--- a/src/core/persistence/sync-tail-record.ts
+++ b/src/core/persistence/sync-tail-record.ts
@@ -23,6 +23,18 @@ export async function recordSyncTail(tx: Pick<BrainEngine, 'executeRaw'>, source
[SYNC_TAIL_OP, sourceId, runId, cursorKey]);
}
+/**
+ * #6712 PR 4b (design v3.2 §3.3): a live pass's stamp records its tail like a cursor's checkpoint, from the counts the pass
+ * carries (there is no cursor row to read them from): `run_id` is the pass id.
+ */
+export async function recordPassTail(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, passId: string, tail: { changed: number; extract: boolean }): Promise<void> {
+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at)
+ VALUES ($1, $2, jsonb_build_array(jsonb_build_object('run_id',$3::text,'at',now(),'changed',$4::int,'extract',$5::boolean)), now())
+ ON CONFLICT (op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=CASE WHEN jsonb_array_length(op_checkpoints.completed_keys)>=${SYNC_TAIL_KEEP}
+ THEN (op_checkpoints.completed_keys-0)||EXCLUDED.completed_keys ELSE op_checkpoints.completed_keys||EXCLUDED.completed_keys END`,
+ [SYNC_TAIL_OP, sourceId, passId, tail.changed, tail.extract]);
+}
+
/** The source's owed tail, or null when none is owed. */
export async function readSyncTail(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<TailObligation[] | null> {
const [row] = await engine.executeRaw<{ completed_keys: TailObligation[] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_TAIL_OP, sourceId]);
diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.ts
index cf47e2e3e2..7f5b4460c6 100644
--- a/src/core/persistence/sync-waivers.ts
+++ b/src/core/persistence/sync-waivers.ts
@@ -27,6 +27,18 @@ import { noteDrainSql } from './drain-step.ts';
import { REVISION_BACKFILL_PENDING } from '../page-state/types.ts';
import { withScreeningPaths } from './screening-paths.ts';
import { withBoundedReadSession } from './bounded-reads.ts';
+import { isPassBatchKey, passBatchHead } from './sync-pass-batch.ts';
+
+/**
+ * The cursor row a waiver commits beside, locked FOR UPDATE (the fixed order: the page guard, then the cursor). #6712 PR 4b:
+ * a live pass's batch has no row; its head is read under the drain lease instead (`passBatchHead`).
+ */
+async function heldCursorHead(tx: BrainEngine, key: string, sourceId: string): Promise<{ run_id: string | null; index: number | string | null; request_id: string | null } | undefined> {
+ if (isPassBatchKey(key)) return passBatchHead(tx, key, sourceId);
+ const [held] = await tx.executeRaw<{ run_id: string | null; index: number | string | null; request_id: string | null }>(`SELECT completed_keys->0->>'runId' AS run_id,
+ completed_keys->0->'index' AS index,completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE`, [key]);
+ return held;
+}
export interface WaiverCursor { sourceId: string; incarnation: string; root: string; gitRoot: string; slugMode: 'git-root' | 'source-root';
binding: { worktree_id: string }; authority: SyncAuthority; runId: string; index: number }
@@ -117,8 +129,7 @@ export async function waiveNoopEntry<C extends WaiverCursor>(engine: BrainEngine
const intent = pending.intent;
return engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId: cursor.sourceId, slug: pending.slug }]);
- const [held] = await tx.executeRaw<{ run_id: string | null; index: number | string | null; request_id: string | null }>(`SELECT completed_keys->0->>'runId' AS run_id,
- completed_keys->0->'index' AS index,completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE`, [key]);
+ const held = await heldCursorHead(tx, key, cursor.sourceId);
if (held?.run_id !== cursor.runId || Number(held.index) !== cursor.index || held.request_id !== pending.requestId) return reread(tx);
const snapshot = await tx.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
if (waived.kind === 'delete') {
@@ -194,8 +205,7 @@ export async function waiveNoopRun<C extends WaiverCursor>(engine: BrainEngine,
return await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('lock_timeout','2s',true),set_config('statement_timeout','10s',true)");
await tx.lockPageKeys(run.map(entry => ({ sourceId: cursor.sourceId, slug: entry.pending.slug })));
- const [held] = await tx.executeRaw<{ run_id: string | null; index: number | string | null; request_id: string | null }>(`SELECT completed_keys->0->>'runId' AS run_id,
- completed_keys->0->'index' AS index,completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE`, [key]);
+ const held = await heldCursorHead(tx, key, cursor.sourceId);
if (held?.run_id !== cursor.runId || Number(held.index) !== cursor.index || held.request_id != null) return { cursor: await reread(tx), waived: 0 };
await faultPoint('sync:mid_waiver_run', { sourceId: cursor.sourceId });
// The run's screens may span many entries: an owner change since the first one sends the run back to the per-entry path.
@@ -277,8 +287,7 @@ export async function waivePrescreenedRun<C extends WaiverCursor & { binding: {
return await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('lock_timeout','2s',true),set_config('statement_timeout','10s',true)");
await tx.lockPageKeys(run.map(entry => ({ sourceId: cursor.sourceId, slug: entry.slug })));
- const [held] = await tx.executeRaw<{ run_id: string | null; index: number | string | null; request_id: string | null }>(`SELECT completed_keys->0->>'runId' AS run_id,
- completed_keys->0->'index' AS index,completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE`, [key]);
+ const held = await heldCursorHead(tx, key, cursor.sourceId);
if (held?.run_id !== cursor.runId || Number(held.index) !== cursor.index || held.request_id != null) return { cursor: await reread(tx), waived: 0 };
await faultPoint('sync:prescreened', { sourceId: cursor.sourceId });
const binding = await getWorktreeBinding(tx, cursor.sourceId);