Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): a disconnect suspends the telemetry writer instead of retiring it
garrytanca13803073cf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 40120568e1..9b2f7c92fa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,12 +12,12 @@ identifiers and attribution are available in the pre-removal Git revision## [0.60.556.0] - 2026-11-02-**Mounted brains stop sharing settings and search telemetry.** In a process that serves several brains, search telemetry for every brain was written into the first brain's database, and a handful of per-brain settings were read once from whichever brain asked first and then applied to all of them. Each of those caches now belongs to its engine, and each engine gets its own telemetry writer, which retires when the engine disconnects. A process with one brain behaves exactly as before. Contributed by @bradgessler (#8454).+**Mounted brains stop sharing settings and search telemetry.** In a process that serves several brains, search telemetry for every brain was written into the first brain's database, and a handful of per-brain settings were read once from whichever brain asked first and then applied to all of them. Each of those caches now belongs to its engine, and each engine gets its own telemetry writer, which stops its timer when the engine disconnects and keeps its buffer for a reconnect. A process with one brain behaves exactly as before. Contributed by @bradgessler (#8454).### Itemized changes- `src/core/engine-key.ts`: `engineKey(engine)` resolves a page-transaction clone, a read-through view and a statement-deadline wrapper to the engine behind them. Every cache below keys on it.-- `src/core/search/telemetry.ts`: one writer per engine (`getTelemetryWriter(engine)`), held weakly, flushing only into its own engine. The disconnect drain bounds every live writer, and a writer retires on its engine's disconnect or collection. `setEngine` is gone.+- `src/core/search/telemetry.ts`: one writer per engine (`getTelemetryWriter(engine)`), held weakly, flushing only into its own engine. The disconnect drain bounds every live writer. A disconnect suspends the writer (no timer, buffer kept), so a PGLite reconnect, which is a disconnect and a connect, still flushes what was buffered; a collected engine retires its writer. `setEngine` is gone.- Keyed by engine: `search.track_retrieval` (`last-retrieved.ts`), `persistence.publication_ceiling_ms` and the idle bound derived from it (`publication-deadline.ts`), the minion admission policy (`admission.ts`), the `mcp.strict_params` last-known-good fallback (`validate-params.ts`), the `write_capacity_low` throttle (`capacity-snapshot.ts`), and `search.hnsw_iterative_scan` / `search.vector_legacy_guard`, which are still latched once and now latched per engine.- `test/engine-keyed-caches.test.ts`: two engines per setting, the second read after the first warmed the cache. All six behavior cases fail on master.diff --git a/src/core/search/telemetry.ts b/src/core/search/telemetry.tsindex 757f214623..b4fa1af1cc 100644--- a/src/core/search/telemetry.ts+++ b/src/core/search/telemetry.ts@@ -301,6 +301,19 @@ class TelemetryWriter {return this.flushInFlight;}+ /** Stops the timer and keeps the buffer, for an engine that disconnected and may reconnect (PGLite's reconnect). */+ suspend(): void {+ if (this.timer) {+ clearInterval(this.timer);+ this.timer = null;+ }+ }++ /** Restarts the timer of a suspended writer. */+ resume(): void {+ this.ensureTimer();+ }+/*** Stop the timer and drop the buffer. Called by `_resetTelemetryWriterForTest`* and for a writer whose engine was garbage collected. Nothing in production@@ -382,9 +395,10 @@ class TelemetryWriter {}/**- * One writer per engine (a transaction or view shares its engine's); `live` lets the drain reach each one. A writer is- * retired when its engine disconnects (after its in-flight flush; residual buckets drop there, as the disconnect drain- * already drops them) or is garbage collected, so an engine opened and closed per request leaves no timer behind.+ * One writer per engine (a transaction or view shares its engine's); `live` lets the drain reach each one. When its+ * engine disconnects, a writer is suspended after its in-flight flush: its timer stops and it leaves `live`, but it keeps+ * its buffer and its place in `writers`, so a reconnect (PGLite's is disconnect then connect) resumes it on the next+ * search and an engine opened and closed per request leaves no timer behind. A garbage-collected engine retires its writer.*/let writers = new WeakMap<object, TelemetryWriter>();const live = new Set<TelemetryWriter>();@@ -394,16 +408,19 @@ const unregisters = new WeakMap<object, () => void>();export function getTelemetryWriter(engine: BrainEngine): TelemetryWriter {const key = engineKey(engine) as BrainEngine;let writer = writers.get(key);+ if (writer && !live.has(writer)) {+ writer.resume();+ live.add(writer);+ }if (!writer) {const created = new TelemetryWriter(key);writer = created;writers.set(key, created);// Never awaits: the bounded disconnect drain (awaitPendingTelemetryFlush) still sees the in-flight flush.const unregister = key.registerBeforeDisconnect?.(async () => {- if (writers.get(key) === created) writers.delete(key);const inFlight = created.pendingFlush();- if (inFlight) void inFlight.catch(() => undefined).finally(() => retireWriter(created));- else retireWriter(created);+ if (inFlight) void inFlight.catch(() => undefined).finally(() => suspendWriter(created));+ else suspendWriter(created);});if (unregister) unregisters.set(key, unregister);live.add(created);@@ -416,6 +433,11 @@ export function _telemetryWriterCountForTest(): number {return live.size;}+function suspendWriter(writer: TelemetryWriter): void {+ writer.suspend();+ live.delete(writer);+}+function retireWriter(writer: TelemetryWriter): void {writer.stop();const engine = writer.liveEngine();diff --git a/test/engine-keyed-caches.test.ts b/test/engine-keyed-caches.test.tsindex d509d7a97b..26ab2457bb 100644--- a/test/engine-keyed-caches.test.ts+++ b/test/engine-keyed-caches.test.ts@@ -5,6 +5,9 @@* after the first one warmed the cache, the order that leaked on master.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+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 type { BrainEngine } from '../src/core/engine.ts';import type { HybridSearchMeta } from '../src/core/types.ts';@@ -125,18 +128,34 @@ describe('search telemetry flushes into the searching brain', () => {expect(_telemetryWriterCountForTest()).toBe(1);});- test('an engine\'s disconnect retires its writer, so engines opened and closed per request leave none behind', async () => {+ test('an engine\'s disconnect suspends its writer, so engines opened and closed per request leave no timer behind', async () => {const closers: Array<() => Promise<void>> = [];for (let i = 0; i < 20; i++) {const hooks = new Set<() => Promise<void>>();const engine = { ...configEngine({}), registerBeforeDisconnect(stop: () => Promise<void>) { hooks.add(stop); return () => { hooks.delete(stop); }; } } as unknown as BrainEngine;recordSearchTelemetry(engine, meta, { results_count: 1 });- closers.push(async () => { for (const stop of [...hooks]) await stop(); expect(hooks.size).toBe(0); });+ closers.push(async () => { for (const stop of [...hooks]) await stop(); });}expect(_telemetryWriterCountForTest()).toBe(20);for (const close of closers) await close();expect(_telemetryWriterCountForTest()).toBe(0);});+ test('a PGLite reconnect keeps the buffered telemetry, which then flushes into the reconnected brain', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gb-telemetry-reconnect-'));+ const engine = new PGLiteEngine();+ try {+ await engine.connect({ database_path: join(dir, 'brain.pglite') });+ await engine.initSchema();+ recordSearchTelemetry(engine, meta, { results_count: 1 });+ await engine.reconnect();+ recordSearchTelemetry(engine, meta, { results_count: 1 });+ await awaitPendingTelemetryFlush(5000, 'exit');+ expect((await engine.executeRaw<{ n: number }>('SELECT COALESCE(SUM(count),0)::int AS n FROM search_telemetry'))[0]!.n).toBe(2);+ } finally {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+ }+ });});describe('per-brain settings are read per engine', () => {