Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync-pass): a keep_db write refused for write capacity waits as keep_db_pending, never a file_drift hold
garrytand3c8dbe9ab85
diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.tsindex ed14672f13..3cfd05731a 100644--- a/src/core/persistence/sync-pass-apply.ts+++ b/src/core/persistence/sync-pass-apply.ts@@ -33,6 +33,8 @@ import type { BrainEngine } from '../engine.ts';import { resolveSlugForPath } from '../sync.ts';import { massReconcileAllowed, planReconcileDeletes } from '../sync-reconcile.ts';import { admitKeepDbReconcile, freezeKeepDbReconcile, releaseMatchedDriftSkips } from '../repair/keep-db-policy.ts';++const KEEP_DB_CAPACITY_REFUSALS = new Set(['capacity', 'write_capacity_backpressure', 'queue_capacity', 'write_quota_exhausted', 'writer_busy', 'writer_pool_capacity']);import type { SyncProcessingOptions } from './sync-authority.ts';import type { SyncClassified } from './sync-classify.ts';import { readOnlySameContentScreen } from './sync-convergence.ts';@@ -330,6 +332,7 @@ async function admitKeepDb(engine: BrainEngine, level: ShadowLevel, input: PassAconst bytes = blobs.get(entry.state.level!);const refuse = (reason: string) => {state.keepDb.refused[reason] = (state.keepDb.refused[reason] ?? 0) + 1;+ if (KEEP_DB_CAPACITY_REFUSALS.has(reason)) { state.keepDb.pending++; settleAs(entry, { settled: true, action: 'none', pending: 'keep_db' }); return; }if (entry.result.cls === 'keep_db') settleAs(entry, { cls: 'drift', settled: false, action: 'hold', side: entry.state.record?.revision != null ? 'both' : 'unknown', classAction: 'repair' });};if (!bytes) { refuse('bytes_unreadable'); continue; }diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 2cc890fe5e..c902a17fd2 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -55,6 +55,7 @@ import { applyPassRound, finishPassApply, newPassApplyState, passApplyCounts, reimport { passCostDecision, passEpisodeClosure, readReservedUsd, registerPassCost, unregisterPassCost } from './sync-pass-episode.ts';import { currentEmbeddingPricePerMTok } from '../embedding.ts';import { massReconcileAllowed } from '../sync-reconcile.ts';+import { keepDbHeadroom } from '../repair/keep-db-policy.ts';/** Rounds a pass runs before it stops `not_converged` (design §3.1). */export const PASS_MAX_ROUNDS = 4;@@ -364,8 +365,10 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): PrworkingChange: working.changed, rescreenDueHold: holds.some(hold => holdRescreenDue(hold, retry.includes(hold.path))), full: opts.full === true });// Design §2.6: a withheld mass delete is applied by a full round once the owner host's env valve allows it.const valveOpen = !remote && !!obligations.deletes_withheld && massReconcileAllowed();- // Design §4: keep_db writes the previous pass's cap deferred (`keep_db_pending`) are owed to this pass, so it is not idle.- const keepDbOwed = !remote && admission === 'normal' && (prior?.value.telemetry.classes?.keep_db_pending?.count ?? 0) > 0;+ // Design §4: keep_db writes the previous pass deferred (`keep_db_pending`: its cap, or write capacity) are owed to this pass, so it is+ // not idle, unless write capacity still stops them; then the idle tick stays idle instead of re-reading the tree every tick.+ const keepDbOwed = !remote && admission === 'normal' && kindOf.kind === 'idle' && (prior?.value.telemetry.classes?.keep_db_pending?.count ?? 0) > 0+ && !(await keepDbHeadroom(engine));const kind: PassKind = admission === 'classify_only' && kindOf.kind === 'idle' ? 'idle' : (valveOpen || keepDbOwed) && kindOf.kind === 'idle' ? 'full' : kindOf.kind;const 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,diff --git a/src/core/repair/keep-db-policy.ts b/src/core/repair/keep-db-policy.tsindex 924fe582fa..e88fbd1c6a 100644--- a/src/core/repair/keep-db-policy.ts+++ b/src/core/repair/keep-db-policy.ts@@ -50,7 +50,7 @@ export interface KeepDbPolicy { source_id: string; keep_db: string[] }*/export type KeepDbAdmission = (engine: BrainEngine) => Promise<'capacity' | 'write_capacity_backpressure' | null>;-const headroom: KeepDbAdmission = async engine => {+export const keepDbHeadroom: KeepDbAdmission = async engine => {const rows = await capacity({ engine, remote: false } as OperationContext);const need = (resource: string) => resource === 'lifetime_ids' ? 1 : RECEIPT_RESERVATION_FLOOR;if (rows.some(c => c.used + need(c.resource) > c.stop_at)) return 'capacity';@@ -161,7 +161,7 @@ export async function admitKeepDbReconcile(engine: BrainEngine, artifact: KeepDbconst requestId = await keepDbRequestId(engine, writer.principal, artifact);const prior = await getWriteRequest(engine, writer.principal, requestId);if (prior) return { request: prior, replayed: true };- const stop = await (opts.admission ?? headroom)(engine);+ const stop = await (opts.admission ?? keepDbHeadroom)(engine);if (stop) return { refused: stop };let fenced: { error: unknown } | undefined;let paused = false;diff --git a/test/sync-prescreen-drift-6712.test.ts b/test/sync-prescreen-drift-6712.test.tsindex 858a28fea2..69cc594928 100644--- a/test/sync-prescreen-drift-6712.test.ts+++ b/test/sync-prescreen-drift-6712.test.ts@@ -33,6 +33,7 @@ import { resolveBulkSettings } from '../src/core/persistence/sync-group.ts';import { readShadowLevel } from '../src/core/persistence/sync-pass.ts';import { managedBrain } from './helpers/managed-brain.ts';import { waitFor } from './helpers/wait-for.ts';+import { isWriteCapacityWait } from '../src/core/persistence/admission-retry.ts';const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };@@ -204,6 +205,30 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATexpect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain('The database-only edit of notes/a.');}, { databaseUrl, setup }), 180_000);+ test('two-sided keep_db pages whose keep_db write is refused for write capacity wait as keep_db_pending and are never held file_drift; later passes admit them', () => managedBrain(async ({ engine, ctx, root }) => {+ await engine.setConfig('sync.write_through', 'false');+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const twoSided = ['notes/a', 'notes/b', 'notes/c', 'notes/d'];+ for (const slug of twoSided) {+ await databaseOnlyEdit(engine, ctx, slug, `The database-only edit of ${slug}.`);+ writeFileSync(join(root, `${slug}.md`), note(slug, `A committed edit of ${slug}.`));+ }+ writeFileSync(join(root, 'gbrain.yml'), 'storage:\n keep_db:\n - notes/\n'); commit(root, 'keep_db and file edits');+ // Two outstanding requests per writer: the pass's third keep_db admission is refused queue_capacity while the first two are in flight.+ await engine.setConfig('persistence.limits.principal_outstanding', '2');+ const incarnation = await incarnationOf(engine);+ for (let pass = 0; pass < 8; pass++) {+ // The drain (sync-drain.ts) waits out an outstanding-cap refusal of a sync's own write; a direct pass call does the same here.+ const result = await performManagedSync(engine, OPTS).catch(async error => { if (!isWriteCapacityWait(error)) throw error; await new Promise(r => setTimeout(r, 200)); return null; });+ if (result) expect(heldOf(result)).toEqual([]);+ for (const slug of twoSided) expect(await readGitHold(engine, 'default', incarnation, `${slug}.md`)).toBeNull();+ }+ for (const slug of twoSided) {+ expect(await bodyOf(engine, slug)).toContain(`The database-only edit of ${slug}.`);+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain(`The database-only edit of ${slug}.`);+ }+ }, { databaseUrl, setup }), 180_000);+test('cold upgrade: a database-only edit with no provenance is held, with partial or obsolete provenance it is db_ahead; no edit is overwritten, in a tree walk or under --full', () => managedBrain(async ({ engine, ctx, root }) => {await engine.setConfig('sync.write_through', 'false');expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');