Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(#6712 PR 4b lane C): first pass retires a finished cursor's manifest and the incarnation's slice records; probe: no non-company cursor row remains

garrytande81ce24a499
diff --git a/src/core/persistence/sync-cursor-key.ts b/src/core/persistence/sync-cursor-key.ts
index 58d5dba1e9..8e817f62df 100644
--- a/src/core/persistence/sync-cursor-key.ts
+++ b/src/core/persistence/sync-cursor-key.ts
@@ -33,6 +33,7 @@ import { clearManagedSyncFailureAfterSuccess } from './sync-failures.ts';
import { assertDrainLease } from './sync-lease.ts';
import { faultPoint } from './fault-points.ts';
import type { SyncCursorOptions } from './sync-prepare.ts';
+import { SYNC_SLICE_OP } from './sync-slices.ts';
type CompanySync = ReturnType<typeof currentCompanyBrainSync>;
@@ -97,7 +98,7 @@ export async function resolveManagedCursor(engine: BrainEngine, input: { sourceI
if (company) continue;
await engine.transaction(async tx => {
await fence(tx);
- await tx.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 AND COALESCE(completed_keys->0->>'done','false')='true'", [row.key]);
+ await deleteFinishedCursor(tx, row.key);
});
await clearManagedSyncFailureAfterSuccess(engine, row.key);
} else {
@@ -132,15 +133,34 @@ export async function retireManagedCursor(engine: BrainEngine, input: { sourceId
if (input.done) {
await engine.transaction(async tx => {
await fence(tx);
- await tx.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 AND COALESCE(completed_keys->0->>'done','false')='true'", [input.key]);
+ await deleteFinishedCursor(tx, input.key);
+ await deleteSliceRecords(tx, input.sourceId, input.incarnation);
});
await clearManagedSyncFailureAfterSuccess(engine, input.key);
return null;
}
const open = await supersede(engine, { key: input.key, done: false, company_receipt_id: null, run_id: input.runId }, { sourceId: input.sourceId, incarnation: input.incarnation, fence });
- if (open === null) return null;
- const busy = open === 'kept' ? await busyRequest(engine, input.sourceId, input.key) : open;
- return busy ? waitOn(busy) : null;
+ if (open === 'kept') {
+ const busy = await busyRequest(engine, input.sourceId, input.key);
+ return busy ? waitOn(busy) : null;
+ }
+ if (open) return waitOn(open);
+ await engine.transaction(async tx => { await fence(tx); await deleteSliceRecords(tx, input.sourceId, input.incarnation); });
+ return null;
+}
+
+/** 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
+ AND COALESCE(completed_keys->0->>'done','false')='true' RETURNING completed_keys->0->>'runId' AS run_id`, [key]);
+ if (row?.run_id) await tx.executeRaw(`DELETE FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1
+ AND NOT EXISTS (SELECT 1 FROM op_checkpoints c WHERE c.op='managed-sync' AND c.completed_keys->0->>'runId'=$1)`, [row.run_id]);
+}
+
+/** The incarnation's path-slice records (sync-slices.ts): only a non-company cursor run cuts its target into slices. */
+async function deleteSliceRecords(tx: BrainEngine, sourceId: string, incarnation: string): Promise<void> {
+ const prefix = `${sourceId}:${incarnation}:`;
+ await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND left(fingerprint, length($2))=$2', [SYNC_SLICE_OP, prefix]);
}
async function busyRequest(engine: BrainEngine, sourceId: string, key: string): Promise<WriteRequest | null> {
const open = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'cursorKey'=$2
diff --git a/test/sync-pass-cursor-retirement-6712.test.ts b/test/sync-pass-cursor-retirement-6712.test.ts
new file mode 100644
index 0000000000..83a653571a
--- /dev/null
+++ b/test/sync-pass-cursor-retirement-6712.test.ts
@@ -0,0 +1,142 @@
+/**
+ * #6712 PR 4b lane C (design v3.2 §3.5): the first live pass of a managed, non-company source retires every legacy
+ * cursor row of that source incarnation, on a real PGLite managed brain.
+ *
+ * Protects: after the first pass, `op_checkpoints` holds no `managed-sync`, `managed-sync-manifest` or
+ * `managed-sync-slice` row of the synced source (an unfinished cursor under the current key with its manifest and its
+ * 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).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { managedCursorKey } from '../src/core/persistence/sync-cursor-key.ts';
+import { resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';
+import { managedSyncAuthority } from '../src/core/persistence/sync-authority.ts';
+import { syncCursorOptions, writeSyncSlice } from '../src/core/persistence/sync-slices.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const note = (title: string) => `---\ntype: concept\ntitle: ${title}\n---\n\nA committed note named ${title} at acme-example.\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true };
+const COMPANY = 'acme-example-co';
+const LEGACY_OPS = ['managed-sync', 'managed-sync-manifest', 'managed-sync-slice'];
+const NAMES = ['acme-example', 'alice-example', 'fund-a'];
+
+let engine: PGLiteEngine;
+let home: string;
+const env = () => ({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined });
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-cursor-retirement-6712-'));
+ await withEnv(env(), async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+});
+
+afterAll(async () => {
+ await withEnv(env(), async () => { await disposePersistenceConsumer(engine); });
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+});
+
+type Row = { op: string; fingerprint: string; completed_keys: unknown; updated_at: string };
+const legacyRows = (db: BrainEngine) => db.executeRaw<Row>(`SELECT op, fingerprint, completed_keys, updated_at::text AS updated_at FROM op_checkpoints
+ WHERE op = ANY($1::text[]) ORDER BY op, fingerprint COLLATE "C"`, [LEGACY_OPS]);
+const at = (minutesAgo: number) => new Date(Date.now() - minutesAgo * 60_000).toISOString();
+async function put(db: BrainEngine, op: string, fingerprint: string, completedKeys: unknown, updatedAt: string) {
+ await db.executeRaw('INSERT INTO op_checkpoints(op, fingerprint, completed_keys, updated_at) VALUES($1, $2, $3::text::jsonb, $4::timestamptz)',
+ [op, fingerprint, JSON.stringify(completedKeys), updatedAt]);
+}
+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 });
+ 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));
+ git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+ await db.executeRaw('INSERT INTO sources(id, name) VALUES($1, $1)', [COMPANY]);
+ await claimWorktree(db, 'default', root);
+ await activateSharedSkillPersistence(db, { confirmQuiesced: true });
+ return root;
+}
+
+/**
+ * The legacy rows an older binary left for the default source: an unfinished cursor under the current key (a path slice
+ * of its first sync) with its manifest and slice record, an unfinished cursor under an older key with its manifest, and
+ * a finished older-key cursor with its manifest. No request is open under any of them.
+ */
+async function seedDefaultCursors(db: BrainEngine, root: string, incarnation: string) {
+ const context = await resolveManagedSyncContext(db, OPTS as never);
+ const authority = await managedSyncAuthority(db, 'default', incarnation, root);
+ const head = git(root, 'rev-parse', 'HEAD');
+ const entries = NAMES.map(name => ({ path: `notes/${name}.md`, sourcePath: `notes/${name}.md`, action: 'import', working: false, slug: `notes/${name}`, pageId: null, revision: null }));
+ const syncOptions = syncCursorOptions(OPTS as never);
+ const processingOptions = { noEmbed: true, noExtract: true, noSchemaPack: false };
+ const binding = { ...context.binding, owner_epoch: String((context.binding as { owner_epoch?: unknown }).owner_epoch), topology_generation: String(context.binding.topology_generation) };
+ const cursor = (runId: string, done: boolean, extra: Record<string, unknown> = {}) => ({ binding, root: context.root, gitRoot: context.gitRoot, sourceId: 'default', incarnation,
+ from: null, target: head, slugMode: 'git-root', discoveredAt: at(90), runId, index: done ? entries.length : 0, authority, processingOptions, syncOptions,
+ counts: { added: done ? entries.length : 0, modified: 0, deleted: 0, chunks: 0 }, ...(done ? { done: true } : {}), total: entries.length, ...extra });
+ const slice = { phase: 'import' as const, after: null, head, target: head };
+ await put(db, 'managed-sync', managedCursorKey(incarnation, undefined), [cursor('run-6712-current', false, { slice: { ...slice, done: false } })], at(10));
+ await put(db, 'managed-sync-manifest', 'run-6712-current', entries, at(10));
+ await writeSyncSlice(db, 'default', incarnation, syncOptions, slice);
+ await put(db, 'managed-sync', 'legacy-6712-unfinished', [cursor('run-6712-older', false)], at(60));
+ await put(db, 'managed-sync-manifest', 'run-6712-older', entries, at(60));
+ await put(db, 'managed-sync', 'legacy-6712-finished', [cursor('run-6712-finished', true)], at(120));
+ await put(db, 'managed-sync-manifest', 'run-6712-finished', entries, at(120));
+}
+
+/** The same three kinds of rows for a company source: its unfinished and finished approval cursors, their manifests, and a slice record. */
+async function seedCompanyCursors(db: BrainEngine) {
+ const incarnation = await incarnationOf(db, COMPANY);
+ const approval = { receiptId: 'receipt-acme-example', plan: { plan_digest: 'plan-acme-example' } } as never;
+ const entries = [{ path: 'handbook/fund-a.md', sourcePath: 'handbook/fund-a.md', action: 'import', working: false, slug: 'handbook/fund-a', pageId: null, revision: null }];
+ const header = (runId: string, done: boolean) => ({ sourceId: COMPANY, incarnation, runId, index: done ? 1 : 0, total: 1, companyReceiptId: 'receipt-acme-example',
+ counts: { added: 0, modified: 0, deleted: 0, chunks: 0 }, ...(done ? { done: true } : {}) });
+ await put(db, 'managed-sync', managedCursorKey(incarnation, approval), [header('run-6712-company', false)], at(30));
+ await put(db, 'managed-sync-manifest', 'run-6712-company', entries, at(30));
+ await put(db, 'managed-sync', 'legacy-6712-company-finished', [header('run-6712-company-finished', true)], at(180));
+ await put(db, 'managed-sync-manifest', 'run-6712-company-finished', entries, at(180));
+ await writeSyncSlice(db, COMPANY, incarnation, syncCursorOptions({}), { phase: 'import', after: null, head: 'c0ffee', target: 'c0ffee' });
+}
+const isCompanyRow = (row: Row) => row.op === 'managed-sync' ? (row.completed_keys as Array<{ sourceId?: string }>)[0]?.sourceId === COMPANY
+ : row.op === 'managed-sync-manifest' ? row.fingerprint.startsWith('run-6712-company') : row.fingerprint.startsWith(`${COMPANY}:`);
+
+describe('#6712 PR 4b lane C: the first live pass retires legacy cursor rows (§3.5)', () => {
+ test('no managed-sync, managed-sync-manifest or managed-sync-slice row of the synced source remains; the pass row exists; the company source is untouched', () => withEnv(env(), async () => {
+ const root = await plantManagedBrain(engine);
+ const incarnation = await incarnationOf(engine, 'default');
+ await seedDefaultCursors(engine, root, incarnation);
+ await seedCompanyCursors(engine);
+ const seeded = await legacyRows(engine);
+ const company = seeded.filter(isCompanyRow);
+ expect(company.map(row => row.op)).toEqual(['managed-sync', 'managed-sync', 'managed-sync-manifest', 'managed-sync-manifest', 'managed-sync-slice']);
+ expect(seeded.filter(row => !isCompanyRow(row)).map(row => row.op)).toEqual(['managed-sync', 'managed-sync', 'managed-sync', 'managed-sync-manifest', 'managed-sync-manifest', 'managed-sync-manifest', 'managed-sync-slice']);
+
+ const result = await performSync(engine, OPTS as never);
+ expect({ status: result.status, reason: result.reason ?? null }).toEqual({ status: 'first_sync', reason: null });
+
+ expect(await legacyRows(engine)).toEqual(company);
+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-pass' AND fingerprint=$1", [`default:${incarnation}`])).toHaveLength(1);
+ // The unfinished cursor's options seeded the episode: the --no-extract it carried is inherited by this pass, which did not pass it.
+ expect(result.inherited_options).toEqual(['noExtract']);
+ 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);
+});