Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(cjk): assert the deadline arm's statement budgets, not wall time

garrytanbea509819875
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index d431d7e4c7..ac70bc25c1 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -50,7 +50,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/evidence-packing.ts` — the explicit-budget packing surface of evidence delivery: `AUTO_PACKINGS` (`off`, `cap_only` default, `breadth_capped`, `depth_first`) for `search.auto_packing`, `MIN_EXPLICIT_AUTO_BUDGET` (32; an explicit `auto` budget below it, or non-finite, is refused with `invalid_params` naming it), `parseAutoPacking` (the library override, unknown values refused), `configPacking` (unknown stored values read as the default) and `autoPackingValueProblem` (the `config set` refusal wired through `search/config-values.ts`). Tests: `test/evidence-delivery.test.ts`.
- `src/core/search/hnsw-iterative-scan.ts` — the pgvector `hnsw.iterative_scan` mode for filtered vector search (#6132 idea): `relaxed_order` by default, `strict_order` or `off` through `GBRAIN_HNSW_ITERATIVE_SCAN` (wins) or `search.hnsw_iterative_scan` (file > DB via loadConfigWithEngine). `resolveHnswIterativeScan(cfg)` latches once per process (hybrid `request.ts` passes it as `SearchOpts.hnswIterativeScan`; engines hand it to `withVectorSettings`), logging once when an override is active. `hnswIterativeScanValueProblem` backs the `config set` refusal through `search/config-values.ts` (`searchConfigValueRefusal`: enum/range rules for `search.*` keys, exit 2 `invalid_params`, nothing written). Pinned by `test/search/hnsw-iterative-scan.test.ts` and the Postgres recall fixture `test/e2e/hnsw-iterative-scan-recall-postgres.test.ts`; bench `scripts/bench/hnsw-iterative-scan.ts` (its `--corpus latent` mode, with `scripts/bench/hnsw-latent-corpus.ts` and the VM bootstrap `scripts/bench/hnsw-scale-vm-setup.sh`, is the E5.4 scale and index-build bench; results in `docs/eval/hnsw-scale-bench.md`).
-- `src/core/search/cjk-keyword-sql.ts` + `src/core/engine-sql/cjk-search.ts` + `src/core/search/cjk-keyword-deadline.ts` — the CJK keyword fallback shared by both engines. `buildCJKKeywordSql(query, ctx, variant)` keeps today's strict-AND SQL byte-identical by default; `match: 'any'` (the OR fallback, #6043) qualifies a chunk on any term and orders by matched-term count, then the TF score (the count enters the score as 1000 x matched outside the source factor, so a boosted partial match never outranks an all-term chunk); `candidateIds` scores only a candidate set by joining `unnest($n::bigint[])` to `content_chunks` (an `= ANY` filter was a sequential scan). `buildCJKCandidateSql` is the unordered capped LIKE scan for ids (all-term, or any-term excluding ids already taken). `searchKeywordCJK(scoped, query, ctx, engine)` runs strict AND and, with `opts.orFallback` and 2+ terms, the OR pass only when strict AND returns fewer than `limit` rows; with `opts.cjkKeyword` (hybrid only, deadline from `search.cjk_keyword_deadline_ms`, integer ms 500..30000, default 3000) it bounds the arm: Postgres runs full scoring in its own scoped read transaction within 2/3 of the deadline (counted from before the pool wait; every statement of an attempt gets `statement_timeout` = what is left of that attempt, minus a 40 ms rollback margin), and on SQLSTATE 57014 a capped retry (`CJK_CANDIDATE_CAP` = 2000; all-term ids first, partial ids only when the all-term rows fall short) in a fresh scoped transaction with the remaining third (a fresh transaction, not a savepoint, because the driver rethrows any failed statement at the end of its transaction scope); PGLite runs the capped stage whenever `pg_class.reltuples` exceeds `PGLITE_CJK_CAPPED_CHUNKS` = 50,000. `onMeta` gets `{ incomplete, reason (timeout | candidate_budget), capped, arm_ms }` (test seams: `candidateCap`, `pgliteCappedChunks`, `fullBudgetMs`); hybrid `request.ts` turns `incomplete` into degraded `keyword_candidates_incomplete` and `emitHybridMeta` adds `keyword_candidates` (keyword-arm wall time, separate from total hybrid latency) to every return path's meta. Pinned by `test/cjk-keyword-fallback.test.ts`, `test/e2e/cjk-keyword-deadline-postgres.test.ts` and `test/cjk-keyword-sql.test.ts`; bench `scripts/bench/cjk-keyword-deadline.ts`.
+- `src/core/search/cjk-keyword-sql.ts` + `src/core/engine-sql/cjk-search.ts` + `src/core/search/cjk-keyword-deadline.ts` — the CJK keyword fallback shared by both engines. `buildCJKKeywordSql(query, ctx, variant)` keeps today's strict-AND SQL byte-identical by default; `match: 'any'` (the OR fallback, #6043) qualifies a chunk on any term and orders by matched-term count, then the TF score (the count enters the score as 1000 x matched outside the source factor, so a boosted partial match never outranks an all-term chunk); `candidateIds` scores only a candidate set by joining `unnest($n::bigint[])` to `content_chunks` (an `= ANY` filter was a sequential scan). `buildCJKCandidateSql` is the unordered capped LIKE scan for ids (all-term, or any-term excluding ids already taken). `searchKeywordCJK(scoped, query, ctx, engine)` runs strict AND and, with `opts.orFallback` and 2+ terms, the OR pass only when strict AND returns fewer than `limit` rows; with `opts.cjkKeyword` (hybrid only, deadline from `search.cjk_keyword_deadline_ms`, integer ms 500..30000, default 3000) it bounds the arm: Postgres runs full scoring in its own scoped read transaction within 2/3 of the deadline (counted from before the pool wait; every statement of an attempt gets `statement_timeout` = what is left of that attempt, minus a 40 ms rollback margin), and on SQLSTATE 57014 a capped retry (`CJK_CANDIDATE_CAP` = 2000; all-term ids first, partial ids only when the all-term rows fall short) in a fresh scoped transaction with the remaining third (a fresh transaction, not a savepoint, because the driver rethrows any failed statement at the end of its transaction scope); PGLite runs the capped stage whenever `pg_class.reltuples` exceeds `PGLITE_CJK_CAPPED_CHUNKS` = 50,000. `onMeta` gets `{ incomplete, reason (timeout | candidate_budget), capped, arm_ms }` (test seams: `candidateCap`, `pgliteCappedChunks`, `fullBudgetMs`, and `onStatementBudget`, which reports each Postgres statement's timeout and the arm time it was computed at so the E2E asserts budgets instead of wall time); hybrid `request.ts` turns `incomplete` into degraded `keyword_candidates_incomplete` and `emitHybridMeta` adds `keyword_candidates` (keyword-arm wall time, separate from total hybrid latency) to every return path's meta. Pinned by `test/cjk-keyword-fallback.test.ts`, `test/e2e/cjk-keyword-deadline-postgres.test.ts` and `test/cjk-keyword-sql.test.ts`; bench `scripts/bench/cjk-keyword-deadline.ts`.
- `src/core/search/internal-breadth.ts` — `INTERNAL_BREADTH_SEARCH_OPTS` (`autocut: false, adaptiveReturn: false`), the one option object internal callers spread into `hybridSearch` when they need the full ranked set rather than a reader-trimmed one (#5890): think gather (both legs), brainstorm close-set, grade-takes evidence, whoknows and enrich. Pinned by `test/internal-breadth-callers.serial.test.ts`; `eval-contradictions/runner.ts` still inherits both trims.
diff --git a/src/core/engine-sql/cjk-search.ts b/src/core/engine-sql/cjk-search.ts
index 196ce253c0..5c9702f951 100644
--- a/src/core/engine-sql/cjk-search.ts
+++ b/src/core/engine-sql/cjk-search.ts
@@ -71,6 +71,8 @@ export interface CjkKeywordRun {
pgliteCappedChunks?: number;
/** Full-scoring share of the deadline in ms (default 2/3 of it). */
fullBudgetMs?: number;
+ /** Test seam: each Postgres statement's timeout and the arm time it was computed at, in ms. */
+ onStatementBudget?: (budget: { timeoutMs: number; armMs: number }) => void;
}
type Exec = ScopedRead;
@@ -113,7 +115,7 @@ function isStatementTimeout(e: unknown): boolean {
* returns null and the next attempt opens a fresh one with the same source
* scope.
*/
-async function bounded<T>(scoped: ScopedReadRunner, ms: number, fn: (exec: Exec) => Promise<T>): Promise<T | null> {
+async function bounded<T>(scoped: ScopedReadRunner, ms: number, fn: (exec: Exec) => Promise<T>, observe?: (timeoutMs: number, at: number) => void): Promise<T | null> {
ms -= ROLLBACK_MARGIN_MS;
if (ms < MIN_ATTEMPT_MS) return null;
const end = performance.now() + ms;
@@ -124,8 +126,10 @@ async function bounded<T>(scoped: ScopedReadRunner, ms: number, fn: (exec: Exec)
const timed = scopedRead({
...exec,
unsafe: async (sql: string, params: readonly unknown[]) => {
- const left = Math.floor(end - performance.now());
+ const now = performance.now();
+ const left = Math.floor(end - now);
if (left < 1) throw Object.assign(new Error('cjk keyword attempt budget spent'), { code: '57014' });
+ observe?.(left, now);
await exec.unsafe(`SELECT set_config('statement_timeout', $1, true)`, [String(left)]);
return exec.unsafe(sql, params);
},
@@ -156,6 +160,7 @@ export async function searchKeywordCJK(
if (!run) return (await scoped(exec => fullScoring(exec, query, ctx, orFallback))).map(rowToSearchResult);
const cap = run.candidateCap ?? CJK_CANDIDATE_CAP;
const report = (meta: Omit<CjkKeywordMeta, 'arm_ms'>) => run.onMeta?.({ ...meta, arm_ms: Math.round(performance.now() - started) });
+ const observe = run.onStatementBudget && ((timeoutMs: number, at: number) => run.onStatementBudget!({ timeoutMs, armMs: at - started }));
if (engine === 'pglite') {
const out = await scoped(async exec => {
if (await chunkEstimate(exec) <= (run.pgliteCappedChunks ?? PGLITE_CJK_CAPPED_CHUNKS)) {
@@ -169,12 +174,12 @@ export async function searchKeywordCJK(
});
return out.map(rowToSearchResult);
}
- const full = await bounded(scoped, started + (run.fullBudgetMs ?? (run.deadlineMs * 2) / 3) - performance.now(), exec => fullScoring(exec, query, ctx, orFallback));
+ const full = await bounded(scoped, started + (run.fullBudgetMs ?? (run.deadlineMs * 2) / 3) - performance.now(), exec => fullScoring(exec, query, ctx, orFallback), observe);
if (full) {
report({ incomplete: false, capped: false });
return full.map(rowToSearchResult);
}
- const capped = await bounded(scoped, started + run.deadlineMs - performance.now(), exec => cappedScoring(exec, query, ctx, orFallback, cap));
+ const capped = await bounded(scoped, started + run.deadlineMs - performance.now(), exec => cappedScoring(exec, query, ctx, orFallback, cap), observe);
report(!capped ? { incomplete: true, reason: 'timeout', capped: true } : capped.capHit ? { incomplete: true, reason: 'candidate_budget', capped: true } : { incomplete: false, capped: true });
return (capped?.rows ?? []).map(rowToSearchResult);
}
diff --git a/test/e2e/cjk-keyword-deadline-postgres.test.ts b/test/e2e/cjk-keyword-deadline-postgres.test.ts
index c93d175fbb..0e694b2a29 100644
--- a/test/e2e/cjk-keyword-deadline-postgres.test.ts
+++ b/test/e2e/cjk-keyword-deadline-postgres.test.ts
@@ -5,7 +5,11 @@
* engine serves the next query normally. The rollback case pins the full
* attempt's budget (150 ms, far below the >1 s full scoring of this corpus)
* and gives the capped retry ample time, so its outcome does not depend on
- * load; the default-split case asserts only what holds under any load.
+ * load. The default-split cases assert the budgets the arm hands Postgres,
+ * on the arm's own clock, never elapsed wall time: a stall of the test
+ * process or the VM lengthens the wall time of a correct arm (a loaded gate
+ * once measured 4.6 s against the 1.5 s deadline), so the stall case below
+ * injects one and checks the arm starts nothing past its deadline.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
@@ -15,6 +19,18 @@ import type { CjkKeywordMeta } from '../../src/core/engine-sql/cjk-search.ts';
const RUN = hasDatabase();
let engine: PostgresEngine;
+type Budget = { timeoutMs: number; armMs: number };
+
+/** The full scoring's statements end inside its default 2/3 share and every statement inside the deadline, on the arm's clock. */
+function expectBudgetedWithin(budgets: Budget[], deadlineMs: number): void {
+ expect(budgets.length).toBeGreaterThan(0);
+ expect(budgets[0]!.armMs + budgets[0]!.timeoutMs).toBeLessThanOrEqual((deadlineMs * 2) / 3);
+ for (const b of budgets) {
+ expect(b.timeoutMs).toBeGreaterThanOrEqual(1);
+ expect(b.armMs + b.timeoutMs).toBeLessThanOrEqual(deadlineMs);
+ }
+}
+
async function seed(source: string, slugPrefix: string, pages: number, chunksPerPage: number, body: string): Promise<void> {
await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)
SELECT '${slugPrefix}' || i, $1, 'note', 'p' || i, 'x', '00000000-0000-4000-8000-000000000001'::uuid,
@@ -60,13 +76,28 @@ describe.skipIf(!RUN)('CJK keyword arm on Postgres', () => {
expect(after.map((r) => r.slug)).toEqual(['cjkb/seats-1']);
}, 60_000);
- test('with the default split the arm ends near its deadline and reports honestly either way', async () => {
+ test('with the default split the arm budgets every statement inside its deadline and reports honestly either way', async () => {
+ const metas: CjkKeywordMeta[] = [];
+ const budgets: Budget[] = [];
+ const rows = await engine.searchKeyword('좌석 업그레이드', { sourceId: 'cjk-a', orFallback: true, limit: 20,
+ cjkKeyword: { deadlineMs: 1500, onMeta: (m) => metas.push(m), onStatementBudget: (b) => budgets.push(b) } });
+ expect(metas[0]?.incomplete).toBe(true);
+ expectBudgetedWithin(budgets, 1500);
+ expect(rows.every((r) => r.source_id === 'cjk-a')).toBe(true);
+ }, 60_000);
+
+ test('a stall of the test process past the deadline lengthens only wall time: the arm starts nothing after its deadline', async () => {
const metas: CjkKeywordMeta[] = [];
+ const budgets: Budget[] = [];
const started = performance.now();
+ // The full scoring's statement is on the server by 300 ms; Postgres cuts it at its share while this thread sleeps.
+ const stall = setTimeout(() => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3_500), 300);
const rows = await engine.searchKeyword('좌석 업그레이드', { sourceId: 'cjk-a', orFallback: true, limit: 20,
- cjkKeyword: { deadlineMs: 1500, onMeta: (m) => metas.push(m) } });
- expect(performance.now() - started).toBeLessThan(1500 + 2_000);
+ cjkKeyword: { deadlineMs: 1500, onMeta: (m) => metas.push(m), onStatementBudget: (b) => budgets.push(b) } });
+ clearTimeout(stall);
+ expect(performance.now() - started).toBeGreaterThanOrEqual(3_500);
expect(metas[0]?.incomplete).toBe(true);
+ expectBudgetedWithin(budgets, 1500);
expect(rows.every((r) => r.source_id === 'cjk-a')).toBe(true);
}, 60_000);