Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(propose_takes): our own implementation of the #5958 fix (#5958)
time-attack30dad6ca7467
diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex 268b848bc0..4912328f22 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -196,10 +196,10 @@ export type ProposeTakesExtractor = (input: {/** #4494: escalated cap for the one truncation retry (default* PROPOSE_TAKES_RETRY_MAX_TOKENS; clamped to >= maxTokens). */retryMaxTokens?: number;- /** #5874: wall-clock bound for every extractor call- * (dream.propose_takes.call_timeout_ms, held to the remaining phase- * time). Unset: scales with the output cap. */- callTimeoutMs?: number;+ /** #5958: operator-set bound (ms) for each extractor call, base and retry+ * alike. The phase reads dream.propose_takes.call_timeout_ms and caps it+ * by the phase time left. Absent: extractorCallTimeoutMs(maxTokens). */+ callBoundMs?: number;/** #5425: include EXTRACT_TAKES_ATTRIBUTION_RULES (opt-in). */attributionRules?: boolean;}) => Promise<ProposedTake[]>;@@ -392,14 +392,8 @@ export const PROPOSE_TAKES_RETRY_MAX_TOKENS = 4096;* page was re-billed (base call + aborted retry) forever with no tombstone.* 90s per PROPOSE_TAKES_MAX_TOKENS of output, floored at 90s, capped at* EXTRACTOR_CALL_TIMEOUT_MAX_MS.- *- * #5874: a configured `callTimeoutMs` replaces the scaling for every call.- * The claude-cli provider ignores maxTokens and never reports a truncation,- * so the retry never runs and the base call keeps 90s, which a large page on- * a slow model does not fit. The gateway's own chat timeout still races it.*/-function extractorCallTimeoutMs(maxTokens: number, callTimeoutMs?: number): number {- if (callTimeoutMs !== undefined) return callTimeoutMs;+function extractorCallTimeoutMs(maxTokens: number): number {const scaled = Math.ceil((EXTRACTOR_CALL_TIMEOUT_MS * maxTokens) / PROPOSE_TAKES_MAX_TOKENS);return Math.min(EXTRACTOR_CALL_TIMEOUT_MAX_MS, Math.max(EXTRACTOR_CALL_TIMEOUT_MS, scaled));}@@ -409,9 +403,9 @@ function extractorCallTimeoutMs(maxTokens: number, callTimeoutMs?: number): numb* never outlasts the phase deadline (never below the default 90s floor, which* the unconfigured path already allows). Unset: no override.*/-function phaseBoundedCallTimeout(configuredMs: number | undefined, phaseRemainingMs: number): { callTimeoutMs?: number } {+function phaseBoundedCallTimeout(configuredMs: number | undefined, phaseRemainingMs: number): { callBoundMs?: number } {if (configuredMs === undefined) return {};- return { callTimeoutMs: Math.min(configuredMs, Math.max(EXTRACTOR_CALL_TIMEOUT_MS, phaseRemainingMs)) };+ return { callBoundMs: Math.min(configuredMs, Math.max(EXTRACTOR_CALL_TIMEOUT_MS, phaseRemainingMs)) };}/**@@ -458,29 +452,31 @@ export async function defaultExtractor(// full gateway default (GBRAIN_AI_CHAT_TIMEOUT_MS, 300s) x pageLimit. The// caller already catches per-page errors, logs a warning, and continues.// The bound scales with maxTokens so an escalated or configured larger cap- // gets time to generate what it allows, unless- // dream.propose_takes.call_timeout_ms replaces it for every call.- const call = async (maxTokens: number) => {- const timeoutMs = extractorCallTimeoutMs(maxTokens, input.callTimeoutMs);- const abortSignal = AbortSignal.timeout(timeoutMs);- try {- return await gatewayChat({- messages: [{ role: 'user', content: prompt }],- ...(input.modelHint ? { model: input.modelHint } : {}),- maxTokens,- abortSignal,- });- } catch (err) {- if (!abortSignal.aborted) throw err;- // #5874: a provider abort message names neither the bound nor the key that moves it.- const msg = err instanceof Error ? err.message : String(err);+ // gets time to generate what it allows. An operator bound (callBoundMs)+ // takes its place for every call: claude-cli never reports a truncation,+ // so on that route the retry and its longer scaled bound never happen.+ const call = (maxTokens: number) => {+ const boundMs = input.callBoundMs ?? extractorCallTimeoutMs(maxTokens);+ const ownBound = AbortSignal.timeout(boundMs);+ return gatewayChat({+ messages: [{ role: 'user', content: prompt }],+ ...(input.modelHint ? { model: input.modelHint } : {}),+ maxTokens,+ abortSignal: ownBound,+ }).catch((err: unknown) => {+ // Reword only what our own bound stopped; any other failure, including+ // the gateway's shorter chat timeout, keeps its error untouched. The+ // provider's abort text alone names neither the bound nor the key.+ if (!ownBound.aborted) throw err;+ const providerText = err instanceof Error ? err.message : String(err);throw new Error(- `propose_takes extractor: call timed out after ${timeoutMs} ms on ${input.pagePath} (${msg}); ` +- `set ${PROPOSE_TAKES_CALL_TIMEOUT_KEY} (${PROPOSE_TAKES_CALL_TIMEOUT_MIN_MS}-${PROPOSE_TAKES_CALL_TIMEOUT_MAX_MS} ms) ` +- `to change the bound; no tombstone written, page retries next cycle`,+ `propose_takes extractor: ${input.pagePath} timed out after ${boundMs} ms, the per-call bound ` ++ `(${providerText}). To move it, set ${PROPOSE_TAKES_CALL_TIMEOUT_KEY} to whole ms from ` ++ `${PROPOSE_TAKES_CALL_TIMEOUT_MIN_MS} to ${PROPOSE_TAKES_CALL_TIMEOUT_MAX_MS}. ` ++ `No tombstone was written; the page is retried next cycle.`,{ cause: err },);- }+ });};let result = await call(baseMaxTokens);diff --git a/test/propose-takes-config-max-tokens.test.ts b/test/propose-takes-config-max-tokens.test.tsindex 9c53c6c9b1..e5fdfe7a69 100644--- a/test/propose-takes-config-max-tokens.test.ts+++ b/test/propose-takes-config-max-tokens.test.ts@@ -11,7 +11,7 @@* seam (dream.triage.max_tokens precedent) and thread into defaultExtractor.*/-import { describe, test, expect, beforeEach, afterAll } from 'bun:test';+import { describe, test, expect, beforeEach, afterAll, spyOn } from 'bun:test';import {configureGateway,resetGateway,@@ -199,71 +199,110 @@ describe('runPhaseProposeTakes threads dream.propose_takes.* config (#4494)', ()});});-// #5958 / #5874: dream.propose_takes.call_timeout_ms. A stored value the phase-// cannot use warns with the key named (never the value); an out-of-range number-// is held to 1000..300000; the configured bound never outlasts the remaining-// phase deadline beyond the default 90s floor.-describe('runPhaseProposeTakes threads dream.propose_takes.call_timeout_ms (#5958)', () => {- const KEY = 'dream.propose_takes.call_timeout_ms';- test.each([- ['an in-range value threads through', '240000', 240_000, false],- ['unset keeps the output-cap scaling', undefined, undefined, false],- ['blank reads as unset', ' ', undefined, false],- ['a non-number keeps the scaling with a warning', 'banana', undefined, true],- ['zero keeps the scaling with a warning', '0', undefined, true],- ['a negative value keeps the scaling with a warning', '-7', undefined, true],- ['a fractional value floors with a warning', '1500.7', 1_500, true],- ['below 1000 is held to 1000 with a warning', '20', 1_000, true],- ['above 300000 is held to 300000 with a warning', '300001', 300_000, true],- ['a value AbortSignal.timeout would reject is held to 300000', '1e16', 300_000, true],- ] as const)('call_timeout_ms: %s', async (_name, raw, expectedMs, warns) => {- const engine = buildMockEngine(raw === undefined ? {} : { [KEY]: raw });- const seen: Array<number | undefined> = [];- const extractor: ProposeTakesExtractor = async (input) => {- seen.push(input.callTimeoutMs);- return [];- };- const result = await runPhaseProposeTakes(buildCtx(engine), { extractor });- expect(seen).toEqual([expectedMs]);- const warnings = (result.details as { warnings: string[] }).warnings;- const named = warnings.filter((w) => w.includes(KEY));- expect(named.length > 0).toBe(warns);- for (const w of named) {- expect(w).toContain(`gbrain config set ${KEY}`);- expect(w).toContain(`gbrain config get ${KEY}`);- if (raw !== undefined && raw.trim().length > 2) expect(w).not.toContain(raw);+// #5958: dream.propose_takes.call_timeout_ms, read through+// cycle/phase-config-values.ts. The phase hands the extractor `callBoundMs`;+// a stored value it cannot use as written warns (key named, value never+// echoed), and the bound never outlasts the phase time left past the 90s floor.+const BOUND_KEY = 'dream.propose_takes.call_timeout_ms';++async function phaseRunWith(config: Record<string, string>, opts: { deadlineMs?: number } = {}) {+ const bounds: Array<number | undefined> = [];+ const extractor: ProposeTakesExtractor = async (input) => {+ bounds.push(input.callBoundMs);+ return [];+ };+ const result = await runPhaseProposeTakes(buildCtx(buildMockEngine(config)), { extractor, ...opts });+ const warnings = (result.details as { warnings: string[] }).warnings.filter((w) => w.includes(BOUND_KEY));+ return { bound: bounds[0], warnings, status: result.status };+}++describe('the phase resolves dream.propose_takes.call_timeout_ms into callBoundMs (#5958)', () => {+ test('an in-range whole number is passed through without a warning', async () => {+ const run = await phaseRunWith({ [BOUND_KEY]: '240000' });+ expect(run.bound).toBe(240_000);+ expect(run.warnings).toEqual([]);+ });++ test('control: unset or blank leaves the bound to the output-cap scaling, silently', async () => {+ for (const config of [{}, { [BOUND_KEY]: '' }, { [BOUND_KEY]: ' ' }]) {+ const run = await phaseRunWith(config);+ expect(run.bound).toBeUndefined();+ expect(run.warnings).toEqual([]);+ expect(run.status).not.toBe('warn');}- if (warns) expect(result.status).toBe('warn');});- test('a failed config read keeps the scaling and does not stop the phase', async () => {+ for (const raw of ['soon', '0', '-250', 'NaN']) {+ test(`unusable ${JSON.stringify(raw)} keeps the scaling and warns with the fix, not the value`, async () => {+ const run = await phaseRunWith({ [BOUND_KEY]: raw });+ expect(run.bound).toBeUndefined();+ expect(run.status).toBe('warn');+ expect(run.warnings).toHaveLength(1);+ expect(run.warnings[0]).toContain(`gbrain config set ${BOUND_KEY}`);+ expect(run.warnings[0]).toContain(`gbrain config get ${BOUND_KEY}`);+ if (raw.length > 2) expect(run.warnings[0]).not.toContain(raw);+ });+ }++ for (const [raw, held] of [['2500.9', 2_500], ['40', 1_000], ['450000', 300_000], ['9e15', 300_000]] as const) {+ test(`out-of-form ${raw} is held to ${held} with a warning`, async () => {+ const run = await phaseRunWith({ [BOUND_KEY]: raw });+ expect(run.bound).toBe(held);+ expect(run.status).toBe('warn');+ expect(run.warnings).toHaveLength(1);+ expect(run.warnings[0]).not.toContain(raw);+ });+ }++ test('an unreadable config row keeps the scaling and never fails the phase', async () => {const engine = buildMockEngine({});- const getConfig = engine.getConfig.bind(engine);+ const readOther = engine.getConfig.bind(engine);engine.getConfig = async (key: string) => {- if (key === KEY) throw new Error('config plane down');- return getConfig(key);+ if (key === BOUND_KEY) throw new Error('config table unavailable');+ return readOther(key);};- const seen: Array<number | undefined> = [];- const extractor: ProposeTakesExtractor = async (input) => {- seen.push(input.callTimeoutMs);- return [];- };- const result = await runPhaseProposeTakes(buildCtx(engine), { extractor });- expect(seen).toEqual([undefined]);+ const bounds: Array<number | undefined> = [];+ const result = await runPhaseProposeTakes(buildCtx(engine), {+ extractor: async (input) => { bounds.push(input.callBoundMs); return []; },+ });+ expect(bounds).toEqual([undefined]);expect(result.status).not.toBe('fail');});- test('the configured bound is held to the remaining phase deadline, never below the 90s default', async () => {- const seen: Array<number | undefined> = [];- const extractor: ProposeTakesExtractor = async (input) => {- seen.push(input.callTimeoutMs);- return [];- };- await runPhaseProposeTakes(buildCtx(buildMockEngine({ [KEY]: '240000' })), { extractor, deadlineMs: 150_000 });- expect(seen[0]).toBeGreaterThan(149_000);- expect(seen[0]).toBeLessThanOrEqual(150_000);- await runPhaseProposeTakes(buildCtx(buildMockEngine({ [KEY]: '240000' })), { extractor, deadlineMs: 10_000 });- expect(seen[1]).toBe(90_000);+ test('a short phase deadline caps the bound, but never below the 90s default', async () => {+ const roomy = await phaseRunWith({ [BOUND_KEY]: '280000' }, { deadlineMs: 200_000 });+ expect(roomy.bound!).toBeLessThanOrEqual(200_000);+ expect(roomy.bound!).toBeGreaterThan(199_000);+ const tight = await phaseRunWith({ [BOUND_KEY]: '280000' }, { deadlineMs: 5_000 });+ expect(tight.bound).toBe(90_000);+ });++ test('control: a bound already under the time left is not raised toward it', async () => {+ const run = await phaseRunWith({ [BOUND_KEY]: '120000' }, { deadlineMs: 900_000 });+ expect(run.bound).toBe(120_000);+ });+});++describe('the configured bound reaches the real gateway call (#5958)', () => {+ async function armedDuringPhase(config: Record<string, string>): Promise<number[]> {+ // The claude-cli shape: a clean stop every time, so no truncation retry.+ __setChatTransportForTests(async () => chatResult(GOOD_JSON, 'end'));+ const spy = spyOn(AbortSignal, 'timeout');+ try {+ const result = await runPhaseProposeTakes(buildCtx(buildMockEngine(config)), {});+ expect((result.details as { llm_calls_succeeded: number }).llm_calls_succeeded).toBe(1);+ return spy.mock.calls.map(([ms]) => ms);+ } finally {+ spy.mockRestore();+ }+ }++ test('a page that never truncates is bounded by the configured value', async () => {+ expect(await armedDuringPhase({ [BOUND_KEY]: '240000' })).toEqual([240_000]);+ });++ test('control: unset, the same page keeps the 90s base bound', async () => {+ expect(await armedDuringPhase({})).toEqual([90_000]);});});diff --git a/test/propose-takes-truncation.test.ts b/test/propose-takes-truncation.test.tsindex 527fe18818..9d81af3b43 100644--- a/test/propose-takes-truncation.test.ts+++ b/test/propose-takes-truncation.test.ts@@ -19,7 +19,7 @@* Uses the gateway chat-transport test seam — no API key, no network.*/-import { describe, test, expect, beforeEach, afterAll } from 'bun:test';+import { describe, test, expect, beforeEach, afterAll, spyOn } from 'bun:test';import {configureGateway,resetGateway,@@ -130,66 +130,112 @@ describe('defaultExtractor truncation retry (#3763)', () => {});});-// ─── per-call timeout: output-cap scaling (#5771), override (#5958) ──--/** Runs `fn` with AbortSignal.timeout spied; returns every armed timeout (ms). */-async function armedTimeouts(fn: () => Promise<unknown>): Promise<number[]> {- const timeouts: number[] = [];- const realTimeout = AbortSignal.timeout;- AbortSignal.timeout = ((ms: number) => {- timeouts.push(ms);- return realTimeout.call(AbortSignal, ms);- }) as typeof AbortSignal.timeout;- try {- await fn();- } finally {- AbortSignal.timeout = realTimeout;- }- return timeouts;-}+// ─── per-call timeout scales with the output cap (#5771) ────────────-describe('defaultExtractor per-call timeout (#5771, #5958)', () => {+describe('defaultExtractor per-call timeout scales with maxTokens (#5771)', () => {const input = {pagePath: 'companies/acme-example',pageBody: 'I bet Acme doubles ARR by Q4. They ship weekly.',existingTakes: [],};- // The first call truncates, so every case arms the base call AND the retry.- test.each([- ['base call keeps 90s; the default 4096 retry gets 180s', {}, [90_000, 180_000]],- ['a large configured retry cap is bounded at the 300s gateway ceiling, not 90s', { retryMaxTokens: 12_000 }, [90_000, 300_000]],- ['small caps never drop below the 90s floor', { maxTokens: 256, retryMaxTokens: 256 }, [90_000, 90_000]],- ['callTimeoutMs bounds both calls', { callTimeoutMs: 240_000 }, [240_000, 240_000]],- ['callTimeoutMs wins over output-cap scaling, below the default too', { callTimeoutMs: 30_000, retryMaxTokens: 12_000 }, [30_000, 30_000]],- ] as const)('%s', async (_name, extra, expected) => {+ async function timeoutsFor(extra: { maxTokens?: number; retryMaxTokens?: number }): Promise<number[]> {+ const timeouts: number[] = [];+ const realTimeout = AbortSignal.timeout;+ AbortSignal.timeout = ((ms: number) => {+ timeouts.push(ms);+ return realTimeout.call(AbortSignal, ms);+ }) as typeof AbortSignal.timeout;let calls = 0;__setChatTransportForTests(async () => {calls++;return calls === 1 ? chatResult('[{"claim_text":"Acme dou', 'length') : chatResult(GOOD_JSON, 'end');});- expect(await armedTimeouts(() => defaultExtractor({ ...input, ...extra }))).toEqual([...expected]);+ try {+ await defaultExtractor({ ...input, ...extra });+ } finally {+ AbortSignal.timeout = realTimeout;+ }+ return timeouts;+ }++ test('base call keeps 90s; the default 4096 retry gets 180s', async () => {+ expect(await timeoutsFor({})).toEqual([90_000, 180_000]);+ });++ test('a large configured retry cap is bounded at the 300s gateway ceiling, not 90s', async () => {+ expect(await timeoutsFor({ retryMaxTokens: 12_000 })).toEqual([90_000, 300_000]);+ });++ test('small caps never drop below the 90s floor', async () => {+ expect(await timeoutsFor({ maxTokens: 256, retryMaxTokens: 256 })).toEqual([90_000, 90_000]);});+});++// ─── operator per-call bound (#5958) ────────────────────────────────- test('a call its own bound stops names the bound and the key, and stays a per-page failure', async () => {- // Hangs until aborted, the way a stalled `claude -p` does.- __setChatTransportForTests((opts) => new Promise((_resolve, reject) => {- opts.abortSignal?.addEventListener('abort', () => reject(new Error('claude-cli adapter aborted')), { once: true });+describe('defaultExtractor honours an operator per-call bound (#5958)', () => {+ const page = {+ pagePath: 'companies/widget-co',+ pageBody: 'I bet Widget Co triples headcount next year.',+ existingTakes: [],+ };++ /** Every bound the extractor arms, in call order, without changing timer behaviour. */+ async function boundsArmed(run: () => Promise<unknown>): Promise<number[]> {+ const spy = spyOn(AbortSignal, 'timeout');+ try {+ await run();+ return spy.mock.calls.map(([ms]) => ms);+ } finally {+ spy.mockRestore();+ }+ }++ function truncateThenAnswer(): void {+ let n = 0;+ __setChatTransportForTests(async () => (++n === 1+ ? chatResult('[{"claim_text":"Widget', 'length')+ : chatResult(GOOD_JSON, 'end')));+ }++ test('the bound replaces the scaled one on the base call and on the retry', async () => {+ truncateThenAnswer();+ expect(await boundsArmed(() => defaultExtractor({ ...page, callBoundMs: 210_000 }))).toEqual([210_000, 210_000]);+ });++ test('a bound under 90s holds even when a large retry cap would scale to 300s', async () => {+ truncateThenAnswer();+ expect(await boundsArmed(() => defaultExtractor({ ...page, callBoundMs: 4_000, retryMaxTokens: 12_000 })))+ .toEqual([4_000, 4_000]);+ });++ test('control: without a bound the same truncating page keeps the scaled 90s then 180s', async () => {+ truncateThenAnswer();+ expect(await boundsArmed(() => defaultExtractor(page))).toEqual([90_000, 180_000]);+ });++ test('a call stopped by the bound names the page, the bound, the key and its range', async () => {+ const providerAbort = new Error('claude-cli adapter aborted');+ __setChatTransportForTests((opts) => new Promise((_ok, fail) => {+ opts.abortSignal?.addEventListener('abort', () => fail(providerAbort), { once: true });}));- const err = await defaultExtractor({ ...input, callTimeoutMs: 20 }).then(() => null, (e: unknown) => e as Error);- expect(err?.message).toContain('timed out after 20 ms');- expect(err?.message).toContain('dream.propose_takes.call_timeout_ms');- expect(err?.message).toContain('claude-cli adapter aborted');+ const err = await defaultExtractor({ ...page, callBoundMs: 30 }).catch((e: unknown) => e);+ expect(err).toBeInstanceOf(Error);+ const message = (err as Error).message;+ expect(message).toContain('companies/widget-co timed out after 30 ms');+ expect(message).toContain('claude-cli adapter aborted');+ expect(message).toContain('dream.propose_takes.call_timeout_ms to whole ms from 1000 to 300000');+ expect(message).toContain('No tombstone was written');+ expect((err as Error).cause).toBe(providerAbort);expect(classifyGlobalLlmError(err)).toBeNull();});- test('a failure before the bound keeps its own error', async () => {- __setChatTransportForTests(async () => {- throw new Error('provider exploded');- });- const err = await defaultExtractor(input).then(() => null, (e: unknown) => e as Error);- expect(err?.message).toContain('provider exploded');- expect(err?.message).not.toContain('timed out');+ test('control: a failure the bound did not cause is rethrown as the same error', async () => {+ const quota = new Error('upstream refused the request');+ __setChatTransportForTests(async () => { throw quota; });+ const err = await defaultExtractor({ ...page, callBoundMs: 60_000 }).catch((e: unknown) => e);+ expect(err).toBe(quota);});});@@ -197,16 +243,10 @@ describe('defaultExtractor per-call timeout (#5771, #5958)', () => {interface CapturedSql { sql: string; params: unknown[] }-function buildMockEngine(- pageCount: number,- config: Record<string, string> = {},-): { engine: BrainEngine; captured: CapturedSql[] } {+function buildMockEngine(pageCount: number): { engine: BrainEngine; captured: CapturedSql[] } {const captured: CapturedSql[] = [];const engine = {kind: 'pglite',- async getConfig(key: string): Promise<string | null> {- return config[key] ?? null;- },async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {captured.push({ sql, params: params ?? [] });if (sql.includes('SELECT slug, source_id, compiled_truth')) {@@ -235,21 +275,6 @@ function buildCtx(engine: BrainEngine): OperationContext {};}-describe('dream.propose_takes.call_timeout_ms reaches the extractor call (#5958)', () => {- test('a run that never truncates (the claude-cli shape) arms the configured bound, not 90s', async () => {- const { engine } = buildMockEngine(1, { 'dream.propose_takes.call_timeout_ms': '240000' });- // claude-cli ignores maxTokens and always reports a clean stop, so the- // truncation retry never fires and the base call's bound is the only one.- __setChatTransportForTests(async () => chatResult(GOOD_JSON, 'end'));- let details: Record<string, unknown> = {};- const timeouts = await armedTimeouts(async () => {- details = (await runPhaseProposeTakes(buildCtx(engine), {})).details as Record<string, unknown>;- });- expect(timeouts).toEqual([240_000]);- expect(details.llm_calls_succeeded).toBe(1);- });-});-describe('extractor failure-streak halt (#3763)', () => {test(`always-throwing extractor over N+2 pages halts at N with status 'fail' and no tombstones`, async () => {const pageCount = EXTRACTOR_FAILURE_HALT_STREAK + 2;