Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): #6712 PR 4b the pin rolls back with an interrupt; legacy markers stay owed until written; admission fences the owner epoch
garrytan62796cd07a40
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 25eeb4aaeb..24dbac71cd 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -49,6 +49,8 @@ export interface WriteAdmission {pageId?: number | null;worktreeId?: string | null;topologyGeneration?: string | number | null;+ /** #6712 PR 4b: the worktree owner epoch the caller resolved; admission refuses `source_changed` when it moved. */+ ownerEpoch?: string | number | null;requestId?: string;/** F6: the client's non-UUID request_id, stored beside the canonical id and never digested. */clientRequestId?: string;@@ -518,19 +520,19 @@ export async function chargePreparationAttempt(engine: SqlEngine, row: WriteRequasync function assertWorktreeAdmission(tx: BrainEngine, input: WriteAdmission): Promise<void> {// Sent together: the server takes the share lock before it reads the fence and the binding.const [[worktree], [state]] = await pipelined(tx, [- () => tx.executeRaw<{ state: string }>('SELECT state FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [input.worktreeId]),+ () => tx.executeRaw<{ state: string; owner_epoch: string }>('SELECT state,owner_epoch::text AS owner_epoch FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [input.worktreeId]),() => tx.executeRaw<{ refresh: { id: string; state: string; source_ids: string[] } | string | null; bound: boolean }>(`SELECT(SELECT row_to_json(f) FROM (SELECT id,state,source_ids FROM persistence_worktree_refreshesWHERE worktree_id=$3::uuid AND state IN ${ACTIVE_REFRESH_STATES_SQL} LIMIT 1) f) AS refresh,EXISTS (SELECT 1 FROM persistence_source_bindings WHERE source_id=$1AND source_incarnation=$2::uuid AND worktree_id=$3::uuid AND topology_generation=$4) AS bound`,[input.sourceId, input.sourceIncarnation, input.worktreeId, input.topologyGeneration]),- ]) as [Array<{ state: string }>, Array<{ refresh: { id: string; state: string; source_ids: string[] } | string | null; bound: boolean }>];+ ]) as [Array<{ state: string; owner_epoch: string }>, Array<{ refresh: { id: string; state: string; source_ids: string[] } | string | null; bound: boolean }>];const refresh = typeof state?.refresh === 'string' ? JSON.parse(state.refresh) as { id: string; state: string; source_ids: string[] } : state?.refresh ?? null;if (refresh) await assertWorktreeNotRefreshing(tx, input, refresh);// #6741 C: a background producer never takes a permanent request id against a worktree in recovery (a draining owner still replays).if (worktree?.state === 'recovering' && resolveAdmissionOrigin(input.origin) === 'background') throw backgroundWorktreeInactive(input.sourceId, worktree.state, ownerStatusFix(input.sourceId));- if (!state?.bound) throw opError('source_changed', 'The source binding changed during admission.',+ if (!state?.bound || input.ownerEpoch != null && worktree && worktree.owner_epoch !== String(input.ownerEpoch)) throw opError('source_changed', 'The source binding changed during admission.',`Source ${input.sourceId}'s worktree binding changed (a claim, transfer or lifecycle change) while this write was being admitted, so nothing was accepted. Check the owner with the command in fix, then submit the write again; reusing the same request_id is safe because nothing was recorded.`,{ fix: ownerStatusFix(input.sourceId) });}diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.tsindex e6dd265b20..795b70965a 100644--- a/src/core/persistence/sync-group.ts+++ b/src/core/persistence/sync-group.ts@@ -150,7 +150,7 @@ export async function freezeFollowers<P extends WaiverEntry & { rebound?: true }}/** Admits the group's members that have no request yet, in one transaction, while the cursor still holds this group. */-export async function admitGroup(engine: BrainEngine, members: WaiverEntry[], cursor: { sourceId: string; incarnation: string; binding: { worktree_id: string; topology_generation: string | number }; authority: SyncAuthority },+export async function admitGroup(engine: BrainEngine, members: WaiverEntry[], cursor: { sourceId: string; incarnation: string; binding: { worktree_id: string; topology_generation: string | number; owner_epoch?: string | number }; authority: SyncAuthority },cursorHolds: (tx: BrainEngine) => Promise<boolean>): Promise<WriteRequest[] | null> {const head = members[0]!;return retryWriteAdmission(head.requestId, remaining => engine.transaction(async tx => {@@ -160,7 +160,7 @@ export async function admitGroup(engine: BrainEngine, members: WaiverEntry[], cu[`${Math.min(1000, remaining)}ms`, `${remaining}ms`]),() => admitWriteGroupInTransaction(tx, members.map(member => ({ requestId: member.requestId, operation: 'submit_job',sourceId: cursor.sourceId, sourceIncarnation: cursor.incarnation, slug: member.slug, pageId: member.pageId,- worktreeId: cursor.binding.worktree_id, topologyGeneration: cursor.binding.topology_generation,+ worktreeId: cursor.binding.worktree_id, topologyGeneration: cursor.binding.topology_generation, ownerEpoch: cursor.binding.owner_epoch,principal: cursor.authority.writer.principal, authority: cursor.authority.writer, callerIntent: member.intent, intent: member.intent }))),]) as [unknown, WriteRequest[]];if (!await cursorHolds(tx)) throw new GroupMoved();diff --git a/src/core/persistence/sync-pass-row.ts b/src/core/persistence/sync-pass-row.tsindex 829348c0dd..d18fbbc04e 100644--- a/src/core/persistence/sync-pass-row.ts+++ b/src/core/persistence/sync-pass-row.ts@@ -72,6 +72,8 @@ export interface ManagedSyncPassValue {faults: Record<string, { level: string | null; class: string; attempts: number }>;/** #6712 PR 4b (design §2.7): when the incarnation's first full round swept every `legacy_unverified` page; later passes sweep at most 500. */legacy_sweep?: { first_full_at: string };+ /** #6712 PR 4b (design §2.7 (b1)): when the incarnation's legacy markers were written; until then each pass's first round writes them (idempotent). */+ legacy_markers_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. */diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex cf06e13057..8957dbcb43 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -354,7 +354,8 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prconst value: ManagedSyncPassValue = { source_id: sourceId, incarnation, lease_token: lease.token, obligations,telemetry: { pass_id: passId, target: head, started_at: startedAt, ended_at: null, kind, round: 0, outcome: 'open', stop_reason: null, candidates: 0, settled: 0, remaining: 0,counts: {}, duration_ms: null, timings_ms: {} } };- const bootstrap = !prior;+ // The incarnation's legacy markers (§2.7 b1) are owed until a local pass wrote them, not only by its first row.+ const markersOwed = () => remote ? !prior : !value.obligations.legacy_markers_at;if (kind === 'idle' && working.cache) rememberWorkingStatCache(cacheKey, working.cache);if (kind === 'idle') {@@ -387,6 +388,8 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr// The lease check and the clock read share a round trip: a lost lease aborts the transaction before the row is written.[, value.telemetry.started_at] = await Promise.all([assertDrainLease(tx, sourceId), databaseNow(tx)]);await writePassRow(tx, value, { pin: true });+ // An interrupt during the pin rolls the pin back with it: no `open` row is left for a pass that never ran.+ assertActive();});assertActive();registerPassCost(passId, { sourceId, incarnation, scope: costScope, pricePerMTok: currentEmbeddingPricePerMTok() });@@ -474,7 +477,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): PrassertActive();value.telemetry.round = round;const level = await readShadowLevel(engine, { sourceId, context, workingTree: mode === 'working',- pass: { noSchemaPack: processingOptions.noSchemaPack, 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: markersOwed() } });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@@ -483,7 +486,11 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): PrlevelSlugMode = level.slugMode;lastLevel = level;value.telemetry.timings_ms = level.timings_ms;- if (bootstrap && round === 1 && !remote) await writeLegacyMarkers(engine, level);+ // Design §2.7 (b1): until the incarnation's markers are written (an aborted or failed first pass wrote none), not only on its first row.+ if (markersOwed() && !remote) {+ await writeLegacyMarkers(engine, level);+ value.obligations.legacy_markers_at = new Date().toISOString();+ }await applyPassRound(engine, level, { passId, observedAt: startedAt, remote, admission, fullRound: kind === 'full', obligations: value.obligations, context, processingOptions,grantPrefixes: remote ? authority.writer.slugPrefixes : null }, applied);assertActive();diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex aabec4d980..49b57d1868 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -1423,7 +1423,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP[`${Math.min(1000, remaining)}ms`, `${remaining}ms`]);const accepted = await admitWriteInTransaction(tx, { requestId: pending.requestId, operation: 'submit_job',sourceId: admitting.sourceId, sourceIncarnation: admitting.incarnation, slug: pending.slug, pageId: pending.pageId,- worktreeId: admitting.binding.worktree_id, topologyGeneration: admitting.binding.topology_generation,+ worktreeId: admitting.binding.worktree_id, topologyGeneration: admitting.binding.topology_generation, ownerEpoch: admitting.binding.owner_epoch,principal: admitting.authority.writer.principal, authority: admitting.authority.writer, callerIntent: pending.intent, intent: pending.intent });// ENG-A7: after the counter locks (the publication lock order), admit only while the cursor still holds this entry// with this intent (#6075: a bulk pass may have grouped the head since this pass read it).diff --git a/test/sync-pass-rulings-6712.test.ts b/test/sync-pass-rulings-6712.test.tsindex d660c6fee3..734e87aa18 100644--- a/test/sync-pass-rulings-6712.test.ts+++ b/test/sync-pass-rulings-6712.test.ts@@ -129,6 +129,28 @@ describe('#6712 PR 4b classifier rulings (pglite)', () => {expect(await classOf(engine, 'notes/c.md')).toMatchObject({ cls: 'legacy_same', settled: true });}, { setup }), 180_000);+ test('b1: the legacy markers stay owed after a first pass that wrote none; a prior pass row alone does not skip them', () => managedBrain(async ({ engine, ctx }) => {+ await engine.setConfig('sync.write_through', 'false');+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const deletion = await deletePage(engine, ctx, 'notes/c');+ await raw(engine, () => engine.executeRaw("DELETE FROM pages WHERE source_id='default' AND slug IN ('notes/b','notes/c')"));+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1', [SYNC_ORIGIN_DELETED_OP]);+ // The row an incarnation's first pass leaves when it fails before its first round wrote the markers: no converged+ // state and no marker stamp, beside the baseline it pinned.+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_build_array(jsonb_set(jsonb_set(+ (completed_keys->0) #- '{obligations,converged}' #- '{obligations,legacy_markers_at}',+ '{obligations,baseline_commit}', to_jsonb((SELECT last_commit FROM sources WHERE id='default'))),+ '{telemetry,outcome}', '"failed"'::jsonb)) WHERE op=$1`, [MANAGED_SYNC_PASS_OP]);++ expect((await performManagedSync(engine, OPTS)).status).not.toBe('blocked_by_failures');+ expect(await liveSlugs(engine)).toEqual(['notes/a', 'notes/b']);+ const markers = await engine.executeRaw<{ fingerprint: string; value: { kind: string; deletion: string | null } }>(+ 'SELECT fingerprint, completed_keys->0 AS value FROM op_checkpoints WHERE op=$1', [SYNC_ORIGIN_DELETED_OP]);+ expect(markers.map(row => ({ path: row.fingerprint.split(':').pop(), kind: row.value.kind, deletion: row.value.deletion }))).toEqual([{ path: 'notes/c.md', kind: 'legacy', deletion }]);+ const [row] = await engine.executeRaw<{ at: string | null }>("SELECT completed_keys->0->'obligations'->>'legacy_markers_at' AS at FROM op_checkpoints WHERE op=$1", [MANAGED_SYNC_PASS_OP]);+ expect(row?.at).toBeString();+ }, { setup }), 180_000);+test('b4/b6: the receipt counts dirty paths by their own action and the source\'s legacy twin pairs', () => managedBrain(async ({ engine, root }) => {writeFileSync(join(root, 'notes/Foo Bar.md'), note('Foo Bar', 'A synthetic observation about Foo Bar.')); commit(root, 'twin file');expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');