Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(sync): the drift baseline read lives in sync-screen.ts; sync-run.ts stays at its size ceiling (#6712)

garrytan18e35087b9d0
diff --git a/src/core/persistence/sync-prescreen.ts b/src/core/persistence/sync-prescreen.ts
index 79670c3fd7..73dba886b5 100644
--- a/src/core/persistence/sync-prescreen.ts
+++ b/src/core/persistence/sync-prescreen.ts
@@ -17,7 +17,7 @@
* incremental sync published a committed edit over a database-only `put_page`). `unknown` is guarded in a tree walk
* (first sync, `--full`, an unreachable checkpoint, a re-discovery), where no Git delta says the file is the side that
* changed. A `both` entry whose page still holds what the recorded disk blob imports (the database changed only what an
- * import keeps: tags, links) imports (sync-run.ts `unchangedSinceBaseline`). A page whose current revision a
+ * import keeps: tags, links) imports (sync-screen.ts `driftBaselineContent`). A page whose current revision a
* committed managed-sync request of this incarnation wrote, or whose writer's write-through wrote to its file
* (`pages.revision_write_request_id`, `fileBackedRevisions`), has no database-only edit to protect and is not guarded. A guarded entry is imported only when the freeze proves the import changes
* nothing (`sameContentAtOrigin`); otherwise it is held `file_drift` (sync-run.ts `driftHold`).
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 71f6c7c054..f4e07b3e60 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -45,8 +45,8 @@ import { managedSyncResumeArgs } from '../sync-reconcile.ts';
import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';
import { isContentRefusal } from '../import-screen.ts';
import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';
-import { readBlobContents, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
-import { dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
+import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
+import { driftBaselineContent, dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
import { frozenImageIntent, sameImageBytes } from './sync-image.ts';
import { fenceReceiptLocation } from '../fence-repair/refusal.ts';
import { managedSyncWriteDiagnostic, writeWaitOf } from './sync-write-diagnostic.ts';
@@ -441,8 +441,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
}
// #6712 PR 1: an import whose page moved since its file was last imported runs only as a proven no-op (sync-prescreen.ts).
if (entry.drift && !occupantRebound && content !== null && snapshot && !(image ? sameImageBytes(imageBytes, snapshot.page)
- : await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal)
- || await unchangedSinceBaseline(engine, cursor, entry, key, snapshot, run.signal))) {
+ : await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal) || await sameContentAtOrigin(engine, cursor, entry, key, snapshot, driftBaselineContent(cursor.gitRoot, entry), null, false, run.signal, true))) {
if (!holdsOn) throw syncRunRefusal('file_drift', 'An import would overwrite a database version of the page that sync never saw.', retry, `Page ${slug} in source ${cursor.sourceId} changed in the database since ${entry.path} was last imported, and the file differs from it, so the run stopped before admitting it (sync.holds=fail).`);
const proof = await pageChangeProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pageId, expectedRevision: null }); assertActive();
return { hold: fileDriftHold(entry, slug, pageId, frozenIntent, { sides: entry.drift, revision: snapshot.revision, proof, sharedOrigin: await sharedOriginSurvivor(engine, cursor.sourceId, entry.sourcePath) }) };
@@ -910,43 +909,19 @@ async function alreadyImportedAtOrigin(engine: BrainEngine, cursor: Cursor, entr
/**
* #5522: the page now at the origin already holds exactly the content this entry would import (the preparer's own no-op verdict).
- * #6278: the preparation races the sync budget; past it the origin refusal stands, and a cancelled run propagates.
+ * #6278: the preparation races the sync budget; past it the origin refusal stands, and a cancelled run propagates. #6712 `pageOnly`: the page holds what `content` (a `both` entry's recorded disk blob) imports, a canonical writeback aside.
*/
async function sameContentAtOrigin(engine: BrainEngine, cursor: Cursor, entry: Cursor['entries'][number], key: string,
- snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>>, content: string, rawHash: string | null, lineEndingOnly: boolean, signal?: AbortSignal): Promise<boolean> {
- 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,
+ snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>>, content: string | null, rawHash: string | null, lineEndingOnly: boolean, signal?: AbortSignal, pageOnly = false): Promise<boolean> {
+ if (!snapshot || snapshot.page.deleted_at != null || content === null) return false;
+ const intent: SyncIntent = { kind: 'managed_sync_import', expected_revision: snapshot.revision, sourcePath: entry.sourcePath, path: entry.path, rawHash: pageOnly ? sha256(content) : 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 };
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,
page_id: snapshot.page.id, worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent }), { engine: engine.kind }, startClaimPhase(Date.now(), undefined, budgetMs)), budgetMs, signal);
- return (prepared.contentUnchanged === true || prepared.noop === true) && !prepared.file && prepared.observedRevision === snapshot.revision;
- } catch (error) {
- if (signal?.aborted) throw error;
- return false;
- }
-}
-
-/**
- * #6712: both the file and the page moved since the last recorded import, but the page still holds exactly what the
- * recorded disk blob imports (the database side changed only what an import keeps: tags, links, withdrawals). The
- * newer file then overwrites nothing the database alone holds, so the entry imports.
- */
-async function unchangedSinceBaseline(engine: BrainEngine, cursor: Cursor, entry: Cursor['entries'][number], key: string,
- snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>>, signal?: AbortSignal): Promise<boolean> {
- if (entry.drift !== 'both' || !entry.driftBaseline || !snapshot || snapshot.page.deleted_at != null) return false;
- const baseline = readBlobContents(cursor.gitRoot, [{ oid: entry.driftBaseline, size: 0 }]).get(entry.driftBaseline);
- if (baseline === undefined) return false;
- const intent: SyncIntent = { kind: 'managed_sync_import', expected_revision: snapshot.revision, sourcePath: entry.sourcePath, path: entry.path, rawHash: sha256(baseline),
- content: baseline, lineEndingOnly: false, 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: 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,
- page_id: snapshot.page.id, worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent }), { engine: engine.kind }, startClaimPhase(Date.now(), undefined, budgetMs)), budgetMs, signal);
- return (prepared.pageUnchanged === true || prepared.noop === true) && prepared.observedRevision === snapshot.revision;
+ return (pageOnly ? prepared.pageUnchanged === true || prepared.noop === true : (prepared.contentUnchanged === true || prepared.noop === true) && !prepared.file) && prepared.observedRevision === snapshot.revision;
} catch (error) {
if (signal?.aborted) throw error;
return false;
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index 077e7f3cc1..9504cc6f2c 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -75,6 +75,16 @@ export function pinnedBlob(cursor: PinnedCursor, path: string): TreeBlob | null
return readPinnedBlob(cursor.gitRoot, cursor.target, syncGitPath(cursor, path), upcomingGitPaths(cursor));
}
+/**
+ * A `both` entry's recorded disk blob (`driftBaseline`), or null. When the page still holds what it imports (sync-run.ts
+ * `sameContentAtOrigin`, `pageOnly`), the database changed only what an import keeps (tags, links), so the newer file
+ * overwrites nothing the database alone holds and the entry imports.
+ */
+export function driftBaselineContent(gitRoot: string, entry: Pick<SyncEntry, 'drift' | 'driftBaseline'>): string | null {
+ if (entry.drift !== 'both' || !entry.driftBaseline) return null;
+ try { return readBlobContents(gitRoot, [{ oid: entry.driftBaseline, size: SYNC_READ_BOUND }]).get(entry.driftBaseline) ?? null; } catch { return null; }
+}
+
/** The frozen import content of one entry (`readSyncContent`); a committed entry's pinned blob is read with the entries after it. */
export function pinnedContent(cursor: SyncDiscovery & { index: number }, entry: SyncEntry): string {
const content = entry.working ? null : readPinnedContent(cursor.gitRoot, cursor.target, syncGitPath(cursor, entry.path), upcomingGitPaths(cursor));
diff --git a/test/sync-prescreen-both-delta-6712.test.ts b/test/sync-prescreen-both-delta-6712.test.ts
index 2eca9c46a5..c5f5ca6c82 100644
--- a/test/sync-prescreen-both-delta-6712.test.ts
+++ b/test/sync-prescreen-both-delta-6712.test.ts
@@ -7,7 +7,7 @@
* - both moved, delta sync: the page keeps the database edit and the file is held `file_drift` (side `both`);
* - control: a file-only edit still imports on a delta sync with no hold;
* - control: a database-only change an import keeps (a tag) is not guarded: the page still holds what the recorded disk
- * blob imports (`unchangedSinceBaseline`), so the committed edit imports and the tag stays;
+ * blob imports (sync-run.ts `sameContentAtOrigin`, `pageOnly`), so the committed edit imports and the tag stays;
* - control: a page whose current revision write-through wrote to its file is not guarded (`fileBackedRevisions`), so the
* committed file edit imports.
*