Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(eval): W3 gate-4 paired latency runner (scripts/bench-rerank-gate-latency.ts) — recall + query per arm with an in-memory gate overlay, warm-up, counterbalanced order, bounded workers; mean saving per skip and p95 verdict
garrytan795ada95ce15
diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.mdindex 041e1bebb8..4f10245d50 100644--- a/docs/architecture/key-files/evaluation.md+++ b/docs/architecture/key-files/evaluation.md@@ -62,4 +62,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/eval/longmemeval/synopsis-tier.ts` — makes `--mode tokenmax` measure the production per-chunk synopsis tier: when the resolved tier is `per_chunk_synopsis`, every imported session is re-embedded through `reembedPageWithContextualRetrieval` with the backfill's synopsis model (`resolveContextualSynopsisModel`), behind a JSONL cache keyed by `buildSynopsisCacheKey` (only answers the model returned are cached) and a `--synopsis-max-usd` cap metered from provider usage (default 20; the run stops after the question that reached it and exits 1). Transient service errors retry with backoff. Row field `contextual_synopsis`; pins in `run_config.contextual_synopsis` and `retrieval_config_hash`. Test: `test/eval-longmemeval-synopsis-tier.serial.test.ts`.- `src/eval/longmemeval/locomo.ts` + `scripts/locomo-to-longmemeval.ts` — LoCoMo `locomo10.json` → LongMemEval-format questions for an explicit conversation list: one question per QA except category 5, the conversation's sessions as the haystack (stable ids `conv-N_sK`, LongMemEval-format dates, the last session's date as the question date), gold sessions from evidence dialog ids, speaker names as turn roles. Sealed conversations (`LOCOMO_SEALED_CONVERSATIONS`) convert only with `custodian`. Test: `test/longmemeval-locomo.test.ts`.-+- `src/eval/rerank-gate-latency.ts` + `scripts/bench-rerank-gate-latency.ts` — the W3 gate-4 paired latency runner (A66/A67) for `search.reranker.gate`. Each item (JSONL: `id`, optional `kind`, `recall` and `query` params passed verbatim) runs the `recall` then `query` operations in-process as a trusted local caller, once with the gate `off` and once `on`; the arms differ only in `withSearchConfig`, an in-memory overlay of `getConfig`/`getAllConfig` that writes nothing. Controls: an untimed warm-up of both arms, `pairedSchedule` (first arm alternates by item and by repeat), a fixed worker count with each worker running one pair's arms back to back, and timing that starts once a worker holds its slot. `summarizeLatency` reports per-arm mean/p50/p95, the skip rate, the mean paired saving per skipped query and on reranked queries, the p95 increase, the reranker-call reduction (calls under `off` = the `on` arm's eligible searches; under `on` = `provider_called`) and a per-kind split; `verdict.latency_pass` is a mean saving of at least 100 ms per skip, no p95 increase and no errored arm. Exit 0 pass / 1 fail / 2 usage. Tests: `test/eval/rerank-gate-latency.test.ts` (pure parts, overlay), `test/eval/rerank-gate-latency-ops.serial.test.ts` (real `query` op on PGLite, a 150 ms provider delay behind the rerank transport seam).diff --git a/scripts/bench-rerank-gate-latency.ts b/scripts/bench-rerank-gate-latency.tsnew file mode 100644index 0000000000..fc42cf9f36--- /dev/null+++ b/scripts/bench-rerank-gate-latency.ts@@ -0,0 +1,100 @@+#!/usr/bin/env bun+/**+ * W3 gate 4 latency (A66/A67): paired `search.reranker.gate` off vs on over+ * the whole recall-plus-query path, on the configured brain.+ *+ * bun scripts/bench-rerank-gate-latency.ts --items <items.jsonl>+ * [--warmup 5] [--repeats 1] [--concurrency 1] [--source <id>]+ * [--database-url <url>] [--samples-out <file.ndjson>] [--json]+ *+ * Each line of the items file is one question:+ * {"id": "q1", "kind": "temporal", "recall": {...}, "query": {"query": "...", "token_budget": 6300}}+ * `recall` (optional) and `query` are passed verbatim to those operations as+ * a trusted local caller. The arms differ only in an in-memory overlay of+ * `search.reranker.gate` (nothing is written to the brain's config); like any+ * search, each call records search telemetry. Controls, timing and the+ * verdict: src/eval/rerank-gate-latency.ts. Exit 0 when the latency clause+ * passes, 1 when it fails or an arm errored, 2 on a usage error.+ */+import { readFileSync, writeFileSync } from 'node:fs';+import { buildGatewayConfig } from '../src/core/ai/build-gateway-config.ts';+import { configureGateway } from '../src/core/ai/gateway.ts';+import { loadConfig, loadConfigWithEngine, toEngineConfig } from '../src/core/config.ts';+import { createEngine } from '../src/core/engine-factory.ts';+import type { OperationContext } from '../src/core/operations.ts';+import type { EngineConfig } from '../src/core/types.ts';+import { type LatencyItem, type LatencyReport, operationArmCaller, runPaired, summarizeLatency } from '../src/eval/rerank-gate-latency.ts';++function flag(args: string[], name: string): string | undefined {+ const at = args.indexOf(name);+ return at >= 0 ? args[at + 1] : undefined;+}++export function parseItems(text: string): LatencyItem[] {+ return text.split('\n').filter((l) => l.trim()).map((line, i) => {+ const row = JSON.parse(line) as Partial<LatencyItem>;+ if (typeof row.id !== 'string' || !row.query || typeof row.query !== 'object') {+ throw new Error(`items line ${i + 1}: needs a string "id" and a "query" params object`);+ }+ return row as LatencyItem;+ });+}++export function renderReport(r: LatencyReport): string {+ const v = (ok: boolean) => (ok ? 'pass' : 'FAIL');+ return [+ `pairs: ${r.pairs} (errors: ${r.errors})`,+ `off: mean ${r.arms.off.mean_ms} ms, p50 ${r.arms.off.p50_ms}, p95 ${r.arms.off.p95_ms}`,+ `on: mean ${r.arms.on.mean_ms} ms, p50 ${r.arms.on.p50_ms}, p95 ${r.arms.on.p95_ms}`,+ `skipped: ${r.skipped_pairs} (${(r.skip_rate * 100).toFixed(1)}%)`,+ `mean saving per skipped query: ${r.mean_saving_per_skip_ms ?? 'n/a'} ms (>= 100: ${v(r.verdict.mean_saving_ok)})`,+ `mean saving on reranked queries: ${r.mean_saving_no_skip_ms ?? 'n/a'} ms`,+ `p95 increase: ${r.p95_increase_ms} ms (<= 0: ${v(r.verdict.p95_ok)})`,+ `reranker calls: ${r.reranker_calls.off} -> ${r.reranker_calls.on} (${(r.reranker_calls.reduction * 100).toFixed(1)}% fewer; >= 25%: ${v(r.verdict.reranker_call_reduction_ok)})`,+ `latency clause: ${v(r.verdict.latency_pass)}`,+ ].join('\n');+}++async function main(): Promise<number> {+ const args = process.argv.slice(2);+ const itemsPath = flag(args, '--items');+ if (!itemsPath) { console.error('usage: bun scripts/bench-rerank-gate-latency.ts --items <items.jsonl> [--warmup 5] [--repeats 1] [--concurrency 1] [--source <id>] [--database-url <url>] [--samples-out <file>] [--json]'); return 2; }+ const numeric = (name: string, fallback: number) => {+ const n = Number(flag(args, name) ?? fallback);+ if (!Number.isInteger(n) || n < 0) throw new Error(`${name} takes a non-negative integer`);+ return n;+ };+ const items = parseItems(readFileSync(itemsPath, 'utf8'));+ const url = flag(args, '--database-url');+ const fileConfig = loadConfig();+ let engineConfig: EngineConfig;+ if (url) engineConfig = { engine: 'postgres', database_url: url };+ else if (fileConfig) engineConfig = toEngineConfig(fileConfig);+ else { console.error('No GBrain config found. Pass --database-url, or set GBRAIN_HOME to the brain under test.'); return 1; }+ const engine = await createEngine(engineConfig);+ try {+ await engine.connect(engineConfig);+ const merged = (await loadConfigWithEngine(engine, fileConfig ?? { engine: 'postgres' })) ?? fileConfig ?? { engine: 'postgres' as const };+ configureGateway(buildGatewayConfig(merged));+ const ctx = {+ engine,+ config: merged,+ logger: { info() {}, warn() {}, error() {}, debug() {} },+ dryRun: false,+ remote: false,+ sourceId: flag(args, '--source') ?? 'default',+ } as unknown as OperationContext;+ const samples = await runPaired(items, operationArmCaller(ctx), {+ warmup: numeric('--warmup', 5), repeats: Math.max(1, numeric('--repeats', 1)), concurrency: Math.max(1, numeric('--concurrency', 1)),+ });+ const samplesOut = flag(args, '--samples-out');+ if (samplesOut) writeFileSync(samplesOut, samples.map((s) => JSON.stringify(s)).join('\n') + '\n');+ const report = summarizeLatency(samples);+ console.log(args.includes('--json') ? JSON.stringify(report, null, 2) : renderReport(report));+ return report.verdict.latency_pass ? 0 : 1;+ } finally {+ await engine.disconnect().catch(() => {});+ }+}++if (import.meta.main) process.exit(await main());diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 223dc235ce..784f997f12 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -162,6 +162,7 @@ test/eval-longmemeval-synopsis-tier.serial.test.ts R1 R1: mutates process.env (Gtest/eval-retrieval-quality-decide.serial.test.ts R1 R1: mutates process.env (GBRAIN_DECIDE_SLOTS)test/eval-run-all-outcome.serial.test.ts R2 R2: mock.module(../src/commands/eval-brainbench.ts) replaces modules for every file in the process; spyOn process.stderr.writetest/eval-takes-quality-runner.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process+test/eval/rerank-gate-latency-ops.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)test/extract-conversation-facts-diagnostics.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests, __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; spyOn console.log, process.exit, concurrency.resolveWorkersWithClamp, console.error (+2 more)test/extract-cross-source-links-db.serial.test.ts R1 R1: mutates process.env (bracket or computed key)test/extract-endpoint-revision.serial.test.ts global-state global-state: spyOn console.error, process.exit@@ -185,6 +186,7 @@ test/fts-language-migration.serial.test.ts R1 R1: mutates process.env (bracket otest/fts-language-schema-replay.serial.test.ts R1 R1: mutates process.env (GBRAIN_PGLITE_SNAPSHOT)test/fts-language.serial.test.ts R1 R1: mutates process.env (bracket or computed key)test/gateway-reconfigure-clobber.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)+test/git-listing-memo.serial.test.ts R1 R1: puts a git-counting shim on process.env.PATH for every spawn in the process (git child processes inherit it, so withEnv cannot scope it)test/git-remote-durable.serial.test.ts R1 R1: mutates process.env (GBRAIN_GIT_ALLOW_FILE_TRANSPORT)test/git-remote-pull-file-transport.serial.test.ts R1 R1: mutates process.env (GBRAIN_GIT_ALLOW_FILE_TRANSPORT)test/google-connect-cmd.serial.test.ts global-state global-state: spyOn console.error; patches process stdout/stderr/console@@ -377,4 +379,3 @@ test/write-path-no-egress.serial.test.ts global-state global-state: binds a locatest/write-path-zero-llm.serial.test.ts R1 R1: mutates process.env (ANTHROPIC_API_KEY, OPENAI_API_KEY) so gated chat and embedding paths are livetest/writeback-nudge.serial.test.ts global-state global-state: patches process stdout/stderr/consoletest/writeback-review-fixes.serial.test.ts global-state global-state: process-wide test seams __resetCheckpointHarvestForTests; patches process stdout/stderr/console-test/git-listing-memo.serial.test.ts R1 R1: puts a git-counting shim on process.env.PATH for every spawn in the process (git child processes inherit it, so withEnv cannot scope it)diff --git a/src/eval/rerank-gate-latency.ts b/src/eval/rerank-gate-latency.tsnew file mode 100644index 0000000000..b14e44ad6e--- /dev/null+++ b/src/eval/rerank-gate-latency.ts@@ -0,0 +1,240 @@+/**+ * W3 gate 4 (A66/A67): the paired latency runner for `search.reranker.gate`.+ *+ * Every item runs the whole read path (the `recall` op, then the `query` op,+ * in-process as a trusted local caller) once with the gate `off` and once+ * with it `on`, against the same brain. The arms differ only in an in-memory+ * config overlay (`withSearchConfig`), so nothing is written to the brain and+ * both arms can run side by side.+ *+ * Controls: a warm-up pass (both arms, untimed) before any timed call;+ * counterbalanced arm order (`pairedSchedule`: the first arm alternates by+ * item and by repeat); a fixed number of workers, each running one pair's two+ * arms back to back; and timing that starts after a worker holds its slot,+ * so queueing never counts. `retrieve_ms` from the harness is not used.+ *+ * Verdict (`summarizeLatency`, A67): a mean saving of at least 100 ms per+ * skipped query (paired off − on over the pairs whose `on` arm skipped) and+ * no p95 increase over all queries. The reranker-call reduction (gate 4's+ * 25% clause) is derived from the `on` arm's own meta: every eligible search+ * calls the reranker under `off`, and `provider_called` says whether `on` did.+ */+import type { BrainEngine } from '../core/engine.ts';+import type { OperationContext } from '../core/operations.ts';+import { operationsByName } from '../core/operations.ts';++export type GateArm = 'off' | 'on';++/** One question: params passed verbatim to `recall` (optional) and `query`. */+export interface LatencyItem {+ id: string;+ kind?: string;+ recall?: Record<string, unknown>;+ query: Record<string, unknown>;+}++/** What one arm of one item observed. */+export interface ArmObservation {+ recall_ms: number;+ query_ms: number;+ /** Searches the gate graded as eligible (the reranker would run under `off`). */+ eligible: number;+ /** Searches whose reranker provider was called. */+ provider_calls: number;+ /** Searches the gate skipped. */+ skipped: number;+}++export interface ArmSample extends ArmObservation {+ id: string;+ kind?: string;+ arm: GateArm;+ repeat: number;+ /** 0 when this arm ran first in its pair. */+ position: 0 | 1;+ ms: number;+ error?: string;+}++export interface PairedRunOpts {+ warmup: number;+ repeats: number;+ concurrency: number;+ now?: () => number;+}++export type ArmCaller = (arm: GateArm, item: LatencyItem, now: () => number) => Promise<ArmObservation>;++/** Pairs in run order; the first arm alternates by item and by repeat. */+export function pairedSchedule(items: readonly LatencyItem[], repeats: number): Array<{ item: LatencyItem; repeat: number; arms: [GateArm, GateArm] }> {+ const out: Array<{ item: LatencyItem; repeat: number; arms: [GateArm, GateArm] }> = [];+ for (let repeat = 0; repeat < repeats; repeat++) {+ items.forEach((item, i) => {+ out.push({ item, repeat, arms: (i + repeat) % 2 === 0 ? ['off', 'on'] : ['on', 'off'] });+ });+ }+ return out;+}++/** Warm up, then run every pair on `concurrency` workers; returns timed samples only. */+export async function runPaired(items: readonly LatencyItem[], call: ArmCaller, opts: PairedRunOpts): Promise<ArmSample[]> {+ const now = opts.now ?? (() => performance.now());+ for (const item of items.slice(0, Math.max(0, opts.warmup))) {+ for (const arm of ['off', 'on'] as const) await call(arm, item, now).catch(() => undefined);+ }+ const queue = pairedSchedule(items, Math.max(1, opts.repeats));+ const samples: ArmSample[] = [];+ const worker = async () => {+ for (let next = queue.shift(); next; next = queue.shift()) {+ for (const [position, arm] of next.arms.entries()) {+ const base = { id: next.item.id, ...(next.item.kind ? { kind: next.item.kind } : {}), arm, repeat: next.repeat, position: position as 0 | 1 };+ try {+ const o = await call(arm, next.item, now);+ samples.push({ ...base, ...o, ms: o.recall_ms + o.query_ms });+ } catch (err) {+ samples.push({ ...base, recall_ms: 0, query_ms: 0, eligible: 0, provider_calls: 0, skipped: 0, ms: 0, error: err instanceof Error ? err.message : String(err) });+ }+ }+ }+ };+ await Promise.all(Array.from({ length: Math.max(1, opts.concurrency) }, worker));+ return samples;+}++/** Nearest-rank percentile. */+export function percentile(xs: readonly number[], q: number): number {+ if (xs.length === 0) return 0;+ const s = [...xs].sort((a, b) => a - b);+ return s[Math.min(s.length - 1, Math.max(0, Math.ceil(q * s.length) - 1))]!;+}++const mean = (xs: readonly number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0);+const round = (x: number) => Math.round(x * 10) / 10;++export const MIN_MEAN_SAVING_MS = 100;+export const MIN_RERANKER_CALL_REDUCTION = 0.25;++export interface LatencyReport {+ pairs: number;+ errors: number;+ arms: Record<GateArm, { n: number; mean_ms: number; p50_ms: number; p95_ms: number }>;+ skipped_pairs: number;+ skip_rate: number;+ /** Mean paired off − on over the pairs whose `on` arm skipped (null with no skip). */+ mean_saving_per_skip_ms: number | null;+ /** Mean paired off − on over the pairs whose `on` arm reranked (the gate's overhead when negative). */+ mean_saving_no_skip_ms: number | null;+ p95_increase_ms: number;+ reranker_calls: { off: number; on: number; reduction: number };+ by_kind: Record<string, { pairs: number; skipped: number; mean_saving_per_skip_ms: number | null }>;+ verdict: {+ mean_saving_ok: boolean;+ p95_ok: boolean;+ reranker_call_reduction_ok: boolean;+ /** Gate 4's latency clause (A67): both of the above latency checks and no errored arm. */+ latency_pass: boolean;+ };+}++export function summarizeLatency(samples: readonly ArmSample[]): LatencyReport {+ const ok = samples.filter((s) => !s.error);+ const byPair = new Map<string, Partial<Record<GateArm, ArmSample>>>();+ for (const s of ok) {+ const key = `${s.id}\u0000${s.repeat}`;+ byPair.set(key, { ...byPair.get(key), [s.arm]: s });+ }+ const pairs = [...byPair.values()].filter((p): p is Record<GateArm, ArmSample> => !!p.off && !!p.on);+ const skipped = pairs.filter((p) => p.on.skipped > 0);+ const reranked = pairs.filter((p) => p.on.skipped === 0);+ const saving = (ps: typeof pairs) => (ps.length ? round(mean(ps.map((p) => p.off.ms - p.on.ms))) : null);+ const arm = (a: GateArm) => {+ const ms = pairs.map((p) => p[a].ms);+ return { n: ms.length, mean_ms: round(mean(ms)), p50_ms: round(percentile(ms, 0.5)), p95_ms: round(percentile(ms, 0.95)) };+ };+ const arms = { off: arm('off'), on: arm('on') };+ const callsOff = pairs.reduce((n, p) => n + p.on.eligible, 0);+ const callsOn = pairs.reduce((n, p) => n + p.on.provider_calls, 0);+ const reduction = callsOff > 0 ? 1 - callsOn / callsOff : 0;+ const by_kind: LatencyReport['by_kind'] = {};+ for (const kind of new Set(pairs.map((p) => p.on.kind ?? 'unknown'))) {+ const ps = pairs.filter((p) => (p.on.kind ?? 'unknown') === kind);+ const sk = ps.filter((p) => p.on.skipped > 0);+ by_kind[kind] = { pairs: ps.length, skipped: sk.length, mean_saving_per_skip_ms: saving(sk) };+ }+ const meanSaving = saving(skipped);+ const p95Increase = round(arms.on.p95_ms - arms.off.p95_ms);+ const errors = samples.length - ok.length;+ const mean_saving_ok = meanSaving !== null && meanSaving >= MIN_MEAN_SAVING_MS;+ const p95_ok = pairs.length > 0 && p95Increase <= 0;+ return {+ pairs: pairs.length,+ errors,+ arms,+ skipped_pairs: skipped.length,+ skip_rate: pairs.length ? skipped.length / pairs.length : 0,+ mean_saving_per_skip_ms: meanSaving,+ mean_saving_no_skip_ms: saving(reranked),+ p95_increase_ms: p95Increase,+ reranker_calls: { off: callsOff, on: callsOn, reduction },+ by_kind,+ verdict: {+ mean_saving_ok,+ p95_ok,+ reranker_call_reduction_ok: reduction >= MIN_RERANKER_CALL_REDUCTION,+ latency_pass: mean_saving_ok && p95_ok && errors === 0,+ },+ };+}++/** The brain as one arm sees it: `search.*` keys answered from `overlay` first. Writes nothing. */+export function withSearchConfig(engine: BrainEngine, overlay: Record<string, string>): BrainEngine {+ return new Proxy(engine, {+ get(target, prop, receiver) {+ if (prop === 'getConfig') {+ return async (key: string) => (key in overlay ? overlay[key] : target.getConfig(key));+ }+ if (prop === 'getAllConfig') {+ return async () => ({ ...(await target.getAllConfig()), ...overlay });+ }+ const value = Reflect.get(target, prop, receiver);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+}++/**+ * The real caller: `recall` then `query` through the operation handlers with+ * the arm's gate overlaid, reading the gate's meta from the retrieval meta+ * each search emits.+ */+export function operationArmCaller(base: OperationContext): ArmCaller {+ const engines: Record<GateArm, BrainEngine> = {+ off: withSearchConfig(base.engine, { 'search.reranker.gate': 'off' }),+ on: withSearchConfig(base.engine, { 'search.reranker.gate': 'on' }),+ };+ return async (arm, item, now) => {+ const metas: Array<{ rerank_gate?: { eligible?: boolean; provider_called?: boolean; skipped?: boolean } }> = [];+ const ctx: OperationContext = {+ ...base,+ engine: engines[arm],+ emitResponseMeta: (kind: string, meta: unknown) => { if (kind === 'retrieval' && meta && typeof meta === 'object') metas.push(meta as never); },+ } as OperationContext;+ let recall_ms = 0;+ if (item.recall) {+ const t0 = now();+ await operationsByName.recall!.handler(ctx, item.recall);+ recall_ms = now() - t0;+ }+ const t1 = now();+ await operationsByName.query!.handler(ctx, item.query);+ const query_ms = now() - t1;+ const gates = metas.map((m) => m.rerank_gate).filter((g) => g !== undefined);+ return {+ recall_ms,+ query_ms,+ eligible: gates.filter((g) => g.eligible).length,+ provider_calls: gates.filter((g) => g.provider_called).length,+ skipped: gates.filter((g) => g.skipped).length,+ };+ };+}diff --git a/test/eval/rerank-gate-latency-ops.serial.test.ts b/test/eval/rerank-gate-latency-ops.serial.test.tsnew file mode 100644index 0000000000..024f4e403e--- /dev/null+++ b/test/eval/rerank-gate-latency-ops.serial.test.ts@@ -0,0 +1,95 @@+/**+ * W3 gate 4 latency runner end to end: `operationArmCaller` drives the real+ * `query` operation on a PGLite brain with the gate overlaid per arm, the+ * real gateway rerank path behind `__setRerankTransportForTests` (a fixed+ * 150 ms provider delay) and a deterministic embed transport.+ *+ * Protects: the `on` arm skips the provider on a strong vector grade and the+ * `off` arm calls it, the runner reads skips and eligibility from the+ * retrieval meta the operation emits, the saving lands on the skipped pairs+ * only, and the brain's own gate config is never written.+ * Fails when: the overlay does not reach the search config read, the meta+ * channel is not read, or the arms share state.+ * Serial: sets GBRAIN_HOME and the process-global gateway transports.+ */+import { afterAll, beforeAll, 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 { configureGateway, resetGateway, __setEmbedTransportForTests, __setRerankTransportForTests } from '../../src/core/ai/gateway.ts';+import type { OperationContext } from '../../src/core/operations.ts';+import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';+import { operationArmCaller, runPaired, summarizeLatency } from '../../src/eval/rerank-gate-latency.ts';+import { DIM, QUERY_DIM, seed } from '../helpers/rerank-gate-fixture.ts';++const PROVIDER_DELAY_MS = 150;+let engine: PGLiteEngine;+let home: string;+let prevHome: string | undefined;+let rerankCalls = 0;++beforeAll(async () => {+ prevHome = process.env.GBRAIN_HOME;+ home = mkdtempSync(join(tmpdir(), 'gbrain-rrg-latency-'));+ process.env.GBRAIN_HOME = home;+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIM, env: { VOYAGE_API_KEY: 'vk-test-not-a-real-key', OPENAI_API_KEY: 'sk-test-not-a-real-key' } });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await seed(engine);+ await engine.setConfig('search.reranker.enabled', 'true');+ __setEmbedTransportForTests((async (args: { values: string[] }) => ({+ embeddings: args.values.map((v) => {+ const query = Object.keys(QUERY_DIM).find((q) => v.includes(q));+ return Array.from(basisEmbedding(query ? QUERY_DIM[query] : 999, DIM));+ }),+ })) as never);+ __setRerankTransportForTests(async (_url: string, init: RequestInit) => {+ rerankCalls++;+ await new Promise((r) => setTimeout(r, PROVIDER_DELAY_MS));+ const body = JSON.parse(String(init.body)) as { documents: string[] };+ const data = body.documents.map((_, index) => ({ index, relevance_score: 1 - index * 0.01 }));+ return new Response(JSON.stringify({ object: 'list', data, model: 'rerank-2.5' }), { status: 200, headers: { 'content-type': 'application/json' } });+ });+}, 120_000);++afterAll(async () => {+ __setRerankTransportForTests(null);+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine.disconnect();+ if (prevHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = prevHome;+ rmSync(home, { recursive: true, force: true });+});++describe('operationArmCaller through the query operation', () => {+ test('a strong vector question skips under on and saves the provider time; a gap miss reranks in both arms', async () => {+ const ctx = {+ engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {}, debug() {} },+ dryRun: false, remote: false, sourceId: 'default',+ } as unknown as OperationContext;+ const items = [+ { id: 'strong', kind: 'single-hop', query: { query: 'orbital period of the gold probe', limit: 10, expand: false } },+ { id: 'gap', kind: 'multi-hop', query: { query: 'tidal locking near twins', limit: 10, expand: false } },+ ];+ const samples = await runPaired(items, operationArmCaller(ctx), { warmup: 0, repeats: 2, concurrency: 1 });+ expect(samples.filter((s) => s.error)).toEqual([]);+ const on = (id: string) => samples.filter((s) => s.arm === 'on' && s.id === id);+ expect(on('strong').every((s) => s.skipped === 1 && s.provider_calls === 0 && s.eligible === 1)).toBe(true);+ expect(on('gap').every((s) => s.skipped === 0 && s.provider_calls === 1)).toBe(true);+ expect(samples.filter((s) => s.arm === 'off').every((s) => s.skipped === 0)).toBe(true);+ // 2 repeats × (strong off + gap off + gap on): the skipped arm made no call.+ expect(rerankCalls).toBe(6);++ const report = summarizeLatency(samples);+ expect(report.pairs).toBe(4);+ expect(report.skipped_pairs).toBe(2);+ expect(report.by_kind['single-hop'].skipped).toBe(2);+ expect(report.reranker_calls).toEqual({ off: 4, on: 2, reduction: 0.5 });+ expect(report.mean_saving_per_skip_ms!).toBeGreaterThanOrEqual(PROVIDER_DELAY_MS * 0.8);+ expect(report.verdict.mean_saving_ok).toBe(true);+ expect(await engine.getConfig('search.reranker.gate')).toBeNull();+ });+});diff --git a/test/eval/rerank-gate-latency.test.ts b/test/eval/rerank-gate-latency.test.tsnew file mode 100644index 0000000000..b9ce70bc01--- /dev/null+++ b/test/eval/rerank-gate-latency.test.ts@@ -0,0 +1,157 @@+/**+ * W3 gate 4 latency runner (src/eval/rerank-gate-latency.ts), pure parts.+ *+ * Protects: counterbalanced arm order, warm-up calls kept out of the samples,+ * the worker bound, the A67 verdict (mean saving per skipped query >= 100 ms,+ * no p95 increase, no errored arm), the derived reranker-call reduction and+ * the read-only config overlay.+ * Fails when: one arm always runs first, warm-up or queueing time leaks into+ * a sample, the verdict uses p50 or the wrong pair set, or the overlay+ * writes to the brain.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import {+ type ArmObservation,+ type ArmSample,+ type GateArm,+ type LatencyItem,+ pairedSchedule,+ percentile,+ runPaired,+ summarizeLatency,+ withSearchConfig,+} from '../../src/eval/rerank-gate-latency.ts';+import { parseItems } from '../../scripts/bench-rerank-gate-latency.ts';++const items = (n: number): LatencyItem[] => Array.from({ length: n }, (_, i) => ({ id: `q${i}`, query: { query: `question ${i}` } }));+const obs = (ms: number, o: Partial<ArmObservation> = {}): ArmObservation => ({ recall_ms: 0, query_ms: ms, eligible: 1, provider_calls: 1, skipped: 0, ...o });++function pair(id: string, offMs: number, onMs: number, skipped: boolean, kind = 'k'): ArmSample[] {+ const base = { id, kind, repeat: 0, recall_ms: 0, eligible: 1 };+ return [+ { ...base, arm: 'off', position: 0, query_ms: offMs, ms: offMs, provider_calls: 0, skipped: 0 },+ { ...base, arm: 'on', position: 1, query_ms: onMs, ms: onMs, provider_calls: skipped ? 0 : 1, skipped: skipped ? 1 : 0 },+ ];+}++describe('pairedSchedule', () => {+ test('the first arm alternates by item and flips on the next repeat', () => {+ const s = pairedSchedule(items(4), 2);+ expect(s.map((p) => p.arms[0])).toEqual(['off', 'on', 'off', 'on', 'on', 'off', 'on', 'off']);+ expect(s.filter((p) => p.arms[0] === 'off')).toHaveLength(4);+ for (const p of s) expect(new Set(p.arms)).toEqual(new Set(['off', 'on']));+ });+});++describe('runPaired', () => {+ test('warm-up calls are untimed, every pair runs both arms, and the worker bound holds', async () => {+ const calls: Array<{ arm: GateArm; id: string }> = [];+ let inFlight = 0;+ let peak = 0;+ const samples = await runPaired(items(6), async (arm, item) => {+ calls.push({ arm, id: item.id });+ inFlight++;+ peak = Math.max(peak, inFlight);+ await new Promise((r) => setTimeout(r, 5));+ inFlight--;+ return obs(10);+ }, { warmup: 2, repeats: 2, concurrency: 3 });+ expect(calls.slice(0, 4)).toEqual([{ arm: 'off', id: 'q0' }, { arm: 'on', id: 'q0' }, { arm: 'off', id: 'q1' }, { arm: 'on', id: 'q1' }]);+ expect(calls).toHaveLength(4 + 6 * 2 * 2);+ expect(samples).toHaveLength(24);+ expect(peak).toBeLessThanOrEqual(3);+ expect(peak).toBeGreaterThan(1);+ });++ test('a sample is the arm\'s own timed calls, never time spent waiting for a worker', async () => {+ let t = 0;+ const samples = await runPaired(items(4), async (_arm, _item, now) => {+ t += 1000;+ const start = now();+ t += 40;+ return obs(now() - start);+ }, { warmup: 0, repeats: 1, concurrency: 1, now: () => t });+ expect(samples.map((s) => s.ms)).toEqual(Array(8).fill(40));+ });++ test('an arm that throws is recorded as an error and fails the latency clause', async () => {+ const samples = await runPaired(items(2), async (arm) => {+ if (arm === 'on') throw new Error('boom');+ return obs(10);+ }, { warmup: 0, repeats: 1, concurrency: 1 });+ expect(samples.filter((s) => s.error === 'boom')).toHaveLength(2);+ expect(summarizeLatency(samples).verdict.latency_pass).toBe(false);+ });+});++describe('summarizeLatency', () => {+ test('nearest-rank percentiles', () => {+ expect(percentile([5, 1, 3, 2, 4], 0.5)).toBe(3);+ expect(percentile(Array.from({ length: 20 }, (_, i) => i + 1), 0.95)).toBe(19);+ expect(percentile([], 0.95)).toBe(0);+ });++ test('the saving is measured per skipped pair; reranked pairs and p95 are reported apart', () => {+ const samples = [+ ...pair('a', 400, 250, true, 'temporal'),+ ...pair('b', 420, 260, true, 'temporal'),+ ...pair('c', 410, 412, false, 'abstention'),+ ...pair('d', 900, 899, false, 'abstention'),+ ];+ const r = summarizeLatency(samples);+ expect(r.pairs).toBe(4);+ expect(r.skipped_pairs).toBe(2);+ expect(r.skip_rate).toBe(0.5);+ expect(r.mean_saving_per_skip_ms).toBe(155);+ expect(r.mean_saving_no_skip_ms).toBe(-0.5);+ expect(r.arms.off.p95_ms).toBe(900);+ expect(r.arms.on.p95_ms).toBe(899);+ expect(r.reranker_calls).toEqual({ off: 4, on: 2, reduction: 0.5 });+ expect(r.by_kind.temporal).toEqual({ pairs: 2, skipped: 2, mean_saving_per_skip_ms: 155 });+ expect(r.by_kind.abstention.mean_saving_per_skip_ms).toBeNull();+ expect(r.verdict).toEqual({ mean_saving_ok: true, p95_ok: true, reranker_call_reduction_ok: true, latency_pass: true });+ });++ test('a small saving or a p95 increase fails the clause', () => {+ const small = summarizeLatency([...pair('a', 300, 220, true), ...pair('b', 300, 300, false)]);+ expect(small.mean_saving_per_skip_ms).toBe(80);+ expect(small.verdict.mean_saving_ok).toBe(false);+ expect(small.verdict.latency_pass).toBe(false);+ const slowTail = summarizeLatency([...pair('a', 400, 200, true), ...pair('b', 500, 520, false)]);+ expect(slowTail.verdict.mean_saving_ok).toBe(true);+ expect(slowTail.p95_increase_ms).toBe(20);+ expect(slowTail.verdict.p95_ok).toBe(false);+ expect(slowTail.verdict.latency_pass).toBe(false);+ const none = summarizeLatency([...pair('a', 300, 300, false)]);+ expect(none.mean_saving_per_skip_ms).toBeNull();+ expect(none.verdict.latency_pass).toBe(false);+ });+});++describe('items file', () => {+ test('one JSON object per line with an id and query params', () => {+ expect(parseItems('{"id":"q1","query":{"query":"x"}}\n\n{"id":"q2","kind":"temporal","recall":{"limit":100},"query":{"query":"y","token_budget":6300}}\n'))+ .toEqual([{ id: 'q1', query: { query: 'x' } }, { id: 'q2', kind: 'temporal', recall: { limit: 100 }, query: { query: 'y', token_budget: 6300 } }]);+ expect(() => parseItems('{"id":"q1"}')).toThrow('items line 1');+ });+});++describe('withSearchConfig', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig('search.reranker.gate', 'shadow');+ }, 120_000);+ afterAll(async () => { await engine.disconnect(); });++ test('the overlay answers its keys first and writes nothing', async () => {+ const on = withSearchConfig(engine, { 'search.reranker.gate': 'on' });+ expect(await on.getConfig('search.reranker.gate')).toBe('on');+ expect((await on.getAllConfig())['search.reranker.gate']).toBe('on');+ expect(await engine.getConfig('search.reranker.gate')).toBe('shadow');+ expect((await engine.getAllConfig())['search.reranker.gate']).toBe('shadow');+ });+});