Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): reset a committed pending cursor on recorded failure (#5687)

garrytan5c5086aca48c
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index dc328e35cc..426bcdf419 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -16,7 +16,7 @@
- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths.
- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).
-- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.
+- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.
- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 29484352f6..2533d32eb0 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -322,7 +322,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
const failed = cursor.pending ? await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId) : null;
const recorded = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, cursor.runId]);
assertActive();
- if ((failed && ['failed', 'conflict', 'cancelled'].includes(failed.state)) || (!failed && recorded.length)) {
+ if ((failed && ['failed', 'conflict', 'cancelled'].includes(failed.state)) || (recorded.length && (failed?.state === 'committed' || !failed))) {
phase = 'discovery';
discoveryTarget = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();
const discovery = await discoverManagedSync(engine, opts, context);
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index d4a15be775..2b699def40 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -495,3 +495,59 @@ test('managed sync still rejects conflicting explicit slugs on extension-bearing
expect(await engine.getPage('notes/other', { sourceId: f.id })).toBeNull();
}
}), 120_000);
+
+test('retry-failed resets cursor when pending write is committed but failure record exists', async () =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ const f = await fixture(engine, {
+ 'a.md': 'First observation committed during the original sync run.\n',
+ 'b.md': 'Second observation not yet imported.\n',
+ });
+ const abort = new AbortController();
+ const partial = await performManagedSync(engine, {
+ sourceId: f.id, noPull: true, noEmbed: true, noExtract: false,
+ signal: abort.signal,
+ onProgress: p => { if (p.phase === 'managed_sync.page_committed') abort.abort(); },
+ });
+ expect(partial).toMatchObject({ status: 'partial', filesImported: 1 });
+ await disposePersistenceConsumer(engine);
+
+ // The progress callback fires AFTER cursor advancement. Reconstruct the
+ // crash window between the committed write and that cursor update.
+ const [row] = await engine.executeRaw<{ fingerprint: string; completed_keys: [{
+ runId: string; incarnation: string; index: number;
+ counts: { added: number; modified: number; deleted: number; chunks: number };
+ pending?: { requestId: string; slug: string; pageId: number | null; intent: SyncIntent };
+ }] }>("SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);
+ const [committed] = await engine.executeRaw<{ request_id: string; slug: string; intent: SyncIntent; state: string }>(
+ "SELECT request_id,slug,intent,state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [f.id]);
+ expect(committed?.state).toBe('committed');
+ expect(committed?.slug).toBe('a');
+ const cursor = row.completed_keys[0];
+ cursor.index = 0;
+ cursor.counts = { added: 0, modified: 0, deleted: 0, chunks: 0 };
+ cursor.pending = { requestId: committed.request_id, slug: committed.slug, pageId: null, intent: committed.intent };
+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1",
+ [row.fingerprint, JSON.stringify([cursor])]);
+ expect((await engine.getPage('a', { sourceId: f.id }))?.compiled_truth).toContain('First observation');
+ expect(await engine.getPage('b', { sourceId: f.id })).toBeNull();
+
+ // A real mismatched invocation records the failure against that run.
+ await expect(performManagedSync(engine, {
+ sourceId: f.id, noPull: true, noEmbed: true, noExtract: true,
+ })).rejects.toThrow('processing options');
+ const failuresBefore = await engine.executeRaw(
+ "SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [row.fingerprint, cursor.runId]);
+ expect(failuresBefore).toHaveLength(1);
+
+ const retried = await performManagedSync(engine, {
+ sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, retryFailed: true,
+ });
+ expect(['first_sync', 'synced']).toContain(retried.status);
+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('Second observation');
+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);
+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1", [row.fingerprint])).toHaveLength(0);
+ await disposePersistenceConsumer(engine);
+ }
+ }), 120_000);