Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): background producers run the claim's owner verification once per source per run and skip a source that fails it (#6741)
garrytan98985817b093
diff --git a/src/core/persistence/admission-origin.ts b/src/core/persistence/admission-origin.tsindex 61f6cd8513..9b56399082 100644--- a/src/core/persistence/admission-origin.ts+++ b/src/core/persistence/admission-origin.ts@@ -33,16 +33,19 @@ export const DEFAULT_BACKGROUND_PAUSE_SHARE = 0.8;/** What a paused admission's doctor finding names as paused. */export const BACKGROUND_PRODUCERS = ['managed maintenance', 'conversation facts', 'autopilot cycle phases', 'autopilot catch-up sync', 'minion jobs'] as const;-const scope = new AsyncLocalStorage<AdmissionOrigin>();+/** #6741 C: a run's origin, and its per-source owner verification outcomes (backgroundOwnerCheck). */+interface OriginScope { origin: AdmissionOrigin; owners: Map<string, Promise<OperationError | null>> }+const scope = new AsyncLocalStorage<OriginScope>();/** Runs `fn` with every admission inside it attributed to `origin` (a background scope wins over an inner interactive caller). */export function withAdmissionOrigin<T>(origin: AdmissionOrigin, fn: () => T): T {- return scope.run(scope.getStore() === 'background' ? 'background' : origin, fn);+ const outer = scope.getStore();+ return scope.run(outer?.origin === 'background' ? outer : { origin, owners: new Map() }, fn);}/** The origin an admission is charged to: a surrounding background scope, else the explicit origin, else the scope, else background. */export function resolveAdmissionOrigin(explicit?: AdmissionOrigin): AdmissionOrigin {- const surrounding = scope.getStore();+ const surrounding = scope.getStore()?.origin;if (surrounding === 'background') return 'background';return explicit ?? surrounding ?? 'background';}@@ -88,3 +91,24 @@ export function backgroundWorktreeInactive(sourceId: string, state: string, owne`Nothing was submitted and no request id was used. Background work for source ${sourceId} resumes once its writer is active again; writer status shows what it is waiting on.`,{ fix: ownerStatusFix });}++/**+ * #6741 C: the owner verification of one source, at most once per background producer run: the outcome is cached in+ * the surrounding background scope (withAdmissionOrigin('background', …)); an admission outside any scope verifies+ * on its own.+ */+export function backgroundOwnerCheck(sourceId: string, verify: () => Promise<OperationError | null>): Promise<OperationError | null> {+ const owners = scope.getStore()?.owners;+ if (!owners) return verify();+ let check = owners.get(sourceId);+ if (!check) { check = verify(); owners.set(sourceId, check); }+ return check;+}++/** #6741 C: the refusal of a background admission whose source's owner on this host fails the claim's owner verification. */+export function backgroundOwnerUnverified(sourceId: string, physicalError: string | undefined, ownerStatusFix: Action): OperationError {+ return opError('owner_unavailable', `Background writes to source ${sourceId} are paused: its canonical owner could not be verified.`,+ `${physicalError ?? `Source ${sourceId}'s host binding has no canonical path or coordination lock path.`} Nothing was submitted and no request id was used. `+ + `Writer status shows the recovery the source needs (a deleted owner marker is repaired by a writer self-transfer, the user's decision); background work resumes after it.`,+ { fix: ownerStatusFix });+}diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex b1ddcda863..56225da639 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -15,6 +15,7 @@ import { pipelined } from '../page-state/transactions.ts';import { backgroundPaused, backgroundWorktreeInactive, readBackgroundPauseShare, resolveAdmissionOrigin, type AdmissionOrigin } from './admission-origin.ts';import { EFFECT_BYTES_SQL, RECEIPT_RESERVATION_FLOOR, receiptReservation, retainedReceiptBytes, TRUE_UP_CLAMP_SQL } from './receipt-bytes.ts';import { writeHealth, type WriteHealthFacts } from './health.ts';+import { assertBackgroundOwner } from './owner-verification.ts';import { writerStamp } from './writer-versions.ts';import { intentCarriesContent, intentCarriesPurgedContent, PURGE_PRESENCE_COLUMNS } from './purged-intent.ts';import { hostname } from 'node:os';@@ -244,6 +245,8 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, overif (!Number.isSafeInteger(terminalBytes) || terminalBytes < 1024) throw new TypeError('Invalid terminal receipt reservation.');const stamp = writerStamp();const origin = resolveAdmissionOrigin(input.origin);+ // #6741 C: a background producer is refused before any receipt when the source's owner fails its verification.+ if (origin === 'background' && input.worktreeId) await assertBackgroundOwner(engine, input.sourceId, ownerStatusFix);return { requestId, apply: async (tx: BrainEngine): Promise<WriteRequest> => {await declarePersistenceProtocol(tx);// The guards are sent together in lock order (worktree, source, writer, counters) and judged in@@ -324,6 +327,7 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writconst items = inputs.map(input => ({ input, requestId: requireUuid(input.requestId ?? randomUUID()), fingerprint: intentDigest(input),bytes: jsonBytes(input.intent) + jsonBytes(input.authority), terminalBytes: Math.max(input.terminalReservation ?? 0, receiptReservation(input)) }));assertMutationProtocol({ target_kind: 'page', protocol_version: 1 });+ if (first.worktreeId && resolveAdmissionOrigin(first.origin) === 'background') await assertBackgroundOwner(tx, first.sourceId, ownerStatusFix);const ids = items.map(item => item.requestId);// #5984: the checks are independent reads and share locks, so they go out back to back in the order they always// had (protocol, graduation, worktree, source, writer, counters); a failure is raised in that order.diff --git a/src/core/persistence/onboarding.ts b/src/core/persistence/onboarding.tsindex 18553280fd..f93a1099e9 100644--- a/src/core/persistence/onboarding.ts+++ b/src/core/persistence/onboarding.ts@@ -3,7 +3,7 @@ import { dirname, join } from 'node:path';import type { BrainEngine } from '../engine.ts';import { existingLocalHostId, persistenceHome } from './identity.ts';import { containsPath, getWorktreeBinding, readManagedMode } from './ownership.ts';-import { assertPhysicalRoot } from './physical-root.ts';+import { verifyOwnerRoot } from './owner-verification.ts';import { inspectLegacyWriterLocks } from './legacy-locks.ts';import { UNSUPPORTED_MANAGED_BULK_WRITERS } from './maintenance.ts';import { isConnectorSourceKind } from './connector-identity.ts';@@ -40,11 +40,9 @@ export async function writerOnboardingPreflight(engine: BrainEngine, sourceId?:let physicalError: string | undefined;if (binding && (binding.source_incarnation !== row.incarnation || binding.state !== 'active')) state = 'recovery_required';if (binding && binding.owner_host_id !== host) state = 'owner_host_required';- if (binding?.owner_host_id === host && (!binding.local_path || !binding.coordination_path)) state = 'recovery_required';- if (binding?.owner_host_id === host && binding.local_path) {- try { assertPhysicalRoot(binding.local_path, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path }); }- catch (error) { state = 'recovery_required'; physicalError = error instanceof Error ? error.message : String(error); }- }+ // #6741 C: the claim's owner verification, shared with background admissions (owner-verification.ts).+ const owner = binding?.owner_host_id === host ? verifyOwnerRoot(binding) : null;+ if (owner) { state = 'recovery_required'; physicalError = owner.physical_error; }const root = binding?.local_path ?? (connector ? null : configured);const paths = root ? containerPathPreflight({ canonical_root: root, reservation_parent: dirname(root), persistence_home: persistenceHome(),coordination_directory: binding?.coordination_path ? dirname(binding.coordination_path) : join(persistenceHome(), 'locks') }) : undefined;diff --git a/src/core/persistence/owner-verification.ts b/src/core/persistence/owner-verification.tsnew file mode 100644index 0000000000..ce3330a1ae--- /dev/null+++ b/src/core/persistence/owner-verification.ts@@ -0,0 +1,50 @@+/**+ * #6741 C: the claim's owner verification, shared by writer onboarding (its `recovery_required` state, which the+ * managed purge reads per source) and the background admission check. A claimed source whose owner is this host+ * can publish only when its host binding names a canonical path and a coordination lock path and the physical root+ * still carries its marker and reservation (`assertPhysicalRoot`). A worktree whose state is still `active` can+ * fail it, for example after `.gbrain-owner.json` is deleted, so a state-only check misses it.+ *+ * A background producer verifies each source once per run (backgroundOwnerCheck in admission-origin.ts caches+ * the outcome for the surrounding background scope; outside a scope it runs per admission) and, when it fails, is+ * refused `owner_unavailable` with the owner-status fix before any receipt, so no request id is spent.+ */+import type { Action } from '../agent-output.ts';+import { OperationError } from '../ops/contract.ts';+import type { SqlEngine } from './model.ts';+import { existingLocalHostId } from './identity.ts';+import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';+import { assertPhysicalRoot } from './physical-root.ts';+import { backgroundOwnerCheck, backgroundOwnerUnverified } from './admission-origin.ts';++/**+ * The owner verification for a binding owned by this host: null when it holds, else why not (with the physical-root+ * error, if any). `restampable`: the paths are recorded and the only change is the filesystem device id (#5604), which+ * the owner's locked worktree acquisition re-stamps before it publishes.+ */+export function verifyOwnerRoot(binding: Pick<WorktreeBinding, 'worktree_id' | 'local_path' | 'coordination_path'>): { physical_error?: string; restampable?: true } | null {+ let failed = !binding.local_path || !binding.coordination_path;+ let physicalError: string | undefined, restampable = false;+ if (binding.local_path) {+ try { assertPhysicalRoot(binding.local_path, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path }); }+ catch (error) {+ restampable = !failed && error instanceof OperationError && error.detail === 'physical_root_device_changed';+ failed = true; physicalError = error instanceof Error ? error.message : String(error);+ }+ }+ if (!failed) return null;+ return { ...(physicalError ? { physical_error: physicalError } : {}), ...(restampable ? { restampable: true as const } : {}) };+}++/** Refuses a background admission for a source whose owner on this host fails the verification (cached per background run). */+export async function assertBackgroundOwner(engine: SqlEngine, sourceId: string, ownerStatusFix: (sourceId: string) => Action): Promise<void> {+ const refusal = await backgroundOwnerCheck(sourceId, async () => {+ const host = existingLocalHostId();+ const binding = await getWorktreeBinding(engine, sourceId, host);+ if (!binding || binding.owner_host_id !== host) return null;+ const failure = verifyOwnerRoot(binding);+ // A device-only change is re-stamped by the publication's own locked acquisition (#5604), so it does not refuse here.+ return failure && !failure.restampable ? backgroundOwnerUnverified(sourceId, failure.physical_error, ownerStatusFix(sourceId)) : null;+ });+ if (refusal) throw refusal;+}diff --git a/test/background-owner-verification.test.ts b/test/background-owner-verification.test.tsnew file mode 100644index 0000000000..7e4e65c81f--- /dev/null+++ b/test/background-owner-verification.test.ts@@ -0,0 +1,129 @@+/**+ * #6741 C (final v3 review, item 5): the reporter's `recovery_required` came from a deleted `.gbrain-owner.json`+ * while the worktree state was still `active`, so a state-only check misses it. A background producer runs the+ * claim's owner verification (the canonical paths, the physical root and its marker, owner-verification.ts: the+ * check writer onboarding reports as `recovery_required`) once per source per run, caches it for the run, and+ * skips the source with `owner_unavailable` and the owner-status fix when it fails; the purge's per-source+ * writer preflight runs the same verification. Interactive writes are unaffected.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runCycle } from '../src/core/cycle.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withAdmissionOrigin } from '../src/core/persistence/admission-origin.ts';+import { writerOnboardingPreflight } from '../src/core/persistence/onboarding.ts';+import { PHYSICAL_ROOT_MARKER } from '../src/core/persistence/root-metadata.ts';+import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++const SOURCE = 'owner-verify';+let engine: PGLiteEngine;+let dir: string;+let root: string;++beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });++const env = () => ({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined });+const logger = { info() {}, warn() {}, error() {} };+const ctxFor = (admissionOrigin: 'interactive' | 'background'): OperationContext => ({ engine, sourceId: SOURCE, remote: false, dryRun: false, logger,+ config: { engine: engine.kind, embedding_disabled: true } as never, admissionOrigin });+const put = (origin: 'interactive' | 'background', slug: string) => submitPageMutation(ctxFor(origin), { operation: 'put_page',+ params: { slug, content: '---\ntitle: Note\ntype: note\n---\nBackground maintenance output.', request_id: randomUUID() } });+const lifetimeIds = async () => Number((await engine.executeRaw<{ n: string }>("SELECT lifetime_ids::text AS n FROM persistence_counters WHERE key='brain'"))[0]?.n ?? 0);+const worktreeState = async () => (await engine.executeRaw<{ state: string }>(+ 'SELECT w.state FROM persistence_worktrees w JOIN persistence_source_bindings b ON b.worktree_id=w.id WHERE b.source_id=$1', [SOURCE]))[0]?.state;+const deleteMarker = () => rmSync(join(root, PHYSICAL_ROOT_MARKER));++beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ dir = mkdtempSync(join(tmpdir(), 'gb-owner-verify-'));+ root = join(dir, 'brain');+ mkdirSync(root);+ await withEnv(env(), async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [SOURCE, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, SOURCE, root);+ await submitPageMutation(ctxFor('interactive'), { operation: 'put_page', params: { slug: 'notes/expired', content: '---\ntitle: Expired\ntype: note\n---\nGone soon.', request_id: randomUUID() } });+ const snapshot = await engine.readPageSnapshot('notes/expired', { sourceId: SOURCE });+ await submitPageMutation(ctxFor('interactive'), { operation: 'delete_page', params: { slug: 'notes/expired', expected_revision: snapshot!.revision, request_id: randomUUID() } });+ await engine.executeRaw("UPDATE pages SET deleted_at=now() - interval '100 hours' WHERE source_id=$1 AND slug='notes/expired'", [SOURCE]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ });+ expect(existsSync(join(root, PHYSICAL_ROOT_MARKER))).toBe(true);+});+afterEach(async () => { await disposePersistenceConsumer(engine); rmSync(dir, { recursive: true, force: true }); });++describe('#6741 C: the owner marker deleted while the worktree state is still active', () => {+ test('writer onboarding reports recovery_required for it, with the state still active', async () => {+ deleteMarker();+ expect(await worktreeState()).toBe('active');+ const [source] = (await withEnv(env(), () => writerOnboardingPreflight(engine, SOURCE))).sources;+ expect(source).toMatchObject({ source_id: SOURCE, state: 'recovery_required', physical_error: expect.any(String) });+ });++ test('the purge spends no request id and reports why, and the cycle purge phase warns', async () => {+ deleteMarker();+ const before = await lifetimeIds();+ const result = await withEnv(env(), () => purgeDeletedPagesCoordinated(engine, 72));+ expect(result).toMatchObject({ count: 0, failed: 0, inactive: 1 });+ expect(result.blocked).toEqual([expect.objectContaining({ slug: 'notes/expired', code: 'writer_not_active', binding_state: 'recovery_required' })]);+ expect(result.blocked[0]!.reason.length).toBeGreaterThan(80);+ const phase = (await withEnv(env(), () => runCycle(engine, { brainDir: root, phases: ['purge'], sourceId: SOURCE }))).phases.find(p => p.phase === 'purge')!;+ expect(phase.status).toBe('warn');+ expect(await lifetimeIds()).toBe(before);+ }, 120_000);++ test('a background admission is refused owner_unavailable with the owner-status fix before any receipt', async () => {+ deleteMarker();+ const before = await lifetimeIds();+ const refusal = await withEnv(env(), () => put('background', 'notes/background')).then(() => null, error => error as { code: string; message: string; fix?: { argv?: string[] } });+ expect(refusal).toMatchObject({ code: 'owner_unavailable', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', SOURCE, '--json'] } });+ expect(refusal!.message).toContain(SOURCE);+ expect(await lifetimeIds()).toBe(before);+ expect((await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE slug='notes/background'")).length).toBe(0);+ }, 120_000);++ test('the verification runs once per source per background run and is cached for that run', async () => {+ await withEnv(env(), () => withAdmissionOrigin('background', async () => {+ await put('background', 'notes/first');+ deleteMarker();+ // Same run: the cached verification (taken before the marker went) stands, so this one is admitted; its+ // publication then meets the owner check itself and ends recovery_required.+ const idsBefore = await lifetimeIds();+ const second = await put('background', 'notes/second').then(() => null, error => error as { code?: string });+ expect(second?.code).toBe('recovery_required');+ expect(await lifetimeIds()).toBe(idsBefore + 1);+ }));+ const before = await lifetimeIds();+ // A new run verifies again and refuses.+ await expect(withEnv(env(), () => withAdmissionOrigin('background', () => put('background', 'notes/third')))).rejects.toMatchObject({ code: 'owner_unavailable' });+ expect(await lifetimeIds()).toBe(before);+ }, 120_000);++ test('a failed verification is cached too: the run refuses each later admission without spending an id', async () => {+ deleteMarker();+ const before = await lifetimeIds();+ await withEnv(env(), () => withAdmissionOrigin('background', async () => {+ for (const slug of ['notes/a', 'notes/b', 'notes/c']) await expect(put('background', slug)).rejects.toMatchObject({ code: 'owner_unavailable' });+ }));+ expect(await lifetimeIds()).toBe(before);+ }, 120_000);++ test('an interactive admission is not subject to the background verification', async () => {+ deleteMarker();+ const before = await lifetimeIds();+ await withEnv(env(), () => put('interactive', 'notes/interactive')).catch(() => undefined);+ expect(await lifetimeIds()).toBe(before + 1);+ }, 120_000);+});