Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(decide): hand buffered spend rows for another engine to their own engine
garrytanbdeae7832b65
diff --git a/src/core/ai/decide/store.ts b/src/core/ai/decide/store.tsindex a57c62a413..c08fe5a5ea 100644--- a/src/core/ai/decide/store.ts+++ b/src/core/ai/decide/store.ts@@ -105,12 +105,18 @@ class BufferedWriter<T extends object> {private engine: BrainEngine | null = null;private timer: ReturnType<typeof setInterval> | null = null;private inFlight: Promise<void> | null = null;+ /** Rows written to the engine they were buffered for when the next push names another brain. */+ private readonly handoffs = new Set<Promise<void>>();constructor(private readonly write: (engine: BrainEngine, rows: T[]) => Promise<void>) {}push(engine: BrainEngine, rows: readonly T[]): void {if (rows.length === 0) return;if (this.engine !== engine) {- if (this.engine && this.rows.length > 0) void this.flush().catch(() => {});+ if (this.engine && this.rows.length > 0 && engineKey(this.engine) !== engineKey(engine)) {+ const handoff: Promise<void> = this.write(this.engine, this.rows).catch(() => {}).finally(() => { this.handoffs.delete(handoff); });+ this.handoffs.add(handoff);+ this.rows = [];+ }this.engine = engine;}this.rows.push(...rows);@@ -133,7 +139,10 @@ class BufferedWriter<T extends object> {return this.inFlight;}- pending(): Promise<void> | null { return this.inFlight; }+ pending(): Promise<void> | null {+ const work = [...this.handoffs, ...(this.inFlight ? [this.inFlight] : [])];+ return work.length > 0 ? Promise.all(work).then(() => {}) : null;+ }hasBuffered(): boolean { return this.rows.length > 0; }reset(): void {if (this.timer) clearInterval(this.timer);@@ -141,6 +150,7 @@ class BufferedWriter<T extends object> {this.rows = [];this.engine = null;this.inFlight = null;+ this.handoffs.clear();}}@@ -162,7 +172,7 @@ export function recordSpend(engine: BrainEngine, row: SpendRow): void {/** Flush both buffers now (CLI commands that read what they just wrote, tests). */export async function flushDecideWrites(): Promise<void> {- await Promise.all([receipts.flush(), spend.flush()]);+ await Promise.all([receipts.flush(), spend.flush(), receipts.pending(), spend.pending()]);}export async function drainDecideWrites(timeoutMs: number, mode: BackgroundWorkDrainMode): Promise<{ unfinished: number }> {diff --git a/test/engine-open-lifecycle.test.ts b/test/engine-open-lifecycle.test.tsindex 2abc78a492..733fcecc43 100644--- a/test/engine-open-lifecycle.test.ts+++ b/test/engine-open-lifecycle.test.ts@@ -5,7 +5,7 @@*/import { afterEach, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';-import { dailySpend, __resetDecideStoreForTests } from '../src/core/ai/decide/store.ts';+import { dailySpend, flushDecideWrites, recordSpend, __resetDecideStoreForTests, type SpendRow } from '../src/core/ai/decide/store.ts';import { _resetFeedbackRecordingForTests, drainFeedbackQueue, recordAnswer } from '../src/core/feedback/record.ts';import { _resetFeedbackSettingsCacheForTests } from '../src/core/feedback/settings.ts';import { hostIdentityMismatches } from '../src/core/persistence/consumer-diagnostics.ts';@@ -35,6 +35,28 @@ describe('decide spend cache', () => {expect(await dailySpend(transactionOn(engine), now)).toEqual({ total: 2, remote: 1 });expect(reads).toBe(1);});++ test('spend rows buffered for one brain are written to that brain when the next row names another, even during a flush', async () => {+ const written = new Map<string, string[]>();+ const brain = (name: string, delayMs: number) => ({+ executeRaw: async (_sql: string, params: string[][]) => {+ await Bun.sleep(delayMs);+ written.set(name, [...(written.get(name) ?? []), ...params[0]!]);+ return [];+ },+ }) as unknown as BrainEngine;+ const a = brain('a', 200);+ const b = brain('b', 0);+ const row = (request_id: string): SpendRow => ({ request_id, slot: 'rerank', provider: 'p', model_resolved: 'm', lane: 'hot', remote: false, input_tokens: 1, cost_usd: 0.01, outcome: 'ok' });+ recordSpend(a, row('a-1'));+ const inFlight = flushDecideWrites();+ recordSpend(a, row('a-2'));+ recordSpend(b, row('b-1'));+ await inFlight;+ await flushDecideWrites();+ expect(written.get('a')?.sort()).toEqual(['a-1', 'a-2']);+ expect(written.get('b')).toEqual(['b-1']);+ });});describe('feedback queue', () => {