Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): #6712 PR 4b item 6 pass defects found by the test rewrite

garrytan076100ab21b9
diff --git a/src/core/persistence/managed-sync-orphans.ts b/src/core/persistence/managed-sync-orphans.ts
index 6a02fdf4d4..0ecd8c4038 100644
--- a/src/core/persistence/managed-sync-orphans.ts
+++ b/src/core/persistence/managed-sync-orphans.ts
@@ -155,7 +155,7 @@ export async function classifyManagedSyncOrphans(engine: SqlEngine, sourceIds: s
FROM op_checkpoints f
JOIN sources s ON s.id=f.completed_keys->0->>'source_id' AND s.incarnation::text=f.completed_keys->0->>'source_incarnation' AND NOT COALESCE(s.archived,false)
WHERE f.op='managed-sync-failure' AND ($1::text[] IS NULL OR s.id=ANY($1::text[]))
- AND NOT EXISTS(SELECT 1 FROM op_checkpoints c WHERE c.op='managed-sync' AND c.fingerprint=f.fingerprint)
+ AND NOT EXISTS(SELECT 1 FROM op_checkpoints c WHERE c.op IN ('managed-sync','managed-sync-pass') AND c.fingerprint=f.fingerprint)
ORDER BY s.id,f.fingerprint`, [sourceIds]);
for (const row of failures) {
orphans.push({ kind: 'failure_row', cursor_key: row.cursor_key, source_id: row.source_id, source_incarnation: row.source_incarnation, run_id: row.run_id,
diff --git a/src/core/persistence/sync-blocked.ts b/src/core/persistence/sync-blocked.ts
index 3484ab4d37..4b3745d664 100644
--- a/src/core/persistence/sync-blocked.ts
+++ b/src/core/persistence/sync-blocked.ts
@@ -12,6 +12,7 @@
*/
import type { BrainEngine } from '../engine.ts';
import { readManagedSyncFailures } from './sync-failures.ts';
+import { passFingerprint } from './sync-pass-row.ts';
/** A run blocked longer than this fails doctor `managed_sync_blocked` and turns get_brain_health to `attention`. */
export const MANAGED_SYNC_BLOCKED_FAIL_MS = 60 * 60_000;
@@ -23,10 +24,16 @@ export async function readBlockedManagedSyncs(engine: BrainEngine, sourceIds?: s
SELECT c.fingerprint FROM op_checkpoints c LEFT JOIN op_checkpoints f ON f.op='managed-sync-failure' AND f.fingerprint=c.fingerprint
WHERE c.op='managed-sync' AND COALESCE(c.completed_keys->0->>'done','false')<>'true' AND (f.updated_at IS NULL OR f.updated_at>=c.updated_at)`)).map(row => row.fingerprint));
const { readPassReadings, passStopCode, passStuck, passStuckSince } = await import('./sync-pass-readers.ts');
+ const failures = await readManagedSyncFailures(engine, sourceIds);
+ // A pass blocked by a failed write names that write's code (its failure row is keyed by the pass fingerprint), as a cursor did.
+ const passFailure = (sourceId: string, incarnation: string) => failures.find(failure => failure.cursor_key === passFingerprint(sourceId, incarnation) && failure.code !== 'sync_incomplete');
const passes: BlockedManagedSync[] = (await readPassReadings(engine, { sourceIds, head: false })).filter(reading => passStuck(reading.health))
- .map(reading => ({ source_id: reading.source_id, code: passStopCode(reading), run_id: reading.row.value.telemetry.pass_id, blocked_since: passStuckSince(reading.row) }));
+ .map(reading => {
+ const failure = passStopCode(reading) === 'blocked_by_failures' ? passFailure(reading.source_id, reading.row.value.incarnation) : undefined;
+ return { source_id: reading.source_id, code: failure?.code ?? passStopCode(reading), run_id: reading.row.value.telemetry.pass_id, blocked_since: failure?.first_seen ?? passStuckSince(reading.row) };
+ });
const passSources = new Set(passes.map(blocked => blocked.source_id));
- return [...(await readManagedSyncFailures(engine, sourceIds))
+ return [...failures
.filter(failure => failure.code !== 'sync_incomplete' && cursors.has(failure.cursor_key) && !passSources.has(failure.source_id))
.map(failure => ({ source_id: failure.source_id, code: failure.code, run_id: failure.run_id, blocked_since: failure.first_seen })), ...passes];
}
diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.ts
index 26538d019f..ed14672f13 100644
--- a/src/core/persistence/sync-pass-apply.ts
+++ b/src/core/persistence/sync-pass-apply.ts
@@ -50,6 +50,7 @@ import { syncClassAction, type SyncClassAction } from './sync-classify.ts';
import type { SyncAdmission } from './sync-admission.ts';
import type { Action } from '../agent-output.ts';
import { slugUnderBoundPrefixes } from '../ops/context.ts';
+import { syncOriginPath } from './sync-origin.ts';
/** Legacy pages the sweep screens per pass after the incarnation's first full round (design §2.7, [estimated]). */
export const PASS_LEGACY_SWEEP_MAX = 500;
@@ -208,6 +209,8 @@ async function applyDeleteValve(engine: BrainEngine, level: ShadowLevel, input:
async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {
type Pending = { entry: ShadowPath; code: GitHoldCode; message: string; slug: string | null; meta: Partial<GitHoldMeta>; kind: keyof PassApplyState['holds'] };
const pending: Pending[] = [];
+ // A held rename's origin waits for its destination's hold (#5988), whatever its page did meanwhile.
+ const heldRenameOrigins = new Set(level.heldRenames.map(held => syncOriginPath(held.rename.sourcePath)));
for (const entry of level.paths) {
const r = entry.result;
if (r.settled || r.inFlight) continue;
@@ -218,6 +221,7 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Pa
message: `${path}: sync settled this file at the same level in ${streak.streak} passes in a row, but the next round never classified it settled, so sync held it instead of re-importing it every pass; the rest of the source synced.` });
continue;
}
+ if (r.cls === 'delete_drift' && heldRenameOrigins.has(syncOriginPath(passEntryPaths(level, entry.path).sourcePath))) continue;
if (r.cls === 'delete_drift') {
pending.push({ entry, code: 'file_drift', slug: entry.slug, kind: 'file_gone', meta: { side: 'deleted', state: 'file_gone', ...(entry.revision ? { page_revision: entry.revision } : {}) },
message: `${path}: the file is gone, but page ${entry.slug} changed in the database since the file was last imported, so sync held the deletion instead of deleting the page; the rest of the source synced.` });
diff --git a/src/core/persistence/sync-pass-row.ts b/src/core/persistence/sync-pass-row.ts
index 3e1bf0ad14..71cc9d33fc 100644
--- a/src/core/persistence/sync-pass-row.ts
+++ b/src/core/persistence/sync-pass-row.ts
@@ -69,6 +69,8 @@ export interface ManagedSyncPassValue {
legacy_sweep?: { first_full_at: string };
/** #6712 PR 4b (design §2.6): the set hash of a withheld mass delete; with the env valve set the next tick runs a full round to apply it. */
deletes_withheld?: string | null;
+ /** #6712 PR 3 (L7) on the pass: the page request a blocked pass stopped on, which the next pass replays while what refused it is unchanged. */
+ blocked?: { request_id: string; pass_id: string };
};
telemetry: {
pass_id: string;
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 2f34a0c695..523fb07a6d 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -14,12 +14,19 @@
* converging stop `resumable` (`not_converged`).
*/
import { randomUUID } from 'node:crypto';
+import { opError } from '../ops/contract.ts';
+import { confirmedSyncDelta } from '../sync-rename-identity.ts';
+import type { DowngradedRename } from '../sync.ts';
import type { BrainEngine } from '../engine.ts';
import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
import type { Cursor, RetryWait } from './sync-run.ts';
+import { getWriteRequestById } from './journal.ts';
+import type { WriteRequest } from './model.ts';
+import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';
+import { recordedStop, replaysUnchangedRefusal } from './sync-stop-class.ts';
import { adoptLegacyPage, syncExcludePatterns, syncGit, type LegacyIdentity, type ManagedSyncContext, type SyncDiscovery, type SyncEntry, type SyncSlugCollision } from './sync-discovery.ts';
-import type { SyncAuthority, SyncProcessingOptions } from './sync-authority.ts';
-import type { PassStamp, SyncCursorOptions } from './sync-prepare.ts';
+import { assertSyncDispatchActive, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
+import type { PassStamp, SyncCursorOptions, SyncIntent } from './sync-prepare.ts';
import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP, writePassRow, type ManagedSyncPassValue, type PassEpisode,
type PassKind, type PassOutcome, type SyncSelection } from './sync-pass-row.ts';
import { readSyncAdmission, type SyncAdmission } from './sync-admission.ts';
@@ -30,8 +37,10 @@ import { PASS_BATCH_KEY_PREFIX, readConvergedWatermark, SyncAdmissionPaused, typ
import { assertDrainLease, currentDrainLease } from './sync-lease.ts';
import { digest } from './digest.ts';
import { readSyncTail } from './sync-tail-record.ts';
-import { holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, readSyncImportProvenances, syncImportParserFor } from './sync-holds.ts';
+import { clearGitHold, holdRescreenDue, readGitHoldRetryPaths, readSyncHoldPolicy, readGitSourceHolds, readSyncImportProvenances, syncImportParserFor } from './sync-holds.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
+import { loadConfig } from '../config.ts';
+import { startPersistenceConsumer } from './service.ts';
import { clearManagedSyncFailureAfterSuccess } from './sync-failures.ts';
import { managedCursorKey, resolveManagedCursor, retireManagedCursor } from './sync-cursor-key.ts';
import { withCoordinatedWrite } from './context.ts';
@@ -111,7 +120,7 @@ function entryPaths(level: ShadowLevel, gitPath: string): { path: string; source
* page moves to the new slug). Deletes first, then imports.
*/
async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: ShadowPath[], imports: ShadowPath[]):
- Promise<{ entries: PassEntry[]; collisions: SyncSlugCollision[]; skipped: ShadowPath[] }> {
+ Promise<{ entries: PassEntry[]; collisions: SyncSlugCollision[]; skipped: ShadowPath[]; downgrades: DowngradedRename[] }> {
const working = (entry: ShadowPath) => level.mode === 'working' && entry.state.level !== entry.state.tree;
const deleteEntries = new Map<string, PassEntry>(deletes.map(entry => [entry.path, { ...entryPaths(level, entry.path), action: 'delete' as const, working: level.mode === 'working',
slug: entry.slug!, pageId: entry.pageId, revision: entry.revision, level: null }]));
@@ -153,6 +162,16 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh
claims.set(slug, [...claims.get(slug) ?? [], entry]);
}
const renamed = new Set<string>();
+ let renames: Promise<Map<string, string> | null> | null = null;
+ const downgrades: DowngradedRename[] = [];
+ const gitRenames = () => renames ??= (async () => {
+ if (level.mode !== 'committed' || !level.baselineCommit || level.baselineCommit === level.head || (!deleteEntries.size && !level.heldRenames.length)) return null;
+ const delta = await confirmedSyncDelta(engine, level.gitRoot, level.baselineCommit, level.head, { sourceId: level.sourceId, sourcePathOf: path => entryPaths(level, path).sourcePath });
+ if (delta.status !== 'ok') return null;
+ // #6729: the inexact renames whose identity was not kept are reported (and recorded) as discovery reported them.
+ downgrades.push(...(delta.manifest.downgradedRenames ?? []).map(pair => ({ ...pair, from: entryPaths(level, pair.from).sourcePath, to: entryPaths(level, pair.to).sourcePath })));
+ return new Map(delta.manifest.renamed.map(pair => [pair.to, pair.from]));
+ })();
for (const [slug, claimants] of claims) {
const holder = holders.get(slug);
const holderPath = holder?.source_path ? gitPathOfOrigin(holder.source_path) : null;
@@ -173,10 +192,23 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh
if (holderPath !== null && deleteEntries.delete(holderPath)) renamed.add(holderPath);
continue;
}
+ // #5988: a held rename destination still owes its page the move: re-bound while the origin page is unchanged, else held rename_held.
+ // A held destination renamed again (a Git rename of the held path) carries the held identity on.
+ const heldAt = (path: string | undefined) => path === undefined ? undefined : level.heldRenames.find(row => row.path === path)?.rename;
+ const held = heldAt(winner.path) ?? (level.heldRenames.length ? heldAt((await gitRenames())?.get(winner.path)) : undefined);
+ const origin = held ? (await engine.executeRaw<{ source_path: string | null; revision: string; deleted: boolean }>(
+ 'SELECT source_path, knowledge_revision::text AS revision, deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 AND id=$2', [level.sourceId, held.pageId]))[0] : undefined;
+ if (held && origin && !origin.deleted && origin.source_path !== null && syncOriginPath(origin.source_path) === syncOriginPath(held.sourcePath)) {
+ entries.push({ ...base, pageId: null, revision: null, ...(origin.revision === held.revision ? { renameFrom: held } : { renameHeld: held }) });
+ continue;
+ }
const moved = [...leaving.values()].filter(gone => deleteEntries.has(gone.path) && !renamed.has(gone.path) && gone.state.record?.blobOids.includes(winner.state.level ?? ''));
const twins = fresh.filter(other => other.state.level === winner.state.level);
- if (moved.length === 1 && twins.length === 1) {
- const gone = moved[0]!;
+ // #6729: a Git rename with an edit keeps its page when Git pairs it and the identity is confirmed, as discovery's delta does.
+ const inexact = moved.length === 1 && twins.length === 1 ? null : (await gitRenames())?.get(winner.path);
+ const gitMoved = inexact && deleteEntries.has(inexact) && !renamed.has(inexact) ? leaving.get(inexact) : undefined;
+ if (gitMoved?.pageId != null || (moved.length === 1 && twins.length === 1)) {
+ const gone = gitMoved ?? moved[0]!;
const origin = entryPaths(level, gone.path).sourcePath;
entries.push({ ...base, pageId: null, revision: null, renameFrom: { sourcePath: origin, slug: gone.slug!, pageId: gone.pageId!, revision: gone.revision! } });
deleteEntries.delete(gone.path); renamed.add(gone.path);
@@ -184,22 +216,49 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh
}
entries.push({ ...base, pageId: null, revision: null });
}
- return { entries: [...deleteEntries.values(), ...entries.sort((a, b) => a.path.localeCompare(b.path))], collisions, skipped };
+ return { entries: [...deleteEntries.values(), ...entries.sort((a, b) => a.path.localeCompare(b.path))], collisions, skipped, downgrades };
}
-/** Waits (bounded) until no open request or Git effect of the worktree names one of the in-flight pages or origins. */
-async function awaitInFlight(engine: BrainEngine, level: ShadowLevel, inFlight: ShadowPath[], budgetMs: number, assertActive: () => void): Promise<void> {
+/**
+ * Waits (bounded) until no open request or Git effect of the worktree names one of the in-flight pages or origins, and
+ * returns what the requests open at its start committed meanwhile: an earlier drain's work this pass reports as its own.
+ */
+async function awaitInFlight(engine: BrainEngine, level: ShadowLevel, inFlight: ShadowPath[], budgetMs: number, assertActive: () => void): Promise<{ added: number; modified: number; deleted: number; renamed: number }> {
const pageIds = inFlight.flatMap(entry => entry.pageId === null ? [] : [entry.pageId]);
const origins = inFlight.map(entry => entryPaths(level, entry.path).sourcePath);
+ const names = `r.page_id=ANY($2::int[]) OR r.intent->>'sourcePath'=ANY($3::text[])`;
+ const opened = await engine.executeRaw<{ id: string }>(`SELECT r.id FROM persistence_requests r WHERE r.source_id=$1 AND r.state IN ('queued','running','recovering') AND (${names})`,
+ [level.sourceId, pageIds, origins]);
const until = Date.now() + budgetMs;
while (Date.now() < until) {
const [open] = await engine.executeRaw(`SELECT 1 FROM persistence_requests r WHERE r.source_id=$1 AND (r.state IN ('queued','running','recovering')
OR EXISTS (SELECT 1 FROM persistence_effects e WHERE e.request_id=r.id AND e.kind='git' AND e.state IN ('queued','running')))
- AND (r.page_id=ANY($2::int[]) OR r.intent->>'sourcePath'=ANY($3::text[])) LIMIT 1`, [level.sourceId, pageIds, origins]);
+ AND (${names}) LIMIT 1`, [level.sourceId, pageIds, origins]);
assertActive();
- if (!open) return;
+ if (!open) break;
await new Promise(resolve => setTimeout(resolve, 100));
}
+ const credited = { added: 0, modified: 0, deleted: 0, renamed: 0 };
+ if (!opened.length) return credited;
+ const created = new Set(inFlight.filter(entry => entry.pageId === null).map(entry => entryPaths(level, entry.path).sourcePath));
+ const committed = await engine.executeRaw<{ kind: string | null; source_path: string | null; renamed: boolean }>(`SELECT intent->>'kind' AS kind, intent->>'sourcePath' AS source_path,
+ intent ? 'renameFrom' AS renamed FROM persistence_requests WHERE id=ANY($1::uuid[]) AND state='committed'`, [opened.map(row => row.id)]);
+ for (const row of committed) {
+ if (row.kind === 'managed_sync_delete') credited.deleted++;
+ else if (row.kind !== 'managed_sync_import') continue;
+ else if (row.renamed) credited.renamed++;
+ else if (row.source_path !== null && created.has(row.source_path)) credited.added++;
+ else credited.modified++;
+ }
+ return credited;
+}
+
+/** The oldest open request naming one of the in-flight pages or origins. */
+async function openInFlightRequest(engine: BrainEngine, level: ShadowLevel, inFlight: ShadowPath[]): Promise<WriteRequest | null> {
+ const [row] = await engine.executeRaw<{ id: string }>(`SELECT r.id FROM persistence_requests r WHERE r.source_id=$1 AND r.state IN ('queued','running','recovering')
+ AND (r.page_id=ANY($2::int[]) OR r.intent->>'sourcePath'=ANY($3::text[])) ORDER BY r.sequence LIMIT 1`,
+ [level.sourceId, inFlight.flatMap(entry => entry.pageId === null ? [] : [entry.pageId]), inFlight.map(entry => entryPaths(level, entry.path).sourcePath)]);
+ return row ? getWriteRequestById(engine, row.id) : null;
}
/** Design §2.7 (b1): the incarnation's first pass writes a `legacy` marker, with its deletion proof, for each page-less path deleted before PR 4. */
@@ -234,20 +293,21 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
// Pin (design §2.2): the row, sync.admission, HEAD and the mode.
const [prior, admission, configuredWorking] = await Promise.all([readPassRow(engine, sourceId, incarnation), readSyncAdmission(engine), engine.getConfig('sync.include_working_tree')]);
assertActive();
- const head = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();
+ let head = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();
const detached = syncGit(context.gitRoot, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() === 'HEAD';
const mode: SyncSelection['mode'] = detached || (opts.workingTree ?? configuredWorking === 'true') ? 'working' : 'committed';
const selection = await passSelection(engine, opts, context, mode);
- const configured = !remote && !opts.exclude?.length && !opts.includeHidden?.length && !opts.strategy && opts.srcSubpath === undefined
+ const configured = !remote && !opts.exclude?.length && !opts.includeHidden?.length && opts.srcSubpath === undefined
+ && (opts.strategy === undefined || opts.strategy === ((context.source.config?.strategy as string | undefined) ?? 'markdown'))
&& (detached || opts.workingTree === undefined || opts.workingTree === (configuredWorking === 'true'));
const selectionFp = digest(selection), parserFp = parserFingerprint();
- const pack = (await loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null))?.identity ?? null;
const obligations: ManagedSyncPassValue['obligations'] = prior ? structuredClone(prior.value.obligations)
: { baseline_commit: context.source.last_commit, mismatch: {}, not_converged_streak: 0, faults: {} };
obligations.mismatch ??= {}; obligations.faults ??= {}; obligations.not_converged_streak ??= 0;
if (handover.episode && !obligations.episode) obligations.episode = handover.episode;
const passId = randomUUID();
- const requested = input.processingOptions;
+ // #6696: a cost-gate deferral rides as noEmbed but is this run's constraint (its requests carry embedDeferred), never an opt-out an episode keeps.
+ const requested = opts.embedDeferred ? { ...input.processingOptions, noEmbed: false } : input.processingOptions;
if (opts.full && !obligations.episode?.full_id) obligations.episode = { opened_at: startedAt, full_id: passId, selection,
inherited: { noEmbed: requested.noEmbed, noExtract: requested.noExtract, noSchemaPack: requested.noSchemaPack, from: obligations.episode?.inherited.from ?? 'flag' } };
// A pass that admits under an opt-out opens an episode carrying it (design §6), when it admits its first batch.
@@ -258,6 +318,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const processingOptions: SyncProcessingOptions = { noEmbed: requested.noEmbed || !!episode?.inherited.noEmbed, noExtract: requested.noExtract || !!episode?.inherited.noExtract,
noSchemaPack: requested.noSchemaPack || !!episode?.inherited.noSchemaPack };
const inherited = (['noEmbed', 'noExtract', 'noSchemaPack'] as const).filter(key => processingOptions[key] && !requested[key]);
+ const pack = processingOptions.noSchemaPack ? null : (await loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null))?.identity ?? null;
// The kind (design §2.2), from the real converged state.
const converged = obligations.converged;
@@ -334,10 +395,11 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (outcome === 'blocked' || stopReason === 'not_converged') value.obligations.stuck_since ??= new Date().toISOString();
await engine.transaction(async tx => { await assertDrainLease(tx, sourceId); await writePassRow(tx, value); });
};
+ const identityDowngrades: DowngradedRename[] = [];
const result = (status: SyncResult['status'], reason?: SyncResult['reason']): SyncResult => ({ status, fromCommit: remote ? null : context.source.last_commit, toCommit: remote ? '' : head,
added: counts.added, modified: counts.modified, deleted: counts.deleted, renamed: counts.renamed, chunksCreated: counts.chunks, embedded: 0, pagesAffected: [],
filesImported: sliceBase.pages, bankedFiles: sliceBase.pages, waived: { imports: counts.waivedImports, deletes: counts.waivedDeletes }, prescreened: 0,
- ...(collisions.length ? { slugCollisions: collisions } : {}), ...(inherited.length ? { inherited_options: inherited } : {}), ...(reason ? { reason } : {}),
+ ...(collisions.length ? { slugCollisions: collisions } : {}), ...(identityDowngrades.length ? { identityDowngrades } : {}), ...(inherited.length ? { inherited_options: inherited } : {}), ...(reason ? { reason } : {}),
pass: { pass_id: passId, kind, round: value.telemetry.round, outcome: value.telemetry.outcome, stop_reason: value.telemetry.stop_reason, candidates: candidatesFirst,
settled: S.size, remaining: value.telemetry.remaining, not_converged_streak: value.obligations.not_converged_streak } });
/** The batch cursor sync-run.ts drains: the discovery shape with no cursor row behind it. */
@@ -366,19 +428,41 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
waivedDeletes: counts.waivedDeletes + (drained.waived?.deletes ?? 0) });
sliceBase.pages += drained.filesImported ?? 0;
const outcome: PassOutcome = drained.status === 'blocked_by_failures' ? 'blocked' : 'resumable';
+ const blockedOn = drained.managedWrite?.path ? drained.managedWrite.write_request.request_id : null;
+ if (outcome === 'blocked' && blockedOn && obligations.blocked?.request_id !== blockedOn) obligations.blocked = { request_id: blockedOn, pass_id: passId };
await save(outcome, drained.reason ?? (outcome === 'blocked' ? 'blocked_by_failures' : null));
const { runId: _run, managedCursor: _cursor, ...rest } = drained;
return { ...rest, ...result(drained.status, drained.reason) };
};
try {
+ // A page refusal the last pass stopped on replays, with no new request, while what decided it is unchanged (#6712 PR 3, L7).
+ // 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);
+ }
+ }
for (let round = 1; round <= PASS_MAX_ROUNDS; round++) {
assertActive();
value.telemetry.round = round;
const level = await readShadowLevel(engine, { sourceId, context, workingTree: mode === 'working',
- pass: { head, episodeFullId: episode?.full_id ?? null, retryConsumed: round > 1 ? retryConsumed : undefined, exclude: opts.exclude, includeHidden: opts.includeHidden, strategy: opts.strategy, bootstrap } });
+ pass: { noSchemaPack: processingOptions.noSchemaPack, episodeFullId: episode?.full_id ?? null, retryConsumed: round > 1 ? retryConsumed : undefined, exclude: opts.exclude, includeHidden: opts.includeHidden, strategy: opts.strategy, bootstrap } });
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
+ // imported by the next round, never frozen from an older pin it is not in).
+ head = value.telemetry.target = level.head;
levelSlugMode = level.slugMode;
lastLevel = level;
value.telemetry.timings_ms = level.timings_ms;
@@ -390,6 +474,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (!remote) value.obligations.deletes_withheld = applied.withheld?.set_hash ?? null;
const deletes: ShadowPath[] = [], imports: ShadowPath[] = [], inFlight: ShadowPath[] = [], mismatch: ShadowPath[] = [], owed: ShadowPath[] = [];
lastMismatch = mismatch;
+ const heldRenameOrigins = new Set(level.heldRenames.map(held => syncOriginPath(held.rename.sourcePath)));
for (const entry of level.paths) {
const r = entry.result;
if (r.settled) continue;
@@ -403,11 +488,19 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
readmitted.add(again);
}
if (r.action === 'delete') {
+ if (heldRenameOrigins.has(syncOriginPath(entryPaths(level, entry.path).sourcePath))) { S.set(settledKey(entry.path, entry.state.level), 'rename_held'); continue; }
if (admission !== 'normal') { S.set(settledKey(entry.path, entry.state.level), 'paused_deletes'); counts.pausedDeletes++; continue; }
deletes.push(entry);
} else if (r.action === 'import' || r.action === 'reparse' || (!remote && (r.cls === 'drift' || r.cls === 'dirty'))) imports.push(entry);
else owed.push(entry);
}
+ // Origins that differ only by case or separator spelling may be one file on another platform: refuse rather than guess, as discovery does.
+ const spelled = owed.filter(entry => entry.result.cls === 'spelling').map(entry => entryPaths(level, entry.path).sourcePath);
+ if (spelled.length) {
+ await save('blocked', 'page_identity_changed');
+ throw opError('page_identity_changed', 'Sync origins for one slug differ only by case or separator spelling.',
+ `Files in ${sourceId} differ only by case or separator spelling (${spelled.slice(0, 3).join(', ')}); nothing was written. Keep one spelling, rename or remove the others and commit, then run gbrain sync --no-pull --source ${sourceId}.`);
+ }
const candidates = deletes.length + imports.length;
if (round === 1) candidatesFirst = candidates + inFlight.length + owed.length;
value.telemetry.candidates = candidatesFirst;
@@ -415,10 +508,19 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (admission === 'classify_only') { await save('resumable', 'admission_paused'); return result('partial', 'admission_paused'); }
if (!candidates && inFlight.length && waits < IN_FLIGHT_WAITS) {
waits++; round--;
- await awaitInFlight(engine, level, inFlight, opts.drainStartedAt ? 30_000 : 5_000, assertActive);
+ startPersistenceConsumer(engine, loadConfig() ?? { engine: engine.kind }).wake(true);
+ const credited = await awaitInFlight(engine, level, inFlight, opts.drainStartedAt ? 30_000 : 5_000, assertActive);
+ Object.assign(counts, { added: counts.added + credited.added, modified: counts.modified + credited.modified, deleted: counts.deleted + credited.deleted, renamed: counts.renamed + credited.renamed });
+ sliceBase.pages += credited.added + credited.modified + credited.renamed;
continue;
}
- if (!candidates && inFlight.length) { await save('resumable', 'writer_pending'); return result('partial', 'writer_pending'); }
+ if (!candidates && inFlight.length) {
+ await save('resumable', 'writer_pending');
+ // The request an agent waits on, as the cursor's writer_pending named it.
+ const waiting = remote ? null : await openInFlightRequest(engine, level, inFlight);
+ return { ...result('partial', 'writer_pending'), ...(waiting?.intent ? { managedWrite: managedSyncWriteDiagnostic({ sourceId, root: context.root, processingOptions,
+ syncOptions: input.syncOptions ?? null }, { slug: waiting.slug, intent: waiting.intent as unknown as SyncIntent }, waiting) } : {}) };
+ }
if (!candidates) {
if (remote) {
// Design §5: a remote caller stops after its one-sided work; the owner host settles and stamps the rest.
@@ -435,6 +537,8 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
assertActive();
await assertDrainLease(tx, sourceId);
await tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]);
+ // Holds on paths that left the level go with it here too, as a stamp releases them.
+ for (const path of level.releasableHolds) await clearGitHold(tx, { sourceId, incarnation, path, observedAt: startedAt });
const watermark = await readConvergedWatermark(tx, { worktreeId: context.binding.worktree_id, sourceId, incarnation }, null, OPEN_AT_STAMP_CAP);
value.obligations.converged = { target: head, at, ...watermark, parser_fp: parserFp, pack, selection_fp: selectionFp,
last_full_at: kind === 'full' || !converged ? at : converged.last_full_at, passes_since_full: kind === 'full' || !converged ? 0 : converged.passes_since_full + 1 };
@@ -454,8 +558,8 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
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: [], selectionFp, parserFp, pack, full: kind === 'full',
- changed: counts.added + counts.modified + counts.deleted + counts.renamed, extract: !processingOptions.noExtract };
+ 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 };
await save('open', null);
const stopped = await drain([], stamp);
if (stopped) return stop(stopped);
@@ -467,6 +571,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
}
const built = await batchEntries(engine, level, deletes, imports);
collisions.push(...built.collisions);
+ identityDowngrades.push(...built.downgrades.filter(pair => !identityDowngrades.some(seen => seen.from === pair.from && seen.to === pair.to)));
for (const entry of [...built.skipped, ...built.collisions.flatMap(c => c.skipped.map(sourcePath => imports.find(i => entryPaths(level, i.path).sourcePath === sourcePath)!))].filter(Boolean)) {
S.set(settledKey(entry.path, entry.state.level), 'collision'); counts.collisions++;
}
@@ -502,6 +607,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
await save('resumable', 'not_converged');
return result('partial', 'not_converged');
} 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'); }
// A Git listing that did not finish cleanly classifies nothing (design v3.2 §9): the pass stops blocked, having written nothing for that round.
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index cd351818a3..692f1e11a0 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -56,8 +56,8 @@ export interface PassLevelInput {
* stored markers count.
*/
bootstrap?: boolean;
- /** The commit the pass pinned (design §3.1): every round reads this level, never a HEAD that moved during the pass. */
- head?: string;
+ /** The pass imports without the schema pack (`no-schema-pack` or an episode carrying it): its parser expects no pack. */
+ noSchemaPack?: boolean;
}
/** 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;
@@ -80,6 +80,10 @@ export interface ShadowLevel {
selection: SyncSelection;
/** Re-screen-due hold paths (Git-root paths): a hold-only round's candidates. */
rescreenDue: string[];
+ /** Held renames (#5988), by the held destination's Git path: the destination still owes its page the move, and the origin's deletion waits for the hold. */
+ heldRenames: Array<{ path: string; rename: { sourcePath: string; slug: string; pageId: number; revision: string } }>;
+ /** Holds on paths outside the level's domain (no file at L, no page, or no longer eligible): the stamp releases them, as discovery did (#6278 B7). */
+ releasableHolds: string[];
/** Working mode: the stat cache this round's rehash left (`hashWorkingLevel`); the stamp's round is the one a pass remembers. */
workingCache: WorkingStatCache | null;
/** Live file-backed pages whose origin is eligible: the mass-delete valve's denominator (#2828). */
@@ -267,7 +271,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
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),
+ input.pass?.noSchemaPack ? Promise.resolve(null) : loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null),
sourceMirrorReadOnly(engine, sourceId),
]);
timings.setup = t();
@@ -287,7 +291,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const gitPathOf = memo((origin: string) => { const o = originPath(origin); return slugMode === 'source-root' && scope ? `${scope}/${o}` : o; });
t = timer();
- const head = input.pass?.head ?? revParse(gitRoot, 'HEAD');
+ const head = revParse(gitRoot, 'HEAD');
if (!head) throw new Error(`source ${sourceId}: HEAD does not name a commit, so there is no level to read`);
// Master's rule (sync-discovery.ts): a detached HEAD forces working mode.
const detached = syncGit(gitRoot, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() === 'HEAD';
@@ -339,9 +343,9 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
// Spellings of one origin that differ only by case or separator: the domain holds each path once, so a count is enough.
const fold = (path: string) => path.replaceAll('\\', '/').toLowerCase();
const spellings = new Map<string, number>();
+ // Only spellings that are files at L count (discovery's case-only respelling whose old file this sync removes is no refusal).
for (const path of domain) {
- const live = byOrigin.get(path);
- if (!tree.has(path) && !(live && !live.deleted)) continue;
+ if (!tree.has(path) && !(mode === 'working' && (untracked.has(path) || index.has(path)))) continue;
const folded = fold(path);
spellings.set(folded, (spellings.get(folded) ?? 0) + 1);
}
@@ -482,6 +486,8 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
rescreenDueHold: holds.some(hold => holdRescreenDue(hold, retry.has(hold.path))), full: input.full === true });
timings.total = total();
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, 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)), workingCache: hashed?.cache ?? null };
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 1630b1b74c..a3031bba65 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -126,6 +126,8 @@ export interface PassStamp {
full: boolean;
/** The tail obligation: pages the pass changed, and whether their links are extracted. */
changed: number; extract: boolean;
+ /** When the pass pinned, on the database clock: the tail reads the pages its requests imported since then. */
+ since?: string;
}
/**
* #5984: the source-wide part of sync validation (managed mode, configured
@@ -514,7 +516,7 @@ 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 });
+ await recordPassTail(tx, row.source_id, p.passId!, { changed: stamp.changed, extract: stamp.extract, ...(stamp.since ? { since: stamp.since } : {}) });
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);
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 0372180e40..e5f2dd2584 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -1657,9 +1657,8 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
...(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' && cursor.passId && done.error_code === 'admission_paused') {
+ return { ...result(cursor, 'partial', 'admission_paused'), ...(authority.writer.remote ? {} : { managedWrite: writeDiagnostic(cursor, pending, done) }) };
}
// #6712 PR 4b (design v3.2 §2): a pass's write refused because its file changed after admission is the level moving, not a
// page failure: the entry is passed over and the next round classifies the new level (a level that never settles ends the
@@ -1710,16 +1709,34 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
// #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) {
+ // The run's report reads the recovered, normalized and converted totals of every batch of the pass, not its last (stamp) batch.
+ const totals: { recovered?: Cursor['counts']['recovered']; fences?: FencesTally; converted: string[] } = { converted: [] };
+ const sum = (a: Record<string, number> = {}, b: Record<string, number> = {}) => Object.fromEntries([...new Set([...Object.keys(a), ...Object.keys(b)])].map(k => [k, (a[k] ?? 0) + (b[k] ?? 0)]));
+ let folded: Cursor | null = null;
+ state.cursor = () => live.cursor ? { ...live.cursor, counts: { ...live.cursor.counts, recovered: totals.recovered, fences: totals.fences }, convertedFromFailed: totals.converted } : null;
return await runSyncPass(engine, { opts, slice, context, authority, processingOptions, syncOptions, assertActive, signal, state, runStartedAt,
drainBatch: async (batchKey, batch, sliceBase) => {
key = batchKey;
setPassBatch(batchKey, batch, JSON.stringify(header(batch)));
try { return await drainCursor(batch, await preparationConfigView(engine), false, sliceBase); }
catch (error) {
+ assertSyncDispatchActive();
// An abort mid-batch stops the pass with what the batch committed before it.
if (signal?.aborted && error instanceof Error && error.name === 'AbortError') return result(live.cursor ?? batch, 'partial', 'timeout');
throw error;
- } finally { setPassBatch(batchKey, null); }
+ } finally {
+ setPassBatch(batchKey, null);
+ const done = live.cursor;
+ if (done?.passId && done !== folded) {
+ folded = done;
+ const { recovered, fences } = done.counts;
+ if (recovered) totals.recovered = { count: (totals.recovered?.count ?? 0) + recovered.count, sample_paths: [...totals.recovered?.sample_paths ?? [], ...recovered.sample_paths].slice(0, 5),
+ ...((totals.recovered?.comment_values ?? 0) + (recovered.comment_values ?? 0) ? { comment_values: (totals.recovered?.comment_values ?? 0) + (recovered.comment_values ?? 0) } : {}) };
+ if (fences) totals.fences = { count: (totals.fences?.count ?? 0) + fences.count, by_class: sum(totals.fences?.by_class, fences.by_class),
+ sample_paths: [...totals.fences?.sample_paths ?? [], ...fences.sample_paths].slice(0, 5), dirs: sum(totals.fences?.dirs, fences.dirs) };
+ totals.converted = [...new Set([...totals.converted, ...done.convertedFromFailed ?? []])];
+ }
+ }
} });
}
const resolved = await resolvePassCursor(engine, { sourceId: context.sourceId, incarnation: context.incarnation, company, remote: authority.writer.remote, dryRun: !!opts.dryRun, assertActive, state });
diff --git a/src/core/persistence/sync-tail-record.ts b/src/core/persistence/sync-tail-record.ts
index a94c673c52..02456e6c43 100644
--- a/src/core/persistence/sync-tail-record.ts
+++ b/src/core/persistence/sync-tail-record.ts
@@ -9,7 +9,7 @@ export const SYNC_TAIL_OP = 'managed-sync-tail';
/** Obligations kept per source; an older one folds into the stale-page scan every tail runs. */
const SYNC_TAIL_KEEP = 16;
-export interface TailObligation { run_id: string; changed: number; extract: boolean; at: string }
+export interface TailObligation { run_id: string; changed: number; extract: boolean; at: string; /** A pass's pin time (database clock): its imports committed in [since, at]. */ since?: string }
/** Inside the checkpoint's transaction: the run's tail is owed before anyone can read the run as synced. */
export async function recordSyncTail(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, cursorKey: string, runId: string): Promise<void> {
@@ -27,12 +27,12 @@ export async function recordSyncTail(tx: Pick<BrainEngine, 'executeRaw'>, source
* #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> {
+export async function recordPassTail(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, passId: string, tail: { changed: number; extract: boolean; since?: string }): 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())
+ VALUES ($1, $2, jsonb_build_array(jsonb_strip_nulls(jsonb_build_object('run_id',$3::text,'at',now(),'changed',$4::int,'extract',$5::boolean,'since',$6::text))), 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]);
+ [SYNC_TAIL_OP, sourceId, passId, tail.changed, tail.extract, tail.since ?? null]);
}
/** The source's owed tail, or null when none is owed. */
diff --git a/src/core/persistence/sync-tail.ts b/src/core/persistence/sync-tail.ts
index ae0ec75409..188b65947b 100644
--- a/src/core/persistence/sync-tail.ts
+++ b/src/core/persistence/sync-tail.ts
@@ -56,9 +56,15 @@ export async function runSyncTail(engine: BrainEngine, sourceId: string, opts: {
await faultPoint('sync:tail_started', { sourceId });
if (changed > 0) statistics = await refreshProjectionStatistics(engine, changed) ? 'refreshed' : 'failed';
if (extract && deadlineAt > Date.now()) {
- slugs = (await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT e->>'slug' AS slug FROM op_checkpoints m, jsonb_array_elements(m.completed_keys) e
- WHERE m.op='managed-sync-manifest' AND m.fingerprint=ANY($1::text[]) AND e->>'action'='import' AND e->>'slug' IS NOT NULL LIMIT ${SYNC_TAIL_MAX_PAGES + 1}`,
- [owed.map(item => item.run_id)], { timeoutMs: Math.max(1, deadlineAt - Date.now()) })).map(row => row.slug);
+ // A cursor run's imports are its manifest's; a pass writes none, so its imports are its committed requests since its pin.
+ const passes = owed.filter(item => item.since);
+ slugs = (await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT slug FROM (SELECT e->>'slug' AS slug FROM op_checkpoints m, jsonb_array_elements(m.completed_keys) e
+ WHERE m.op='managed-sync-manifest' AND m.fingerprint=ANY($1::text[]) AND e->>'action'='import' AND e->>'slug' IS NOT NULL
+ UNION SELECT r.slug FROM persistence_requests r, jsonb_to_recordset($2::text::jsonb) AS p(run_id text, since timestamptz, at timestamptz)
+ WHERE r.recovery IS NULL AND NOT r.compacted AND r.state='committed' AND r.completed_at BETWEEN p.since AND p.at AND r.source_id=$3
+ AND r.intent->>'passId'=p.run_id AND r.intent->>'kind'='managed_sync_import') imported LIMIT ${SYNC_TAIL_MAX_PAGES + 1}`,
+ [owed.map(item => item.run_id), JSON.stringify(passes.map(item => ({ run_id: item.run_id, since: item.since, at: item.at }))), sourceId],
+ { timeoutMs: Math.max(1, deadlineAt - Date.now()) })).map(row => row.slug);
if (deadlineAt > Date.now()) links = await extractManagedStaleLinks(engine, { sourceId, maxPages: SYNC_TAIL_MAX_PAGES, timeBudgetMs: deadlineAt - Date.now(), signal: opts.signal, mentions: false, slugs });
}
} catch (error) {
diff --git a/test/sync-pass-live-6712.test.ts b/test/sync-pass-live-6712.test.ts
index 2bd766fc4f..a2bf912a60 100644
--- a/test/sync-pass-live-6712.test.ts
+++ b/test/sync-pass-live-6712.test.ts
@@ -22,7 +22,9 @@
* - a committed edit under a different uncommitted edit (committed mode) is held worktree_dirty, the page and the local
* file untouched, and the next pass settles instead of counting a not_converged streak; sync.holds=fail stops the run.
* - a page written straight to the database at a new file's slug is never overwritten by the file: held file_drift (side unknown).
- * - a commit during a pass: every round reads the pinned level (no storage_error from a moved HEAD); the next pass takes the new commit.
+ * - a commit during a pass: the next round reads the new HEAD and its batch freezes that commit (no storage_error from an older pin).
+ * - --no-schema-pack: a first pass converges (its parser expects no pack); a cost-gate deferral is no inherited opt-out;
+ * a source configured with a strategy, synced with that strategy named (sync --all), stamps last_commit.
* - probe 54: a pass intent keeps what the #6862 FIFO guard reads: a `managed_sync_` kind, the slug and page, and `renameFrom.slug`.
*
* Each test fails on capy/6712-pr4b (8cda2764b), where a non-company source still runs the cursor engine: the fences do not
@@ -304,9 +306,9 @@ describe('#6712 PR 4b live pass fences (pglite)', () => {
expect((await engine.executeRaw<{ source_path: string | null }>("SELECT source_path FROM pages WHERE source_id='default' AND slug IN ('notes/d','notes/e') ORDER BY slug")).map(row => row.source_path)).toEqual([null, null]);
}, { setup }), 180_000);
- test('a commit landing during a pass: the pass finishes at its pinned level and the next pass imports the new commit', () => managedBrain(async ({ engine, root }) => {
+ test('a commit landing during a pass: the next round imports it from the new HEAD, and the pass ends there', () => managedBrain(async ({ engine, root }) => {
expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
- const pinned = (writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A committed change of notes/a.')), commit(root, 'change a'), git(root, 'rev-parse', 'HEAD'));
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A committed change of notes/a.')); commit(root, 'change a');
let moved = false;
installFaultHook(async (point, detail) => {
if (point !== 'consumer:prepared' || moved || detail.operation !== 'submit_job') return;
@@ -316,11 +318,39 @@ describe('#6712 PR 4b live pass fences (pglite)', () => {
const during = await performManagedSync(engine, OPTS);
installFaultHook(undefined);
expect(moved).toBe(true);
- expect({ status: during.status, to: during.toCommit }).toEqual({ status: 'synced', to: pinned });
+ expect({ status: during.status, to: during.toCommit, added: during.added, modified: during.modified }).toEqual({ status: 'synced', to: git(root, 'rev-parse', 'HEAD'), added: 1, modified: 1 });
expect((await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))!.page.compiled_truth).toContain('A committed change of notes/a.');
- const next = await performManagedSync(engine, OPTS);
- expect({ status: next.status, to: next.toCommit }).toEqual({ status: 'synced', to: git(root, 'rev-parse', 'HEAD') });
expect((await engine.readPageSnapshot('notes/d', { sourceId: 'default' }))!.page.compiled_truth).toContain('A file committed during the pass.');
+ expect((await engine.executeRaw<{ last_commit: string }>("SELECT last_commit FROM sources WHERE id='default'"))[0]!.last_commit).toBe(git(root, 'rev-parse', 'HEAD'));
+ expect((await performManagedSync(engine, OPTS)).status).toBe('up_to_date');
+ }, { setup }), 180_000);
+
+ test('--no-schema-pack: a three-file first pass converges, and the next pass under the flag is idle', () => managedBrain(async ({ engine }) => {
+ const first = await performManagedSync(engine, { ...OPTS, noSchemaPack: true });
+ expect({ status: first.status, outcome: first.pass?.outcome, remaining: first.pass?.remaining }).toEqual({ status: 'first_sync', outcome: 'synced', remaining: 0 });
+ expect((await engine.executeRaw<{ last_commit: string | null }>("SELECT last_commit FROM sources WHERE id='default'"))[0]!.last_commit).not.toBeNull();
+ expect((await performManagedSync(engine, { ...OPTS, noSchemaPack: true })).status).toBe('up_to_date');
+ }, { setup }), 180_000);
+
+ test('#6696: a cost-gate deferral is the pass\'s own constraint, never an opt-out the next flagless pass inherits', () => managedBrain(async ({ engine }) => {
+ const deferred = await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, embedDeferred: true }, { maxPages: 1, maxMs: 60_000 });
+ expect(deferred.status).toBe('partial');
+ const [row] = await engine.executeRaw<{ episode: unknown }>("SELECT completed_keys->0->'obligations'->'episode' AS episode FROM op_checkpoints WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'='default'");
+ expect(row!.episode ?? null).toBeNull();
+ const imports = await engine.executeRaw<{ no_embed: boolean; deferred: boolean | null }>("SELECT (intent->'processingOptions'->>'noEmbed')::boolean AS no_embed, (intent->>'embedDeferred')::boolean AS deferred FROM persistence_requests WHERE source_id='default' AND intent->>'kind'='managed_sync_import'");
+ expect(imports.length).toBeGreaterThan(0);
+ expect(imports.every(request => request.no_embed === false && request.deferred === true)).toBe(true);
+ const next = await performManagedSync(engine, { sourceId: 'default', noPull: true });
+ expect(next.status).toBe('first_sync');
+ expect(next.inherited_options).toBeUndefined();
+ }, { setup }), 180_000);
+
+ test('#6696 C1: a source configured with a strategy, synced with that strategy named (sync --all), is the configured selection and stamps last_commit', () => managedBrain(async ({ engine, root }) => {
+ await engine.executeRaw("UPDATE sources SET config=COALESCE(config,'{}'::jsonb)||jsonb_build_object('strategy','markdown') WHERE id='default'");
+ const first = await performManagedSync(engine, { ...OPTS, strategy: 'markdown' });
+ expect({ status: first.status, reason: first.reason }).toEqual({ status: 'first_sync', reason: undefined });
+ expect((await engine.executeRaw<{ last_commit: string | null }>("SELECT last_commit FROM sources WHERE id='default'"))[0]!.last_commit).toBe(git(root, 'rev-parse', 'HEAD'));
+ expect((await performManagedSync(engine, { ...OPTS, strategy: 'markdown' })).status).toBe('up_to_date');
}, { setup }), 180_000);
test('probe 54: a pass intent keeps what the #6862 FIFO guard reads, renameFrom included', () => managedBrain(async ({ engine, root }) => {