Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(test): two wave-15 flakes quiesce by contract instead of racing a wall clock

garrytan8f0818952c5c
diff --git a/src/core/context/openclaw-core.ts b/src/core/context/openclaw-core.ts
index 5a7d81c2be..175a20c329 100644
--- a/src/core/context/openclaw-core.ts
+++ b/src/core/context/openclaw-core.ts
@@ -71,7 +71,20 @@ export interface OpenClawCoreLane {
compacted(sessionId: string | null): void;
}
-export function createOpenClawCoreLane(opts: { workspaceDir?: string; timeoutMs: number; fetcher?: CoreFetcher }): OpenClawCoreLane {
+export interface OpenClawCoreLaneOptions {
+ workspaceDir?: string;
+ timeoutMs: number;
+ fetcher?: CoreFetcher;
+ /** Scheduler seam: run `fn` once after `ms`. Default: a real timer that does not hold the process open. Tests fire the deadline by hand instead of racing a wall clock. */
+ later?(ms: number, fn: () => void): void;
+}
+
+function realLater(ms: number, fn: () => void): void {
+ const t = setTimeout(fn, ms);
+ (t as { unref?: () => void }).unref?.();
+}
+
+export function createOpenClawCoreLane(opts: OpenClawCoreLaneOptions): OpenClawCoreLane {
let memo: { at: number; identity: string; value: CoreFetch } | null = null;
const warned = new Set<string>();
const lastTokens = new Map<string, number>();
@@ -108,10 +121,7 @@ export function createOpenClawCoreLane(opts: { workspaceDir?: string; timeoutMs:
return null;
}
})();
- return Promise.race([work, new Promise<null>((resolve) => {
- const t = setTimeout(() => resolve(null), opts.timeoutMs);
- (t as { unref?: () => void }).unref?.();
- })]);
+ return Promise.race([work, new Promise<null>((resolve) => (opts.later ?? realLater)(opts.timeoutMs, () => resolve(null)))]);
}
async function getCore(sessionId: string | null): Promise<CoreFetch> {
diff --git a/test/activation-unbound-rooted-6449.test.ts b/test/activation-unbound-rooted-6449.test.ts
index c869d06741..1d6f050b82 100644
--- a/test/activation-unbound-rooted-6449.test.ts
+++ b/test/activation-unbound-rooted-6449.test.ts
@@ -25,6 +25,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import type { OperationContext } from '../src/core/operations.ts';
+import { testWaitMs } from './helpers/wait-for.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { activatePersistence } from '../src/core/persistence/activation.ts';
import { writerOnboardingPreflight } from '../src/core/persistence/onboarding.ts';
@@ -59,6 +60,17 @@ afterAll(async () => {
await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });
});
+async function settledEffects(engine: BrainEngine): Promise<void> {
+ const deadline = Date.now() + testWaitMs(30_000);
+ while (true) {
+ const open = await engine.executeRaw<{ id: string; kind: string; state: string }>(
+ "SELECT id::text AS id, kind, state FROM persistence_effects WHERE state<>'committed' OR recovery IS NOT NULL ORDER BY id");
+ if (!open.length) return;
+ if (Date.now() > deadline) throw new Error(`effects did not settle: ${JSON.stringify(open)}`);
+ await new Promise(resolve => setTimeout(resolve, 50));
+ }
+}
+
type Outcome = { state: string; code?: string; detail?: string; suggestion?: string; write_through?: { skipped?: string } };
const outcome = (promise: Promise<unknown>): Promise<Outcome> => promise.then(
receipt => receipt as Outcome,
@@ -135,8 +147,10 @@ async function databaseOnlyActivation(engine: BrainEngine): Promise<void> {
expect(existsSync(root)).toBe(true);
// Deactivation clears the list; back in classic mode the ordinary PGLite first-write claim applies again.
+ // The brain must quiesce first: the committed writes' embedding effects drain asynchronously, and a running
+ // effect blocks deactivation (deleting queued rows raced the consumer picking one up).
await engine.setConfig('sync.write_through', 'false');
- await engine.executeRaw("DELETE FROM persistence_effects WHERE state='queued'");
+ await settledEffects(engine);
expect(await deactivatePersistence(engine, { requestId: randomUUID() })).toMatchObject({ mode: 'classic', deactivated: true });
expect(await engine.getConfig(DATABASE_ONLY_SOURCES_KEY)).toBeNull();
});
diff --git a/test/trust-cache-invalidation.test.ts b/test/trust-cache-invalidation.test.ts
index b81330558e..2877f37be4 100644
--- a/test/trust-cache-invalidation.test.ts
+++ b/test/trust-cache-invalidation.test.ts
@@ -244,17 +244,22 @@ for (const backendName of testBackends()) {
const engine = engineOf();
const marker = `cnrycore${randomUUID().slice(0, 8)}`;
await corePage(engine, marker);
+ // The deadline is fired by hand: a real 50 ms budget raced against a real
+ // Postgres refresh lost on a loaded shard and failed the first call.
const slow = { now: false };
+ const deadlines: number[] = [];
const l = createOpenClawCoreLane({
timeoutMs: 50,
- fetcher: async (_s, memo) => {
- if (slow.now) await new Promise(r => setTimeout(r, 200));
- return refreshCoreFromEngine(engine, 'default', memo);
+ later: (ms, fire) => {
+ deadlines.push(ms);
+ if (slow.now) fire();
},
+ fetcher: (_s, memo) => slow.now ? new Promise<never>(() => {}) : refreshCoreFromEngine(engine, 'default', memo),
});
expect((await l.additions({ sessionId: 's', messages: [] })).join('\n')).toContain(marker);
slow.now = true;
expect((await l.additions({ sessionId: 's', messages: [] })).join('\n')).not.toContain(marker);
+ expect(deadlines).toEqual([50, 50]);
});
test('the serve coreOnly arm answers unchanged for a matching identity and a fresh block after a transition', async () => {