Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test: isolate yield-bound tests from shard-process work; pin GC and clock in two flaky tests

garrytan54bcedf1c947
diff --git a/test/doctor-content-golden.test.ts b/test/doctor-content-golden.test.ts
index 55cb6332e8..691dbffa2d 100644
--- a/test/doctor-content-golden.test.ts
+++ b/test/doctor-content-golden.test.ts
@@ -62,6 +62,12 @@ const PAGES: Record<string, string> = {
const BROKEN_PAGE = ['---', 'title: [unclosed', 'tags: a: b', '---', 'Body with [[alice-example]].', ''].join('\n');
const FIXED_DATE = '2024-01-01T00:00:00Z';
+/**
+ * The fixture's clock (fixed-clock-preload.ts). The capacity forecast's `max_day_7d` is the largest UTC day of journal
+ * rows, so a capture whose writes straddle midnight UTC splits its 7 rows across two days (6 on one read on #7375's
+ * 00:06 UTC shard). Noon leaves 12 hours for a capture's writes to stay on one day.
+ */
+const CONTENT_CLOCK = '2026-10-10T12:00:00Z';
function writeSource(dir: string): void {
for (const [rel, body] of Object.entries(PAGES)) {
@@ -79,7 +85,7 @@ type Captures = Record<string, GbrainRun>;
const ALL = defineNormalizer<Captures>(DOCTOR.name, (c) => Object.fromEntries(Object.entries(c).map(([k, v]) => [k, DOCTOR.apply(v)])));
async function capture(): Promise<Captures> {
- const h = makeDoctorHome('doctor-content-golden');
+ const h = makeDoctorHome('doctor-content-golden', { clock: CONTENT_CLOCK });
homes.push(h);
const src = join(h.home, 'notes-src');
writeSource(src);
diff --git a/test/helpers/isolated-test.ts b/test/helpers/isolated-test.ts
new file mode 100644
index 0000000000..dd8e41838f
--- /dev/null
+++ b/test/helpers/isolated-test.ts
@@ -0,0 +1,30 @@
+import { expect, test } from 'bun:test';
+
+/**
+ * A test whose body runs in a fresh `bun test` process of its own file, for bounds on the thread's CPU between timer
+ * runs (`watchLoopLag`). In a unit shard one process runs a few hundred files in turn, and that reading covers every
+ * task on the thread: a timer an earlier file left running, or a collection pause that grows with the heap the earlier
+ * files left. With a 60 ms timer left running every 100 ms, sync-pass-patched-domain-yield read 112-113 ms in its own
+ * process and 47 ms in a fresh one (2 of 2 each); a collection's pause on a 4M-object heap read 45-64 ms
+ * (test/loop-lag-cpu-clock.test.ts). The parent waits for the child, so the shard runs nothing else on that thread.
+ *
+ * The child finds its test by `GBRAIN_TEST_ISOLATED_NAME` (under `GBRAIN_TEST_`, so the operator-env scrub keeps it).
+ */
+export function isolatedTest(file: string, name: string, body: () => unknown, timeoutMs: number): void {
+ const isolated = process.env.GBRAIN_TEST_ISOLATED_NAME;
+ if (isolated !== undefined) {
+ if (isolated === name) test(name, body as () => Promise<void>, timeoutMs);
+ return;
+ }
+ test(name, async () => {
+ const child = Bun.spawn([process.execPath, 'test', `--timeout=${timeoutMs}`, file, '-t', name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')], {
+ env: { ...process.env, GBRAIN_TEST_ISOLATED_NAME: name }, stdout: 'pipe', stderr: 'pipe',
+ });
+ const [out, err] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ const output = out + err;
+ if (child.exitCode !== 0 || !/^ 1 pass$/m.test(output) || !/^ 0 fail$/m.test(output)) {
+ throw new Error(`the isolated run of "${name}" did not pass exactly one test (exit ${child.exitCode}):\n${output.slice(-6000)}`);
+ }
+ expect(child.exitCode).toBe(0);
+ }, timeoutMs + 30_000);
+}
diff --git a/test/loop-lag-cpu-clock.test.ts b/test/loop-lag-cpu-clock.test.ts
index 29360f3b16..3d564689aa 100644
--- a/test/loop-lag-cpu-clock.test.ts
+++ b/test/loop-lag-cpu-clock.test.ts
@@ -20,6 +20,11 @@
* mi_page_purge_holes_now < _mi_thread_idle_work < waitSyncImpl < atomicsFuncWait.
* With a 6M-object heap and 1.5M objects dropped before each of 40 blocks, Atomics.wait read up to 108 ms and
* Bun.sleepSync at most 0.3 ms.
+ * A collection the engine starts while the thread blocks charges its own pause to the reading: the collector stops the
+ * thread when the block returns, and that pause grows with the heap. Bun.sleepSync read 31 ms on #7383 (Bun 1.4.4).
+ * With a 4M-object heap, 50k objects dropped and an async collection requested before each of 12 blocks, one block per
+ * process read 45-64 ms of thread CPU and 193-213 ms of wall time, on Bun 1.4.3 and 1.4.4 (8 of 8 processes, a full
+ * collection's first pause); a full collection run before each block left at most 4 ms (8 of 8).
*/
import { expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
@@ -31,6 +36,7 @@ const MAX_LAG_MS = 100;
const turn = () => new Promise<void>(resolve => setTimeout(resolve, 20));
/** Blocks the thread off the CPU for `ms`; returns the thread CPU the block cost. */
const offCpu = (ms: number) => {
+ Bun.gc(true);
const start = threadCpuNow();
Bun.sleepSync(ms);
return threadCpuNow() - start;
diff --git a/test/sync-pass-batch-entries-6712.test.ts b/test/sync-pass-batch-entries-6712.test.ts
index 90a33fd875..754d71384a 100644
--- a/test/sync-pass-batch-entries-6712.test.ts
+++ b/test/sync-pass-batch-entries-6712.test.ts
@@ -12,13 +12,14 @@
* 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, spyOn, test } from 'bun:test';
+import { afterEach, describe, expect, spyOn } 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';
+import { isolatedTest } from './helpers/isolated-test.ts';
import { managedBrain } from './helpers/managed-brain.ts';
const PATHS = 8_000;
@@ -55,13 +56,13 @@ describe('GBRA-133 PR 2b: a first sync builds its batch in linear time', () => {
};
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 }) => {
+ isolatedTest(import.meta.path, `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 }) => {
+ isolatedTest(import.meta.path, `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>) => {
diff --git a/test/sync-pass-patched-domain-yield.test.ts b/test/sync-pass-patched-domain-yield.test.ts
index aaa21f4fa6..e846f72b80 100644
--- a/test/sync-pass-patched-domain-yield.test.ts
+++ b/test/sync-pass-patched-domain-yield.test.ts
@@ -8,19 +8,20 @@
* a confirm round patches all 4,000 pages (about 800 ms of keys). Without yields that is one stretch; with them, none
* passes the bound, and the patch equals the full build.
*/
-import { expect, test } from 'bun:test';
+import { expect } from 'bun:test';
import { domainCache, levelDomain, type DomainInput } from '../src/core/persistence/sync-pass-narrow.ts';
import { PageTable } from '../src/core/persistence/sync-pass.ts';
import type { GitTreeEntry } from '../src/core/persistence/sync-git-stream.ts';
import { loopYield } from '../src/core/persistence/sync-yield.ts';
import { spinCpuMs, watchLoopLag } from './helpers/cpu-time.ts';
+import { isolatedTest } from './helpers/isolated-test.ts';
const MAX_LAG_MS = 100;
const PAGES = 4_000;
/** Thread CPU clocks tick in about 4 ms steps, so the cost comes in 4 ms pieces. */
const KEY_CPU_MS = 4, KEY_COST_EVERY = 20;
-test('a confirm round that patches every page yields; no stretch passes the bound and the patch equals a full build', async () => {
+isolatedTest(import.meta.path, 'a confirm round that patches every page yields; no stretch passes the bound and the patch equals a full build', async () => {
const tree = new Map<string, GitTreeEntry>(), pages = new PageTable({ name: 'markdown', version: 1 } as never);
for (let i = 0; i < PAGES; i++) {
const path = `notes/n${i}.md`;
@@ -41,5 +42,6 @@ test('a confirm round that patches every page yields; no stretch passes the boun
finally { ({ maxLag } = lag.stop()); }
expect(patched!.touched!.size).toBe(PAGES);
expect({ domain: [...patched!.domain].sort(), byOrigin: [...patched!.byOrigin].sort() }).toEqual(expected);
+ console.error('ZZWORST isolated', Math.round(maxLag));
expect(Math.round(maxLag)).toBeLessThan(MAX_LAG_MS);
-});
+}, 60_000);
diff --git a/test/sync-probe-dirtiness-yield.test.ts b/test/sync-probe-dirtiness-yield.test.ts
index fad18b3373..8136c0b7df 100644
--- a/test/sync-probe-dirtiness-yield.test.ts
+++ b/test/sync-probe-dirtiness-yield.test.ts
@@ -7,7 +7,7 @@
* Forced probe (deterministic): every file read costs 4 ms of thread CPU (a seam on `readSyncFile`), 64 files. Asked
* per entry, the probe runs all 64 in one stretch (about 256 ms); asked per file, no stretch passes the bound.
*/
-import { afterEach, expect, spyOn, test } from 'bun:test';
+import { afterEach, expect, spyOn } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -15,6 +15,7 @@ import { join } from 'node:path';
import * as discovery from '../src/core/persistence/sync-discovery.ts';
import { probeDirtiness, readIndexLevel, readTreeLevel } from '../src/core/persistence/sync-git-stream.ts';
import { spinCpuMs, watchLoopLag } from './helpers/cpu-time.ts';
+import { isolatedTest } from './helpers/isolated-test.ts';
const MAX_LAG_MS = 100;
const FILES = 64;
@@ -23,7 +24,7 @@ const READ_CPU_MS = 4;
const spies: Array<{ mockRestore(): void }> = [];
afterEach(() => { for (const spy of spies.splice(0)) spy.mockRestore(); });
-test('the dirtiness probe yields between file reads; no stretch of reads passes the bound', async () => {
+isolatedTest(import.meta.path, 'the dirtiness probe yields between file reads; no stretch of reads passes the bound', async () => {
const root = mkdtempSync(join(tmpdir(), 'gbrain-probe-yield-'));
try {
const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
@@ -45,4 +46,4 @@ test('the dirtiness probe yields between file reads; no stretch of reads passes
expect([...probed!.values()].every(probe => probe.dp === 'clean')).toBe(true);
expect(Math.round(maxLag)).toBeLessThan(MAX_LAG_MS);
} finally { rmSync(root, { recursive: true, force: true }); }
-});
+}, 60_000);