Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(D4): embedding-claim renewal interval seam; lease tests run in renewal intervals
garrytan688511904240
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex 4669544033..8694fd23b0 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -114,6 +114,17 @@ async function materializeAndAdvance(engine: BrainEngine, effect: PersistenceEff/** At most this many skipped scan targets are recorded on one effect. */const SKIPPED_TARGET_LIMIT = 100;+/** An embedding claim renews this often while the provider works; the claim lease is 2 minutes. */+export const EFFECT_RENEWAL_INTERVAL_MS = 10_000;+let effectRenewalIntervalMs = EFFECT_RENEWAL_INTERVAL_MS;+/** Test seam: replace the embedding-claim renewal interval (null restores it); returns the restore function. */+export function __setEffectRenewalIntervalForTests(ms: number | null): () => void {+ const previous = effectRenewalIntervalMs;+ effectRenewalIntervalMs = ms ?? EFFECT_RENEWAL_INTERVAL_MS;+ return () => { effectRenewalIntervalMs = previous; };+}+/** The renewal interval in effect (production: EFFECT_RENEWAL_INTERVAL_MS). */+export function effectRenewalInterval(): number { return effectRenewalIntervalMs; }async function recordSkippedTarget(engine: BrainEngine, effect: PersistenceEffect, target: SkippedTarget): Promise<void> {await engine.executeRaw(`UPDATE persistence_effects SET data=jsonb_set(data,'{skipped}',COALESCE(data->'skipped','[]'::jsonb)||$3::text::jsonb)@@ -290,7 +301,7 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers}).catch(error => { lease.abort(embeddingStorageFailure(error)); });const interval = setInterval(() => {if (!renewing && !signal.aborted) renewing = renew().finally(() => { renewing = undefined; });- }, 10_000);+ }, effectRenewalIntervalMs);interval.unref?.();let vectors: (Float32Array | null)[];// #4616: a degenerate vector refuses only its own chunk; the usable vectors still install.diff --git a/test/persistence-embedding-effects.test.ts b/test/persistence-embedding-effects.test.tsindex 8d0a2e3c62..21b2c2d905 100644--- a/test/persistence-embedding-effects.test.ts+++ b/test/persistence-embedding-effects.test.ts@@ -1,4 +1,4 @@-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+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';@@ -7,7 +7,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { PostgresEngine } from '../src/core/postgres-engine.ts';import type { OperationContext } from '../src/core/ops/contract.ts';-import { runPersistenceEffects, type EffectWorkerOptions } from '../src/core/persistence/effects.ts';+import { EFFECT_RENEWAL_INTERVAL_MS, __setEffectRenewalIntervalForTests, effectRenewalInterval, runPersistenceEffects, type EffectWorkerOptions } from '../src/core/persistence/effects.ts';import { claimPersistenceEffect, publicEffectsForRequest } from '../src/core/persistence/effect-journal.ts';import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';import { submissionAuthority } from '../src/core/persistence/authority.ts';@@ -20,8 +20,19 @@ import { invokeAI, isAIInvocationPolicyError, withAIInvocationGuard } from '../simport { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';+import { testWaitMs } from './helpers/wait-for.ts';const databaseUrl = process.env.DATABASE_URL;+/**+ * Claim renewal runs at this interval instead of the production 10 s. Every+ * renewal-timing case below is expressed in renewal intervals, including the+ * fixture lease (1.5 intervals, as 15 s is to 10 s), so the takeover attempts+ * still land after the unrenewed lease would have expired.+ */+const renewalMs = testWaitMs(1_500);+let restoreRenewal: () => void = () => {};+beforeEach(() => { restoreRenewal = __setEffectRenewalIntervalForTests(renewalMs); });+afterEach(() => { restoreRenewal(); expect(effectRenewalInterval()).toBe(EFFECT_RENEWAL_INTERVAL_MS); });for (const kind of testBackends()) {describe(`embedding effects ${kind}`, () => {let engine: BrainEngine;@@ -315,7 +326,7 @@ for (const kind of testBackends()) {} } });expect(reason).toMatchObject({ code: 'write_claim_lost' });const stoppedAt = renewals;- await Bun.sleep(11_000);+ await Bun.sleep(renewalMs * 1.1);expect(renewals).toBe(stoppedAt);expect((await engine.executeRaw('SELECT state,execution_token FROM persistence_effects WHERE id=$1', [f.effectId]))[0]).toMatchObject({ state: 'running', execution_token: successor });@@ -469,7 +480,7 @@ for (const kind of testBackends()) {await engine.executeRaw(`CREATE FUNCTION shorten_embedding_claim() RETURNS trigger LANGUAGE plpgsql AS $$BEGINIF NEW.kind='embedding' AND NEW.state='running' AND NEW.claim_expires_at IS DISTINCT FROM OLD.claim_expires_at THEN- NEW.claim_expires_at=clock_timestamp()+interval '15 seconds';+ NEW.claim_expires_at=clock_timestamp()+interval '${renewalMs * 1.5} milliseconds';END IF;RETURN NEW;END $$`);@@ -479,16 +490,16 @@ for (const kind of testBackends()) {const started = Promise.withResolvers<void>();const options = { hostId: localHostId(), limit: 1, embedding: { signature, model, embed: async () => {calls++; started.resolve();- for (let n = 0; n < 3; n++) { await Bun.sleep(11_000); batches++; }+ for (let n = 0; n < 3; n++) { await Bun.sleep(renewalMs * 1.1); batches++; }return vectors();} } };const worker = runPersistenceEffects(engine, { engine: engine.kind }, options);try {await started.promise;- await Bun.sleep(17_000);+ await Bun.sleep(renewalMs * 1.7);await runPersistenceEffects(competitor, { engine: competitor.kind }, { ...options,embedding: { signature, model, embed: async () => { calls++; return vectors(); } } });- await Bun.sleep(11_000);+ await Bun.sleep(renewalMs * 1.1);await runPersistenceEffects(competitor, { engine: competitor.kind }, { ...options,embedding: { signature, model, embed: async () => { calls++; return vectors(); } } });await worker;@@ -527,7 +538,7 @@ for (const kind of testBackends()) {}const stoppedAt = renewals;expect(stoppedAt).toBe(4);- await Bun.sleep(11_000);+ await Bun.sleep(renewalMs * 1.1);expect(renewals).toBe(stoppedAt);});diff --git a/test/persistence-test-seams.test.ts b/test/persistence-test-seams.test.tsnew file mode 100644index 0000000000..6180df2c55--- /dev/null+++ b/test/persistence-test-seams.test.ts@@ -0,0 +1,63 @@+/**+ * Persistence test seams restore production defaults.+ *+ * Protects: every timing seam the test corpus shortens (maintenance publish+ * wait, embedding-claim renewal interval, connector wait budget) returns to+ * its production value after a test restores it, so a shortened budget never+ * leaks into a later file that shares the shard process.+ * Fails when: a setter stops returning a working restore function, a restore+ * resets to a stale value instead of the previous one, or a production+ * default changes without its tests noticing.+ * Why new: the seams were bare setters with `null` resets; nothing checked+ * the restored value.+ * Seam: the seams under test.+ */+import { afterAll, expect, test } from 'bun:test';+import { MAINTENANCE_PUBLISH_WAIT_MS, MAINTENANCE_WRITE_WAIT_MS, MaintenanceWriteWait, __setMaintenanceWriteWaitForTests, maintenancePublishWaitMs } from '../src/core/persistence/maintenance-wait.ts';+import { EFFECT_RENEWAL_INTERVAL_MS, __setEffectRenewalIntervalForTests, effectRenewalInterval } from '../src/core/persistence/effects.ts';+import { CONNECTOR_WAIT_BUDGET_MS, connectorWaitBudget } from '../src/core/persistence/connector-sync.ts';+import { createConnectorFixture } from './helpers/connector-fixture.ts';++function expectProductionDefaults(): void {+ expect(maintenancePublishWaitMs()).toBe(MAINTENANCE_PUBLISH_WAIT_MS);+ expect(new MaintenanceWriteWait().ms()).toBe(MAINTENANCE_WRITE_WAIT_MS);+ expect(effectRenewalInterval()).toBe(EFFECT_RENEWAL_INTERVAL_MS);+ expect(connectorWaitBudget.ms).toBe(CONNECTOR_WAIT_BUDGET_MS);+}++afterAll(expectProductionDefaults);++test('production defaults are the documented values', () => {+ expect([MAINTENANCE_PUBLISH_WAIT_MS, MAINTENANCE_WRITE_WAIT_MS, EFFECT_RENEWAL_INTERVAL_MS, CONNECTOR_WAIT_BUDGET_MS])+ .toEqual([5_000, 30_000, 10_000, 30_000]);+ expectProductionDefaults();+});++test('the maintenance wait seam scales both waits and nested restores unwind in order', () => {+ const outer = __setMaintenanceWriteWaitForTests(500);+ const inner = __setMaintenanceWriteWaitForTests(250);+ expect(maintenancePublishWaitMs()).toBe(250);+ expect(new MaintenanceWriteWait().ms()).toBe(250);+ inner();+ expect(maintenancePublishWaitMs()).toBe(500);+ outer();+ expectProductionDefaults();+});++test('the effect renewal seam restores the previous interval', () => {+ const outer = __setEffectRenewalIntervalForTests(1_500);+ const inner = __setEffectRenewalIntervalForTests(null);+ expect(effectRenewalInterval()).toBe(EFFECT_RENEWAL_INTERVAL_MS);+ inner();+ expect(effectRenewalInterval()).toBe(1_500);+ outer();+ expectProductionDefaults();+});++test('the connector fixture restores the production wait budget on teardown', async () => {+ const fixture = createConnectorFixture();+ await fixture.setup();+ try { expect(connectorWaitBudget.ms).toBeLessThan(CONNECTOR_WAIT_BUDGET_MS); }+ finally { await fixture.teardown(); }+ expectProductionDefaults();+}, 120_000);