Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): the query-embed deadline starts at the first embed request (#6400 a)
time-attackef943659d85c
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex a69f1c54b7..c257b4b0df 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -43,6 +43,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELregardless of which deadline path wins. Provider failures before that deadlineretain their classification. The timeout budget and keyword fallback are unchanged;pinned by `test/search/query-embed-deadline.test.ts` and the real transport matrix.+ The shared query-embed deadline (`lazyQueryEmbedDeadline`, threaded to the+ vector arm as the `_queryEmbedDeadline` getter) starts at the first embed+ request, so lexical work and expansion before the vector arm don't spend it;+ the cache-lookup and vector-arm embeds still share one budget+ (`test/search/query-embed-deadline-start.test.ts`).- `src/core/search/image-loader.ts` — `loadImageInput(input, opts)` accepts a local path, `data:` URI, or `http(s)://` URL. Magic-byte sniff for PNG/JPEG/WebP. Hard size cap (default 10 MB, configurable via `search.image_query.max_bytes`). URLs route through `fetchWithSSRFGuard` so DNS rebinding + redirect chains are defeated; shared guarded transport pins validated DNS answers and streams decoded bodies with a 2 MiB remote cap (10 MiB local cap). `ImageLoadError` with discriminated `code` (INVALID_FORMAT / OVERSIZED / INVALID_URL / FETCH_FAILED / TIMEOUT / SSRF_BLOCKED / NOT_FOUND).diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex b1d441549b..e71d82e516 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -944,10 +944,11 @@ export interface HybridSearchOpts extends SearchOpts {* v0.42.20.0 (Fix 3, #1775) INTERNAL — shared query-embed deadline threaded* from `hybridSearchCached` into the inner `hybridSearch` so the cache-lookup* embed and the inner embed share ONE wall-clock budget (worst case ~one- * timeout, not two). Direct `hybridSearch` callers leave it undefined and get- * a fresh per-call deadline. Not part of the public contract.+ * timeout, not two). A getter: the deadline starts at the first embed+ * request. Direct `hybridSearch` callers leave it undefined and get a fresh+ * per-call deadline. Not part of the public contract.*/- _queryEmbedDeadline?: QueryEmbedDeadline;+ _queryEmbedDeadline?: () => QueryEmbedDeadline;/*** #5691 INTERNAL — the brain's `embedding_query_prefix`, read once per* request (by `hybridSearchCached`, or by `hybridSearch` when undefined) and@@ -1008,8 +1009,8 @@ const QUERY_EMBED_TIMEOUT_MS = (() => {/*** Floor for the remaining shared-deadline budget at each embed call (codex).- * The shared deadline is absolute from `hybridSearchCached` entry, so slow- * expansion/keyword (or a 6s cache-lookup stall) before the inner embed could+ * The shared deadline is absolute from the first embed request, so a 6s+ * cache-lookup stall (or slow work between two embeds) before the inner embed could* leave ~0 budget and starve a HEALTHY embed into a false keyword-only result.* Flooring guarantees every embed gets at least this long, so a fast healthy* embed (~0.5s) always succeeds. Worst case under a stalled provider on the@@ -1029,6 +1030,17 @@ export function makeQueryEmbedDeadline(ms = QUERY_EMBED_TIMEOUT_MS): QueryEmbedDreturn { signal: AbortSignal.timeout(ms), deadlineAt: Date.now() + ms };}+/**+ * #6400 (a): a shared query-embed deadline that starts at the FIRST embed+ * request, not when the search starts. Every call returns the same deadline,+ * so the cache-lookup embed and the vector-arm embeds still share one budget,+ * but lexical work and expansion before the first embed no longer spend it.+ */+export function lazyQueryEmbedDeadline(ms = QUERY_EMBED_TIMEOUT_MS): () => QueryEmbedDeadline {+ let dl: QueryEmbedDeadline | undefined;+ return () => (dl ??= makeQueryEmbedDeadline(ms));+}+/*** Embed a query bounded by the shared deadline. Two layers: (1) `abortSignal`* aborts the fetch so the socket closes and the process can exit clean; (2) a@@ -1215,8 +1227,10 @@ export async function hybridSearchCached(// opts._queryEmbedDeadline). On a stalled provider the cache-lookup embed// times out (→ cacheStatus 'disabled', fall through), then the inner embed// sees the already-elapsed budget and fails fast → keyword fallback. Worst- // case ~one timeout (~6s), comfortably under the CLI 10s force-exit.- const queryEmbedDl = makeQueryEmbedDeadline();+ // case ~one timeout (~6s), comfortably under the CLI 10s force-exit. The+ // budget starts at the first embed request (#6400), so lexical work and+ // expansion before the vector arm don't spend it.+ const queryEmbedDl = lazyQueryEmbedDeadline();if (semanticCache && !skipCache) {try {const { isAvailable } = await import('../ai/gateway.ts');@@ -1230,7 +1244,7 @@ export async function hybridSearchCached(// v0.42.20.0 (Fix 3) — bounded by the shared deadline; on timeout this// throws → caught below → cacheStatus 'disabled' → falls through to the// inner hybridSearch (which reuses the same elapsed deadline).- queryEmbedding = await embedQueryBounded(query, queryPrefix ? { queryPrefix } : undefined, queryEmbedDl);+ queryEmbedding = await embedQueryBounded(query, queryPrefix ? { queryPrefix } : undefined, queryEmbedDl());} else {cacheStatus = 'disabled';}diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.tsindex 8e6dea1c62..976b98d148 100644--- a/src/core/search/hybrid/arms.ts+++ b/src/core/search/hybrid/arms.ts@@ -6,7 +6,7 @@import type { ModalityMode } from '../query-intent.ts';import type { ExactLookupOpts } from '../exact-lookup.ts';import type { HybridRequest } from './request.ts';-import { type PostFusionOpts, embedQueryBounded, makeQueryEmbedDeadline } from '../hybrid.ts';+import { type PostFusionOpts, embedQueryBounded, lazyQueryEmbedDeadline } from '../hybrid.ts';import type { SearchOpts, SearchResult } from '../../types.ts';import { type VectorArm, pushVectorList } from '../fusion-lists.ts';import { buildRelationalArm } from '../relational-recall.ts';@@ -379,7 +379,7 @@ export async function runVectorArms(// threaded from hybridSearchCached (so the cache-lookup embed + this one// share one ~6s budget); direct callers get a fresh deadline. On timeout// the embed rejects → salvage below (or keyword-only when all reject).- const embedDl = opts?._queryEmbedDeadline ?? makeQueryEmbedDeadline();+ const embedDl = opts?._queryEmbedDeadline ?? lazyQueryEmbedDeadline();// Hermetic eval canaries/CI: queryEmbedFn (non-semantic deterministic// embeddings) replaces the gateway query-embed for the text vector arm.// No deadline needed — it's a synchronous-ish local computation with no@@ -387,7 +387,7 @@ export async function runVectorArms(const embedOneQuery = (q: string): Promise<Float32Array> =>opts?.queryEmbedFn? Promise.resolve(opts.queryEmbedFn(q))- : embedQueryBounded(q, embedOpts, embedDl);+ : embedQueryBounded(q, embedOpts, embedDl());if (!searchSalvageEnabled()) {// ENG-7 kill switch (GBRAIN_SEARCH_SALVAGE=off): pre-wave// all-or-nothing fan-outs — one variant's failure abandons everydiff --git a/test/search/query-embed-deadline-start.test.ts b/test/search/query-embed-deadline-start.test.tsnew file mode 100644index 0000000000..e4b55d0b18--- /dev/null+++ b/test/search/query-embed-deadline-start.test.ts@@ -0,0 +1,72 @@+/**+ * #6400 (a): the query-embed deadline starts at the first embed request.+ *+ * Protects: slow lexical work or expansion before the vector arm must not+ * spend the embed budget, so a healthy embed after a slow keyword arm still+ * gets the full QUERY_EMBED_TIMEOUT_MS instead of the 2 s floor. Fails when+ * the deadline is created at hybridSearchCached entry (master before the fix).+ * The clock jump is injected in the keyword arm; AbortSignal.timeout records+ * the budget embedQueryBounded grants. PGLite in-memory; embed transport stubbed.+ */+import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';+import { hybridSearchCached, lazyQueryEmbedDeadline } from '../../src/core/search/hybrid.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ await importFromContent(engine, 'notes/widget-roadmap',+ '---\ntype: note\ntitle: Widget roadmap\n---\n\nThe widget roadmap covers the next release.\n', { noEmbed: true });+}, 60_000);++afterAll(async () => { await engine?.disconnect(); }, 60_000);++afterEach(() => {+ __setEmbedTransportForTests(null);+ resetGateway();+});++describe('query-embed deadline start (#6400 a)', () => {+ test('lazyQueryEmbedDeadline starts on the first call and returns the same deadline after', async () => {+ const get = lazyQueryEmbedDeadline(6_000);+ await new Promise(resolve => setTimeout(resolve, 50));+ const before = Date.now();+ const first = get();+ expect(first.deadlineAt).toBeGreaterThanOrEqual(before + 6_000);+ expect(get()).toBe(first);+ });++ test('a slow keyword arm does not spend the vector arm embed budget', async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-fake' } });+ let embeds = 0;+ __setEmbedTransportForTests((async (args: { values: string[] }) => {+ embeds += args.values.length;+ return { embeddings: args.values.map(() => Array.from({ length: 1536 }, () => 0.01)) };+ }) as never);+ const realNow = Date.now.bind(Date);+ let offset = 0;+ const now = spyOn(Date, 'now').mockImplementation(() => realNow() + offset);+ const budgets: number[] = [];+ const realTimeout = AbortSignal.timeout.bind(AbortSignal);+ const timeout = spyOn(AbortSignal, 'timeout').mockImplementation((ms: number) => { budgets.push(ms); return realTimeout(ms); });+ const searchKeyword = engine.searchKeyword.bind(engine);+ const keyword = spyOn(engine, 'searchKeyword').mockImplementation(async (...args: Parameters<PGLiteEngine['searchKeyword']>) => {+ offset += 10_000; // the keyword arm "took" 10 s+ return searchKeyword(...args);+ });+ try {+ await hybridSearchCached(engine, 'widget roadmap', { expansion: false, limit: 5 } as never);+ } finally {+ keyword.mockRestore();+ timeout.mockRestore();+ now.mockRestore();+ }+ expect(embeds).toBeGreaterThan(0);+ // embedQueryBounded's own budget: the full default, not the 2 s floor.+ expect(budgets.some(ms => ms >= 5_000)).toBe(true);+ expect(budgets).not.toContain(2_000);+ });+});