Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): #6712 PR 4b retire an orphaned managed-sync-slice record on the pass

garrytan8fcdf58c552b
diff --git a/src/core/persistence/sync-cursor-key.ts b/src/core/persistence/sync-cursor-key.ts
index 8e817f62df..885054374e 100644
--- a/src/core/persistence/sync-cursor-key.ts
+++ b/src/core/persistence/sync-cursor-key.ts
@@ -149,6 +149,11 @@ export async function retireManagedCursor(engine: BrainEngine, input: { sourceId
return null;
}
+/** #6712 PR 4b: an orphaned path-slice record, left with no cursor row beside it, goes on the incarnation's first pass too. */
+export async function retireOrphanSliceRecords(engine: BrainEngine, sourceId: string, incarnation: string): Promise<void> {
+ await engine.transaction(async tx => { await assertDrainLease(tx, sourceId); await deleteSliceRecords(tx, sourceId, incarnation); });
+}
+
/** A finished cursor row and its frozen manifest, unless another cursor still names that run. */
async function deleteFinishedCursor(tx: BrainEngine, key: string): Promise<void> {
const [row] = await tx.executeRaw<{ run_id: string | null }>(`DELETE FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 523fb07a6d..7070ec41d1 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -42,12 +42,13 @@ 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 { managedCursorKey, resolveManagedCursor, retireManagedCursor, retireOrphanSliceRecords } from './sync-cursor-key.ts';
import { withCoordinatedWrite } from './context.ts';
import { principalAttribution } from './attribution.ts';
import { isCodeFilePath, resolveSlugForPath } from '../sync.ts';
import { syncOriginPath } from './sync-origin.ts';
import { originMarkerFingerprint } from './sync-markers.ts';
+import { SYNC_SLICE_OP } from './sync-slices.ts';
import { passResumeArgs } from './sync-pass-readers.ts';
import { applyPassRound, finishPassApply, newPassApplyState, passApplyCounts, remoteReconcile } from './sync-pass-apply.ts';
import { passCostDecision, passEpisodeClosure, readReservedUsd, registerPassCost, unregisterPassCost } from './sync-pass-episode.ts';
@@ -90,10 +91,14 @@ async function retireLegacyCursors(engine: BrainEngine, input: { sourceId: strin
Promise<{ wait?: RetryWait; hostRequired?: true; episode?: PassEpisode }> {
const resolution = await resolveManagedCursor(engine, { sourceId: input.sourceId, incarnation: input.incarnation, company: undefined, assertActive: input.assertActive, foldIn: !input.remote });
if (resolution.waitFor) return { wait: { ...resolution.waitFor, retry_after_ms: 5000 } };
- const [row] = await engine.executeRaw<{ header: { runId?: string; done?: boolean; processingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions & { exclude?: string[]; includeHidden?: string[]; strategy?: string; srcSubpath?: string; workingTree?: boolean } } | null }>(
- "SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [resolution.key]);
+ const [row] = await engine.executeRaw<{ slices: boolean; header: { runId?: string; done?: boolean; processingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions & { exclude?: string[]; includeHidden?: string[]; strategy?: string; srcSubpath?: string; workingTree?: boolean } } | null }>(
+ `SELECT (SELECT completed_keys->0 FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1) AS header,
+ EXISTS (SELECT 1 FROM op_checkpoints WHERE op=$2 AND left(fingerprint, length($3))=$3) AS slices`, [resolution.key, SYNC_SLICE_OP, `${input.sourceId}:${input.incarnation}:`]);
const header = row?.header;
- if (!header) return {};
+ if (!header) {
+ if (row?.slices && !input.remote) await retireOrphanSliceRecords(engine, input.sourceId, input.incarnation);
+ return {};
+ }
if (input.remote) return header.done ? {} : { hostRequired: true };
const busy = await retireManagedCursor(engine, { sourceId: input.sourceId, incarnation: input.incarnation, key: resolution.key, runId: header.runId ?? null, done: header.done === true });
input.assertActive();
diff --git a/test/sync-pass-cursor-retirement-6712.test.ts b/test/sync-pass-cursor-retirement-6712.test.ts
index 83a653571a..77597200a2 100644
--- a/test/sync-pass-cursor-retirement-6712.test.ts
+++ b/test/sync-pass-cursor-retirement-6712.test.ts
@@ -7,7 +7,8 @@
* path-slice record, an unfinished cursor under an older key with its manifest, and a finished older-key cursor with
* its manifest), the pass row `managed-sync-pass` / `<source>:<incarnation>` exists, the unfinished cursor's options seed
* the pass's episode (`inherited.from = 'legacy_cursor'`, so the pass inherits its `noExtract`), and the same three kinds of rows of a company source in the
- * same brain stay byte-identical (completed_keys and updated_at).
+ * same brain stay byte-identical (completed_keys and updated_at). An orphaned slice record (no cursor row left beside it)
+ * is retired by the first pass too.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
@@ -64,8 +65,8 @@ const incarnationOf = async (db: BrainEngine, sourceId: string) =>
(await db.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]))[0]!.incarnation;
/** A managed brain whose default source is a claimed, committed checkout that has never synced, beside the company source's registration. */
-async function plantManagedBrain(db: BrainEngine): Promise<string> {
- const root = join(home, 'content'); mkdirSync(join(root, 'notes'), { recursive: true });
+async function plantManagedBrain(db: BrainEngine, dir = 'content'): Promise<string> {
+ const root = join(home, dir); mkdirSync(join(root, 'notes'), { recursive: true });
await db.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
git(root, 'init', '-q');
for (const name of NAMES) writeFileSync(join(root, `notes/${name}.md`), note(name));
@@ -139,4 +140,21 @@ describe('#6712 PR 4b lane C: the first live pass retires legacy cursor rows (§
expect((await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id='default' AND deleted_at IS NULL ORDER BY slug")).map(row => row.slug))
.toEqual(NAMES.map(name => `notes/${name}`));
}), 180_000);
+
+ test('an orphaned slice record, with no cursor row beside it, is retired by the first pass; the company slice stays', () => withEnv(env(), async () => {
+ const db = new PGLiteEngine();
+ await db.connect({}); await db.initSchema();
+ try {
+ const root = await plantManagedBrain(db, 'orphan');
+ const incarnation = await incarnationOf(db, 'default');
+ const head = git(root, 'rev-parse', 'HEAD');
+ await writeSyncSlice(db, 'default', incarnation, syncCursorOptions(OPTS as never), { phase: 'import', after: null, head, target: head });
+ await writeSyncSlice(db, COMPANY, await incarnationOf(db, COMPANY), syncCursorOptions({}), { phase: 'import', after: null, head: 'c0ffee', target: 'c0ffee' });
+ const company = (await legacyRows(db)).filter(isCompanyRow);
+ expect((await legacyRows(db)).map(row => row.op)).toEqual(['managed-sync-slice', 'managed-sync-slice']);
+ const result = await performSync(db, OPTS as never);
+ expect(result.status).toBe('first_sync');
+ expect(await legacyRows(db)).toEqual(company);
+ } finally { await disposePersistenceConsumer(db); await db.disconnect(); }
+ }), 180_000);
});