Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): one bounded writer probe for the facts, atom and connector-sync preflights

garrytand68f5288f3c3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2f2d7010c0..268e081448 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -129,7 +129,7 @@ The release also absorbs 62 open community pull requests, each re-checked agains
- **What the agent saves with `remember` is no longer stored a second time by automatic capture (#5888).** The writeback hook, the compaction harvest and the corpus sweep skip a fact only on an exact normalized match (rules above). Capture counts same-entity near duplicates (cosine 0.92 or higher) without dropping them, so a threshold can be measured first. Hot memory and the `context_pack`/`delta` facts show one line per duplicate group. Each skip is logged on stderr and in the hook heartbeat, and `gbrain doctor` (`memory_writeback`) reports `cross_lane_duplicates_7d` and `near_duplicates_shadow_7d`.
- **The maintenance sweep reads whole session transcripts, and a resumed session no longer re-extracts the same head (#5887).** Windows break at turn boundaries and carry their `[user]` or `[assistant]` label, pasted blocks are removed first, and the progress sidecar makes appends and compaction rewrites cost only their new turns. `gbrain sweep --once --json` reports `corpus_files[]` with `windows_done` and `windows_remaining`. Ported from #5897. Contributed by @javieraldape.
-- **A capture right after another managed write no longer refuses as "writer busy".** The managed-facts preflight probed the worktree lock with no wait, while this process's own persistence consumer was still finishing the previous write (its receipt already read committed). A `remember` followed by automatic capture could lose that capture for a whole sweep cycle. The preflight now waits up to 1 s; a writer still busy after that refuses with `writer_lock_unavailable` as before.
+- **A capture or atom drain right after another managed write no longer refuses as "writer busy".** The managed-facts preflight, the atom-maintenance session and the connector-sync preflight probed the worktree lock with no wait, while this process's own persistence consumer was still finishing the previous write (its receipt already read committed). A `remember` followed by automatic capture could lose that capture for a whole sweep cycle, and an atom drain burned one of its capped attempts. All three now share one bounded probe that waits up to 1 s (`MANAGED_WRITER_PROBE_WAIT_MS`); a writer still busy after that refuses with `writer_lock_unavailable` as before. The connector-sync probe only exists to re-stamp a moved checkout's device, so a busy result there still lets the sync continue.
- **New explicit repair `gbrain repair captured-facts`** expires facts captured before v0.60.30.0 from gbrain's own claude-cli sessions or from pasted text (doctor `captured_facts_active`; the post-upgrade banner names the preview). Self-capture facts with evidence expire with `--apply --expect <hash>`; paste candidates (a word-overlap heuristic against the retained session corpus) only with `--include-ambiguous`. A claim with a legitimate active copy is kept. Facts are expired, never withdrawn, so `remember` can save the claim again.
#### Search (#5889, #5890, #5892)
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index acf4e250ff..0f7d26277f 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -9,7 +9,7 @@ import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './a
import { currentVerifiedLocalWriter, localHostId, registerLocalWriter } from './identity.ts';
import { admitWriteInTransaction, getWriteRequest, receiptFor } from './journal.ts';
import { digest, requireUuid, sha256 } from './digest.ts';
-import { acquireWorktree, getWorktreeBinding, managedPersistenceEnabled, type WorktreeBinding } from './ownership.ts';
+import { getWorktreeBinding, managedPersistenceEnabled, probeWorktreeWriter, type WorktreeBinding } from './ownership.ts';
import { isConnectorSourceKind } from './connector-identity.ts';
import { preparePageMutation } from './page-prepare.ts';
import { assertPersistenceAccepting, waitForWrite, writeResponse } from './service.ts';
@@ -99,9 +99,7 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,
const { binding, writeThrough, connectorDatabase, refusal } = await atomOwnerTarget(engine, sourceId, source);
if (refusal) throw new OperationError('owner_unavailable', refusal);
if (writeThrough && binding) {
- const lock = await acquireWorktree(binding, 0, undefined, engine);
- if (!lock) throw new OperationError('writer_lock_unavailable', 'The canonical atom writer is busy; no extraction was started.');
- await lock.release();
+ if (!await probeWorktreeWriter(binding, engine)) throw new OperationError('writer_lock_unavailable', 'The canonical atom writer is busy; no extraction was started.');
}
if (!writeThrough) authority.databaseOnlyReason = 'disabled_by_config';
else if (connectorDatabase) authority.databaseOnlyReason = 'connector_database';
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index d74a2dbf38..5a63d72056 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -16,7 +16,7 @@ import { authorizeStoredRequest, authorizeWrite } from './authority.ts';
import { materializeTimeline, prepareCanonicalProjections } from './canonical-projections.ts';
import { digest, sha256 } from './digest.ts';
import { admitWriteInTransaction, assertReplayIntent, getWriteRequest, getWriteRequestById, intentDigest, receiptFor } from './journal.ts';
-import { acquireWorktree, containsPath, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
+import { acquireWorktree, containsPath, getWorktreeBinding, probeWorktreeWriter, type WorktreeBinding } from './ownership.ts';
import { localHostId } from './identity.ts';
import { assertPersistenceAccepting, startPersistenceConsumer, waitForWrite, writeResponse } from './service.ts';
import { managedSyncAuthority, validateManagedSyncOptions, validateSyncAuthority, type SyncAuthority } from './sync-authority.ts';
@@ -189,7 +189,7 @@ export async function beginConnectorSync(engine: BrainEngine, sourceId: string,
const authority = await managedSyncAuthority(engine, sourceId, source.incarnation, source.local_path ?? '');
const binding = await getWorktreeBinding(engine, sourceId);
// The locked acquisition re-stamps a device-only physical-root change (#5604) before the root is asserted.
- if (binding) { checkedConnectorBinding(sourceId, source, binding); await (await acquireWorktree(binding, 0, undefined, engine))?.release(); }
+ if (binding) { checkedConnectorBinding(sourceId, source, binding); await probeWorktreeWriter(binding, engine); }
else authority.writer.databaseOnlyReason = 'connector_database';
const canonicalRoot = connectorBindingRoot(sourceId, source, binding);
const session = new ManagedConnectorSync(engine, sourceId, identity, source, authority, binding, canonicalRoot, opts.noEmbed === true, opts.noSchemaPack === true,
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index af629039d6..dfe66bf635 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -14,7 +14,7 @@ import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './a
import { authorizePageVisibility } from './page-visibility.ts';
import { initializeLocalPersistence } from './page-mutations.ts';
import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
-import { acquireWorktree, getWorktreeBinding, managedPersistenceEnabled, type WorktreeBinding } from './ownership.ts';
+import { getWorktreeBinding, managedPersistenceEnabled, probeWorktreeWriter, type WorktreeBinding } from './ownership.ts';
import { authorizeFactsBackstop } from './effect-facts.ts';
import { admitWriteInTransaction, getWriteRequest, getWriteRequestById, receiptFor } from './journal.ts';
import { assertPersistenceAccepting, waitForWrite, writeResponse } from './service.ts';
@@ -103,16 +103,6 @@ export async function assertManagedFactsEmbedding(engine: BrainEngine, config: G
}
}
-/**
- * How long the managed-facts preflight waits for the worktree lock. This
- * process's own persistence consumer holds it while it finishes publishing
- * the previous write, after that write's receipt already reads committed, so
- * a capture that follows a `remember` or another capture found it busy and
- * refused for a whole sweep cycle. A holder still busy after the wait is a
- * real conflict and still refuses.
- */
-export const MANAGED_FACTS_WRITER_WAIT_MS = 1000;
-
export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
input: { turnText: string; pageSlug?: string }): Promise<ManagedFactsSession | null> {
const engine = ctx.engine;
@@ -176,9 +166,7 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
if (writeThrough && binding) {
if (binding.state !== 'active' || !binding.owner_host_id) throw new OperationError('owner_unavailable', 'The canonical fact writer is unavailable; extraction has not started.');
if (binding.owner_host_id === localHostId()) {
- const lock = await acquireWorktree(binding, MANAGED_FACTS_WRITER_WAIT_MS, undefined, engine);
- if (!lock) throw new OperationError('writer_lock_unavailable', 'The canonical fact writer is busy; extraction has not started.');
- await lock.release();
+ if (!await probeWorktreeWriter(binding, engine)) throw new OperationError('writer_lock_unavailable', 'The canonical fact writer is busy; extraction has not started.');
}
}
if (!writeThrough) authority.databaseOnlyReason = 'disabled_by_config';
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index ce3e0f9607..6c932cb1e5 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -139,6 +139,22 @@ export async function acquireWorktree(binding: WorktreeBinding, waitMs = 0, sign
} catch (failure) { await lock.release(); throw failure; }
}
}
+/**
+ * How long a managed writer's preflight probe waits for the worktree lock.
+ * This process's own persistence consumer holds it while it finishes
+ * publishing the previous write, after that write's receipt already reads
+ * committed, so a zero-wait probe refused on our own writer. A holder still
+ * busy after the wait is a real conflict.
+ */
+export const MANAGED_WRITER_PROBE_WAIT_MS = 1000;
+
+/** Acquire-and-release probe of the worktree lock within MANAGED_WRITER_PROBE_WAIT_MS; false when it stayed busy. */
+export async function probeWorktreeWriter(binding: WorktreeBinding, engine?: BrainEngine): Promise<boolean> {
+ const lock = await acquireWorktree(binding, MANAGED_WRITER_PROBE_WAIT_MS, undefined, engine);
+ if (!lock) return false;
+ await lock.release();
+ return true;
+}
export async function guardOwnership(tx: SqlEngine, row: WriteRequest, hostId: string): Promise<WorktreeBinding | null> {
if (!row.worktree_id) return null;
const [owner] = await tx.executeRaw<{ owner_host_id: string; owner_epoch: string | number; state: string }>(
diff --git a/test/capture-dedup.test.ts b/test/capture-dedup.test.ts
index d6ecd254f1..591daf1d84 100644
--- a/test/capture-dedup.test.ts
+++ b/test/capture-dedup.test.ts
@@ -25,7 +25,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding, MANAGED_WRITER_PROBE_WAIT_MS } from '../src/core/persistence/ownership.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -33,7 +33,6 @@ import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedT
import { runFactsPipeline, type FactsBackstopCtx } from '../src/core/facts/backstop.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { disposePersistenceConsumer, persistenceConsumerStatus } from '../src/core/persistence/service.ts';
-import { MANAGED_FACTS_WRITER_WAIT_MS } from '../src/core/persistence/facts-maintenance.ts';
import { getBrainHotMemoryMeta, __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';
import { readHeartbeatTail } from '../src/core/context/hook-heartbeat.ts';
import { buildMemoryWritebackCheck } from '../src/commands/doctor/checks/memory-writeback.ts';
@@ -158,21 +157,21 @@ for (const mode of ['unmanaged', 'managed'] as const) {
const run = (fn: () => Promise<void>) => withEnv({ GBRAIN_HOME: home }, async () => { await freshSource(mode); await fn(); });
if (mode === 'managed') {
- // The preflight waits up to MANAGED_FACTS_WRITER_WAIT_MS for the worktree
+ // The preflight waits up to MANAGED_WRITER_PROBE_WAIT_MS for the worktree
// lock: a writer finishing its previous publication is not a conflict.
const holdLock = async (ms: number) => {
const lock = await acquireWorktree((await getWorktreeBinding(engine, sourceId))!, 0, undefined, engine);
expect(lock).not.toBeNull();
- return new Promise<void>(resolve => setTimeout(() => { void lock!.release().then(resolve); }, ms));
+ return { released: new Promise<void>(resolve => setTimeout(() => { void lock!.release().then(resolve); }, ms)) };
};
test('the fact preflight waits out a writer that releases within the bound', () => run(async () => {
- const released = holdLock(200);
+ const { released } = await holdLock(200);
extracts([{ fact: 'Bob Example owns the Acme Example launch checklist', entity: 'people/bob-example' }]);
expect(await capture('hook:writeback', 'sess-lock')).toMatchObject({ inserted: 1 });
await released;
}), 60_000);
test('a writer busy past the bound still refuses with writer_lock_unavailable', () => run(async () => {
- const released = holdLock(MANAGED_FACTS_WRITER_WAIT_MS + 1500);
+ const { released } = await holdLock(MANAGED_WRITER_PROBE_WAIT_MS + 1500);
extracts([{ fact: 'Bob Example owns the Acme Example budget review', entity: 'people/bob-example' }]);
await expect(capture('hook:writeback', 'sess-lock-2')).rejects.toMatchObject({ code: 'writer_lock_unavailable' });
await released;
diff --git a/test/managed-writer-probe.test.ts b/test/managed-writer-probe.test.ts
new file mode 100644
index 0000000000..dce45de7f1
--- /dev/null
+++ b/test/managed-writer-probe.test.ts
@@ -0,0 +1,91 @@
+/**
+ * The managed-writer preflight probe (`probeWorktreeWriter`) waits up to
+ * MANAGED_WRITER_PROBE_WAIT_MS for the worktree lock: this process's own
+ * persistence consumer holds it while it finishes publishing the previous
+ * write, after that receipt already reads committed. The facts preflight, the
+ * atom-maintenance session and the connector-sync preflight all use it. A
+ * holder that releases within the bound is waited out; one held past it is
+ * still busy (the atom session refuses with writer_lock_unavailable).
+ *
+ * Synthetic data only. PGLite.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { managedAtomSession } from '../src/core/persistence/atom-maintenance.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding, MANAGED_WRITER_PROBE_WAIT_MS, probeWorktreeWriter, type WorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let home: string;
+let sourceId: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'gbrain-writer-probe-')); });
+afterEach(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(home, { recursive: true, force: true });
+});
+
+async function managedSource(): Promise<WorktreeBinding> {
+ sourceId = `wp-${randomUUID().slice(0, 8)}`;
+ const root = mkdtempSync(join(home, 'root-'));
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return (await getWorktreeBinding(engine, sourceId))!;
+}
+
+/** Takes the worktree lock now and releases it after `ms`; `released` settles after the release. */
+async function hold(binding: WorktreeBinding, ms: number): Promise<{ released: Promise<void> }> {
+ const lock = await acquireWorktree(binding, 0, undefined, engine);
+ expect(lock).not.toBeNull();
+ return { released: new Promise<void>(resolve => setTimeout(() => { void lock!.release().then(resolve); }, ms)) };
+}
+
+const run = (fn: () => Promise<void>) => withEnv({ GBRAIN_HOME: home }, fn);
+
+describe('probeWorktreeWriter (connector-sync and facts preflights)', () => {
+ test('a holder that releases at 200 ms is waited out', () => run(async () => {
+ const binding = await managedSource();
+ const { released } = await hold(binding, 200);
+ expect(await probeWorktreeWriter(binding, engine)).toBe(true);
+ await released;
+ }), 30_000);
+
+ test('a holder kept past the bound leaves the writer busy', () => run(async () => {
+ const binding = await managedSource();
+ const { released } = await hold(binding, MANAGED_WRITER_PROBE_WAIT_MS + 1500);
+ const started = performance.now();
+ expect(await probeWorktreeWriter(binding, engine)).toBe(false);
+ expect(performance.now() - started).toBeGreaterThanOrEqual(MANAGED_WRITER_PROBE_WAIT_MS - 50);
+ await released;
+ }), 30_000);
+});
+
+describe('managedAtomSession preflight', () => {
+ test('a holder that releases at 200 ms is waited out', () => run(async () => {
+ const binding = await managedSource();
+ const { released } = await hold(binding, 200);
+ expect(await managedAtomSession(engine, sourceId)).not.toBeNull();
+ await released;
+ }), 30_000);
+
+ test('a holder kept past the bound still refuses with writer_lock_unavailable', () => run(async () => {
+ const binding = await managedSource();
+ const { released } = await hold(binding, MANAGED_WRITER_PROBE_WAIT_MS + 1500);
+ await expect(managedAtomSession(engine, sourceId)).rejects.toMatchObject({ code: 'writer_lock_unavailable' });
+ await released;
+ }), 30_000);
+});