Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(2b gate): annotate the idle kill switch, keep the db-plane publish literal, yield in the batch build, settle ghost fixtures

garrytanb5f89220024f
diff --git a/src/cli/db-plane-config.ts b/src/cli/db-plane-config.ts
index 38e850610f..a1d5bbf875 100644
--- a/src/cli/db-plane-config.ts
+++ b/src/cli/db-plane-config.ts
@@ -9,7 +9,7 @@ import { loadConfigWithEngine, type GBrainConfig } from '../core/config.ts';
import { withRequestConfigSnapshot } from '../core/config-snapshot.ts';
import type { BrainEngine } from '../core/engine.ts';
-export async function mergeDbPlaneConfig(engine: BrainEngine, config: GBrainConfig, mergedByEngine: WeakMap<BrainEngine, GBrainConfig>): Promise<void> {
+export async function mergeDbPlaneConfig(engine: BrainEngine, config: GBrainConfig, MERGED_CONFIG_BY_ENGINE: WeakMap<BrainEngine, GBrainConfig>): Promise<void> {
// v0.27.1 (F3 fix): re-merge DB-plane config now that the engine is up.
// Flags like `embedding_multimodal` are user-mutable via `gbrain config set`
// (DB plane) and need to flow into the gateway after connect. Schema-sizing
@@ -26,7 +26,7 @@ export async function mergeDbPlaneConfig(engine: BrainEngine, config: GBrainConf
// function's per-key config reads on every command (the cost #3980 is
// about). Keyed on the engine so a mounted brain cannot be served the
// host brain's merge.
- mergedByEngine.set(engine, merged);
+ MERGED_CONFIG_BY_ENGINE.set(engine, merged);
// Stash gate flags on process.env for downstream readers (import-file.ts
// dispatches on GBRAIN_EMBEDDING_MULTIMODAL, gates OCR on GBRAIN_EMBEDDING_IMAGE_OCR).
// The OCR *model* reaches the gateway via the re-configure below (#4107); its
diff --git a/src/core/persistence/sync-idle-skips.ts b/src/core/persistence/sync-idle-skips.ts
index 6acf0a9478..66ac1bb262 100644
--- a/src/core/persistence/sync-idle-skips.ts
+++ b/src/core/persistence/sync-idle-skips.ts
@@ -38,6 +38,7 @@ export async function readIdleFacts(engine: Pick<BrainEngine, 'executeRaw'>, sou
/** Whether an idle tick with these facts leaves the settles in IDLE_SKIPS nothing to do. */
export function idleClear(facts: IdleFacts): boolean {
+ // cwd-dotenv-ok: a kill switch that only turns the idle skips off (every settle runs, as before); it names no path.
return process.env.GBRAIN_SYNC_IDLE_FAST_PATH !== '0' && !facts.tail && facts.holds === 0 && facts.holdSummary === 0 && !facts.failures;
}
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 4f4e103c69..e04fcd0af1 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -158,7 +158,13 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh
for (const entry of fresh) twinsAt.set(entry.state.level, (twinsAt.get(entry.state.level) ?? 0) + 1);
const leavingAt = new Map<string, ShadowPath[]>();
for (const gone of leaving.values()) for (const oid of new Set(gone.state.record?.blobOids ?? [])) { const at = leavingAt.get(oid); if (at) at.push(gone); else leavingAt.set(oid, [gone]); }
- const slugOf = new Map(fresh.map(entry => [entry.path, resolveSlugForPath(entryPaths(level, entry.path).sourcePath)]));
+ // A first sync's batch is every new file: each loop below yields between stretches, as a level's own loops do.
+ const step = loopYield();
+ const slugOf = new Map<string, string>();
+ for (const entry of fresh) {
+ if (step.due()) await step.pause();
+ slugOf.set(entry.path, resolveSlugForPath(entryPaths(level, entry.path).sourcePath));
+ }
// #6727, as discovery does: a new origin with no live page at its slug takes the one legacy page (no recorded origin)
// that folds to it; several, or one the importer cannot write, keep the slug and the freeze holds legacy_slug_conflict.
const legacySlugs = new Map<string, Pick<SyncEntry, 'legacySlugs' | 'legacyIdVeto'>>();
@@ -170,6 +176,7 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh
[level.sourceId, [...new Set(adopting.map(entry => slugOf.get(entry.path)!))]]);
const bySlug = new Map(identities.map(page => [page.slug, page]));
for (const entry of adopting) {
+ if (step.due()) await step.pause();
const adopted = named(entry);
slugOf.set(entry.path, await adoptLegacyPage(engine, discovery, identities, bySlug.get(slugOf.get(entry.path)!), slugOf.get(entry.path)!, adopted));
if (adopted.legacySlugs) legacySlugs.set(entry.path, { legacySlugs: adopted.legacySlugs, ...(adopted.legacyIdVeto ? { legacyIdVeto: true as const } : {}) });
@@ -187,6 +194,7 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh
const entries: PassEntry[] = [], collisions: SyncSlugCollision[] = [], skipped: ShadowPath[] = [], identity: Array<{ entry: ShadowPath; origin: ShadowPath | null; slug: string; ids: { page: string; file: string } }> = [];
const claims = new Map<string, ShadowPath[]>();
for (const entry of imports) {
+ if (step.due()) await step.pause();
const paths = entryPaths(level, entry.path);
const base = { ...paths, action: 'import' as const, working: working(entry), level: entry.state.level, ...(entry.result.cls === 'drift' && entry.result.side && entry.result.side !== 'deleted' ? { drift: entry.result.side, ...(driftBaseline(entry) ? { driftBaseline: driftBaseline(entry) } : {}) } : {}) };
if (entry.state.page) { entries.push({ ...base, slug: entry.slug!, pageId: entry.pageId, revision: entry.revision }); continue; }
@@ -215,6 +223,7 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh
return new Map(manifests.flatMap(manifest => manifest.renamed.map(pair => [pair.to, { from: pair.from, ...(pair.identityHead ? { identityHead: pair.identityHead } : {}) }] as const)));
})();
for (const [slug, claimants] of claims) {
+ if (step.due()) await step.pause();
const holder = holders.get(slug);
const holderPath = holder?.source_path ? gitPathOfOrigin(holder.source_path) : null;
const kept = holder && !holder.deleted && holderPath !== null && !leaving.has(holderPath) ? holderPath : null;
diff --git a/test/helpers/managed-brain.ts b/test/helpers/managed-brain.ts
index e870185254..0f4f3c3bfc 100644
--- a/test/helpers/managed-brain.ts
+++ b/test/helpers/managed-brain.ts
@@ -5,7 +5,10 @@ import type { BrainEngine } from '../../src/core/engine.ts';
import type { OperationContext } from '../../src/core/ops/contract.ts';
import { claimWorktree } from '../../src/core/persistence/ownership.ts';
import { activateSharedSkillPersistence } from '../../src/core/persistence/skill-activation.ts';
+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';
+import { localHostId } from '../../src/core/persistence/identity.ts';
import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { testWaitMs } from './wait-for.ts';
import { isolatedSharedSkillsEngine } from './shared-skills-engine.ts';
import { withEnv } from './with-env.ts';
@@ -31,3 +34,20 @@ export async function managedBrain(run: (brain: ManagedBrain) => Promise<void>,
});
} finally { rmSync(home, { recursive: true, force: true }); }
}
+
+/**
+ * Runs queued effects (and waits for the consumer's) until no Git effect of the source is open, so a fixture that edits
+ * the checkout next starts from pages whose files are committed. A put returns once its row commits; its Git publication
+ * lands later, and `disposePersistenceConsumer` right after the put can leave the file untracked: a working-tree-only
+ * page, which a later full pass deletes once its file is gone (a different case from a page whose file left Git's checkout).
+ */
+export async function settleManagedGitEffects(engine: BrainEngine, sourceId = 'default'): Promise<void> {
+ const deadline = performance.now() + testWaitMs(30_000);
+ for (;;) {
+ await runPersistenceEffects(engine, { engine: engine.kind }, { hostId: localHostId(), limit: 10 });
+ const open = await engine.executeRaw("SELECT 1 FROM persistence_effects WHERE source_id=$1 AND kind='git' AND state<>'committed'", [sourceId]);
+ if (!open.length) return;
+ if (performance.now() > deadline) throw new Error(`${open.length} Git effect(s) of ${sourceId} still open after the wait`);
+ await Bun.sleep(50);
+ }
+}
diff --git a/test/pathological/s-sync-offpath-2b.test.ts b/test/pathological/s-sync-offpath-2b.test.ts
index 2cc73a936d..7253ab1ca5 100644
--- a/test/pathological/s-sync-offpath-2b.test.ts
+++ b/test/pathological/s-sync-offpath-2b.test.ts
@@ -36,6 +36,7 @@ import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../
import { installFixtureChunks } from '../helpers/page-projection.ts';
import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
import { durableGitRepo } from '../helpers/git-publication.ts';
+import { settleManagedGitEffects } from '../helpers/managed-brain.ts';
import { withEnv } from '../helpers/with-env.ts';
import { managedBrain, pathologicalArms } from './harness.ts';
import { md, record, withProbeEngine, withProbeRepo } from './s-blockers-fixture.ts';
@@ -121,6 +122,8 @@ describe('GBRA-133 2b.2: the ghost report runs after the sync, rate-limited per
for (const slug of ['notes/kept', 'notes/gone']) {
await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: `---\ntype: note\ntitle: ${slug}\n---\n\n${slug} body.\n` } });
}
+ // The files are committed first: a page whose file never reached Git is a working-tree page, which a full pass deletes.
+ await settleManagedGitEffects(engine);
await disposePersistenceConsumer(engine);
const ghosts = await import('../../src/core/persistence/sync-ghosts.ts') as Partial<typeof import('../../src/core/persistence/sync-ghosts.ts')>;
const since = ghosts.syncGhostDecisions?.length ?? 0;
diff --git a/test/serve-http-head-watcher.serial.test.ts b/test/serve-http-head-watcher.serial.test.ts
index 107cf64c10..c86454532c 100644
--- a/test/serve-http-head-watcher.serial.test.ts
+++ b/test/serve-http-head-watcher.serial.test.ts
@@ -74,8 +74,9 @@ test('runServeHttp starts the head watcher with the serve and stops it on SIGINT
expect(watcherIntervals).toHaveLength(1);
const cleared = () => clearSpy.mock.calls.filter(([h]) => h === watcherIntervals[0]).length;
expect(cleared()).toBe(0);
- // http-server (lifecycle), resolve-ipc-close and pglite-engine-disconnect: the watcher adds none of its own.
- expect(_registeredCleanupCountForTests()).toBe(baseline + 3);
+ // http-server (lifecycle), resolve-ipc-close, pglite-engine-disconnect and the resident notifier's
+ // lease release (GBRA-133 2b: a SIGTERM hands the lease over at once); the watcher adds none of its own.
+ expect(_registeredCleanupCountForTests()).toBe(baseline + 4);
process.emit('SIGINT');
await done;
diff --git a/test/serve-http-run-teardown.serial.test.ts b/test/serve-http-run-teardown.serial.test.ts
index 06fefcdce1..e707d7a952 100644
--- a/test/serve-http-run-teardown.serial.test.ts
+++ b/test/serve-http-run-teardown.serial.test.ts
@@ -54,14 +54,14 @@ test('SIGINT shutdown closes the resolve-IPC socket and deregisters every cleanu
const baseline = _registeredCleanupCountForTests();
const done = runServeHttp(engine, { port: 0, tokenTtl: 3600, enableDcr: false });
let socketPath: string | undefined;
- for (let i = 0; i < 200 && (socketPath === undefined || _registeredCleanupCountForTests() < baseline + 3); i++) {
+ for (let i = 0; i < 200 && (socketPath === undefined || _registeredCleanupCountForTests() < baseline + 4); i++) {
socketPath ??= lines.map(l => /Resolve IPC: (\S+)/.exec(l)?.[1]).find(Boolean);
await Bun.sleep(25);
}
expect(socketPath, `resolve-IPC path not logged; stderr:\n${lines.join('\n').slice(-2000)}`).toBeDefined();
expect(existsSync(socketPath!)).toBe(true);
- // http-server (lifecycle), resolve-ipc-close and pglite-engine-disconnect.
- expect(_registeredCleanupCountForTests()).toBe(baseline + 3);
+ // http-server (lifecycle), resolve-ipc-close, pglite-engine-disconnect and the resident notifier's lease release.
+ expect(_registeredCleanupCountForTests()).toBe(baseline + 4);
process.emit('SIGINT');
await done;
diff --git a/test/sync-exits-l4-6712.test.ts b/test/sync-exits-l4-6712.test.ts
index 9706c985d8..fc9222e008 100644
--- a/test/sync-exits-l4-6712.test.ts
+++ b/test/sync-exits-l4-6712.test.ts
@@ -30,7 +30,7 @@ import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
-import { managedBrain } from './helpers/managed-brain.ts';
+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
import { durableGitRepo } from './helpers/git-publication.ts';
describe('#6712 PR 2 L4: the fault table and source_changed routing', () => {
@@ -223,6 +223,8 @@ describe('#6712 PR 2 L4: ghost pages after a managed sync', () => {
for (const slug of ['notes/kept', 'notes/gone']) {
await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: `---\ntype: note\ntitle: ${slug}\n---\n\n${slug} body.\n` } });
}
+ // The files are committed first: a page whose file never reached Git is a working-tree page, which a full pass deletes.
+ await settleManagedGitEffects(engine);
await disposePersistenceConsumer(engine);
// GBRA-133 2b.2: the scan runs in the background after a sync (interval 0 here: every sync starts one) and the next
// sync reports what it found.
diff --git a/test/sync-pass-batch-entries-6712.test.ts b/test/sync-pass-batch-entries-6712.test.ts
index 2593ee6b05..90a33fd875 100644
--- a/test/sync-pass-batch-entries-6712.test.ts
+++ b/test/sync-pass-batch-entries-6712.test.ts
@@ -6,9 +6,16 @@
*
* Forced probe: a first sync of ${PATHS} new files sharing one blob (each has every other as a twin). The stretch from the
* batch build's start to the first freeze is timed on the thread's CPU; the run is aborted there, so nothing is imported.
+ *
+ * Its linear work still ran as one stretch with no timer turn: about 62 ms of thread CPU on a dev box and 98-125 ms on a
+ * loaded 16-vCPU CI VM, against the 100 ms bound. Its loops now yield as a level's own loops do (sync-yield.ts). The second
+ * probe makes each new file's slug cost SLUG_CPU_MS of CPU, so a build that does not yield holds timers well past the
+ * bound on any machine (451 ms here before the fix).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
+import type { BrainEngine } from '../src/core/engine.ts';
+import * as syncCore from '../src/core/sync.ts';
import { installFaultHook } from '../src/core/persistence/fault-points.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { watchLoopLag } from './helpers/cpu-time.ts';
@@ -16,6 +23,7 @@ import { managedBrain } from './helpers/managed-brain.ts';
const PATHS = 8_000;
const MAX_LAG_MS = 100;
+const SLUG_CPU_MS = 0.05;
const git = (root: string, args: string[], input?: string) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', input, maxBuffer: 1 << 26 }).trim();
const setup = ({ root }: { root: string }) => {
@@ -30,17 +38,42 @@ const setup = ({ root }: { root: string }) => {
afterEach(() => installFaultHook(undefined));
describe('GBRA-133 PR 2b: a first sync builds its batch in linear time', () => {
- test(`the batch build of ${PATHS} new same-blob files never blocks a timer for ${MAX_LAG_MS} ms`, () => managedBrain(async ({ engine }) => {
+ /** The most thread CPU the sync ran between two timer turns, from the batch build's start to the first freeze. */
+ const batchBuildLag = async (engine: BrainEngine, inWindow: () => boolean = () => false) => {
let lag: ReturnType<typeof watchLoopLag> | undefined, maxLag: number | undefined;
const stop = new AbortController();
+ window.open = false;
installFaultHook(async point => {
- if (point === 'sync:batch_entries' && !lag) lag = watchLoopLag();
- if (point === 'sync:after_freeze' && lag && maxLag === undefined) { maxLag = lag.stop().maxLag; stop.abort(); }
+ if (point === 'sync:batch_entries' && !lag) { lag = watchLoopLag(); window.open = inWindow(); }
+ if (point === 'sync:after_freeze' && lag && maxLag === undefined) { window.open = false; maxLag = lag.stop().maxLag; stop.abort(); }
});
await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, signal: stop.signal }).catch(() => undefined);
installFaultHook(undefined);
+ window.open = false;
if (lag && maxLag === undefined) lag.stop();
+ return maxLag;
+ };
+ const window = { open: false };
+
+ test(`the batch build of ${PATHS} new same-blob files never blocks a timer for ${MAX_LAG_MS} ms`, () => managedBrain(async ({ engine }) => {
+ const maxLag = await batchBuildLag(engine);
expect(maxLag).toBeDefined();
expect(Math.round(maxLag!)).toBeLessThan(MAX_LAG_MS);
}, { setup }), 300_000);
+
+ test(`with ${SLUG_CPU_MS} ms of CPU per new file's slug, the batch build still yields within ${MAX_LAG_MS} ms`, () => managedBrain(async ({ engine }) => {
+ const resolve = syncCore.resolveSlugForPath;
+ let slowed = 0;
+ const spy = spyOn(syncCore, 'resolveSlugForPath').mockImplementation(((...args: Parameters<typeof resolve>) => {
+ // A wall-clock spin: thread CPU advances in ~4 ms steps on some hosts, too coarse for a per-call cost.
+ if (window.open) { slowed++; const end = performance.now() + SLUG_CPU_MS; while (performance.now() < end) { /* the slug's cost */ } }
+ return resolve(...args);
+ }) as typeof resolve);
+ try {
+ const maxLag = await batchBuildLag(engine, () => true);
+ expect(slowed).toBeGreaterThanOrEqual(PATHS);
+ expect(maxLag).toBeDefined();
+ expect(Math.round(maxLag!)).toBeLessThan(MAX_LAG_MS);
+ } finally { spy.mockRestore(); }
+ }, { setup }), 300_000);
});