Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): report candidate_budget when the Postgres capped retry hits its cap; deterministic rollback e2e (#5989)

garrytan938cf9f30028
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 205c20573f..c03f2ec2f4 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -30,7 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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`.
-- `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, capped, arm_ms }`; 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`); 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 1b56223b75..196ce253c0 100644
--- a/src/core/engine-sql/cjk-search.ts
+++ b/src/core/engine-sql/cjk-search.ts
@@ -69,6 +69,8 @@ export interface CjkKeywordRun {
/** Test and bench seams; production uses CJK_CANDIDATE_CAP and PGLITE_CJK_CAPPED_CHUNKS. */
candidateCap?: number;
pgliteCappedChunks?: number;
+ /** Full-scoring share of the deadline in ms (default 2/3 of it). */
+ fullBudgetMs?: number;
}
type Exec = ScopedRead;
@@ -167,12 +169,12 @@ export async function searchKeywordCJK(
});
return out.map(rowToSearchResult);
}
- const full = await bounded(scoped, started + (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));
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));
- report(capped && !capped.capHit ? { incomplete: false, capped: true } : { incomplete: true, reason: 'timeout', capped: true });
+ 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 e19b4e2221..ccfeaff57d 100644
--- a/test/e2e/cjk-keyword-deadline-postgres.test.ts
+++ b/test/e2e/cjk-keyword-deadline-postgres.test.ts
@@ -2,9 +2,10 @@
* Postgres parity for the CJK keyword OR fallback (#6043) and the bounded arm
* (#5989): a real statement timeout inside the scoped read transaction rolls
* back to the savepoint, the capped retry keeps the source scope, and the
- * engine serves the next query normally. The corpus is sized so the full
- * scoring takes well past 2/3 of the 1.5 s deadline (asserted) while the capped
- * retry needs tens of milliseconds, so the outcome does not depend on load.
+ * 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.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
@@ -42,22 +43,26 @@ describe.skipIf(!RUN)('CJK keyword arm on Postgres', () => {
test('a full scoring that times out rolls back; the capped retry, in a fresh transaction, serves in-scope rows and the engine stays usable', async () => {
const metas: CjkKeywordMeta[] = [];
- const started = performance.now();
const rows = await engine.searchKeyword('좌석 업그레이드', { sourceId: 'cjk-a', orFallback: true, limit: 20,
- cjkKeyword: { deadlineMs: 1500, onMeta: (m) => metas.push(m) } });
- const elapsed = performance.now() - started;
+ cjkKeyword: { deadlineMs: 30_000, fullBudgetMs: 150, onMeta: (m) => metas.push(m) } });
expect(metas).toHaveLength(1);
- expect(metas[0]).toMatchObject({ incomplete: true, reason: 'timeout', capped: true });
- const full = performance.now();
- await engine.searchKeyword('좌석 업그레이드', { sourceId: 'cjk-a', limit: 20 });
- expect(performance.now() - full).toBeGreaterThan(1_200);
- expect(elapsed).toBeLessThan(2_500);
- expect(rows.length).toBeGreaterThan(0);
+ expect(metas[0]).toMatchObject({ incomplete: true, reason: 'candidate_budget', capped: true });
+ expect(rows).toHaveLength(20);
expect(rows.every((r) => r.source_id === 'cjk-a')).toBe(true);
const after = await engine.searchKeyword('席位', { sourceId: 'cjk-b' });
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 () => {
+ const metas: CjkKeywordMeta[] = [];
+ const started = performance.now();
+ 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);
+ expect(metas[0]?.incomplete).toBe(true);
+ expect(rows.every((r) => r.source_id === 'cjk-a')).toBe(true);
+ }, 60_000);
+
test('a retry that also runs out of time returns no keyword rows with the degraded reason, never an error', async () => {
const metas: CjkKeywordMeta[] = [];
const rows = await engine.searchKeyword('좌석 업그레이드', { sourceId: 'cjk-a', orFallback: true,