Public: anyone can read this; the crew can change it.

An OpenAI-type account that fails during a run hands the run to the next account and says so on it #17897

opened this

Merged 25h 17m ago, live in production

scout/forge:scout/17889-an-openai-type-account-that-fails-during → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/17889-an-openai-type-account-that-fails-during was merged into main as a6a608a.

Review

Sign in to review this change.
4 files changed +195 −7
src/crew/openai_runner.ts +27 −4
@@ -32,6 +32,7 @@
3232 * is answered with every tool and its parameters, so the next turn corrects it.
3333 */
3434
35 import { background } from "../perf/jobs.ts";
3536 import { closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, statSync, writeSync } from "node:fs";
3637 import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3738 import { BUDGET_REACHED, TURNS_REACHED, type AgentDetection, type AgentOutcome, type AgentRun, type AgentRunner, type HistoryTurn } from "./agent_runner.ts";
@@ -387,6 +388,8 @@ export const OPENAI_SESSION = "openai-";
387388 export const isOpenAISession = (sessionId: string): boolean => sessionId.startsWith(OPENAI_SESSION);
388389
389390 /** Seconds a crew run waits after each 429 or 5xx before it asks again: an endpoint may say no Retry-After. */
391 /** How long an endpoint has to start answering a request before the account counts as failing. */

Non-blocking: this new doc comment and constant split the BUSY_SECONDS doc from BUSY_SECONDS. Put HEADERS_MS after BUSY_SECONDS.

392 const HEADERS_MS = 90_000;
390393 export const BUSY_SECONDS: readonly number[] = [2, 5, 15, 30, 60];
391394
392395 /** Why a picked account without a gateway does not run here. */
@@ -462,7 +465,7 @@ export function callAsText(text: string): boolean {
462465 * One run on an OpenAI-compatible endpoint. `guard` is the outbound guard's options for a person's
463466 * own connection (a test hands it a resolver); the forge's own endpoints never read it.
464467 */
465 export async function runOpenAI(run: AgentRun, config: Record<string, string | undefined> = process.env, guard: OutboundOptions = {}, busySeconds: readonly number[] = BUSY_SECONDS): Promise<AgentOutcome> {
468 export async function runOpenAI(run: AgentRun, config: Record<string, string | undefined> = process.env, guard: OutboundOptions = {}, busySeconds: readonly number[] = BUSY_SECONDS, headersMs = HEADERS_MS): Promise<AgentOutcome> {
466469 const sessionId = run.mcp !== undefined ? (run.resume ?? crypto.randomUUID()) : run.resume !== undefined && isOpenAISession(run.resume) ? run.resume : `${OPENAI_SESSION}${crypto.randomUUID()}`;
467470 let tokensIn = 0, tokensOut = 0, turns = 0, contextTokens = 0, costUsd = 0, result = "";
468471 const done = (ok: boolean, reason: string): AgentOutcome => ({
@@ -504,9 +507,29 @@ export async function runOpenAI(run: AgentRun, config: Record<string, string | u
504507 signal,
505508 };
506509 // A person's own connection is reached only through the guard, which follows no redirect.
507 const send = (): Promise<Response> =>
508 run.account?.connection?.guarded === true ? outboundFetch(`${cfg.base}/chat/completions`, { ...ask, signal }, guard) : fetch(`${cfg.base}/chat/completions`, { ...ask, signal });
509 let res = await send();
510 // An endpoint that does not answer within `headersMs` is a failing account, not the run's
511 // whole deadline spent on it: the request alone is cut, and the account is handed on from
512 // (#17889).
513 let hung = false;
514 const send = async (): Promise<Response> => {
515 const cut = new AbortController();
516 const timer = setTimeout(() => background("openai-headers", () => { hung = true; cut.abort(); }), headersMs);
517 const only = AbortSignal.any([signal, cut.signal]);
518 try {
519 return run.account?.connection?.guarded === true ? await outboundFetch(`${cfg.base}/chat/completions`, { ...ask, signal: only }, guard) : await fetch(`${cfg.base}/chat/completions`, { ...ask, signal: only });
520 } finally {
521 clearTimeout(timer);
522 }
523 };
524 let res: Response;
525 try {
526 res = await send();
527 } catch (e) {
528 if (!hung || signal.aborted || run.account?.connection === undefined || run.mcp !== undefined) throw e;
529 result = `the account's endpoint did not answer in ${Math.round(headersMs / 1000)} s`;
530 run.log(`! ${result}`);
531 return { ...done(false, "error"), limit: { said: result, refused: false } };
532 }
510533 // A crew run keeps no session, so a 429 that ended it would throw its work's thread away: it
511534 // waits and asks the same thing again. Talk answers the person at once, as before.
512535 for (const seconds of run.mcp === undefined ? busySeconds : []) {
src/crew/run_limits.ts +56 −1
@@ -6,7 +6,7 @@
66
77 import type { App } from "../app.ts";
88 import type { Run } from "../core/runs.ts";
9 import { connectionHere, PLATFORM, pickSubscription, restSubscription, type Pick } from "../core/subscriptions.ts";
9 import { connectionHere, PLATFORM, pickSubscription, restSubscription, wakeSubscription, type Pick } from "../core/subscriptions.ts";
1010 import { crewPick } from "./key_fallback.ts";
1111 import type { AgentOutcome } from "./agent_runner.ts";
1212 import {
@@ -21,6 +21,7 @@ import {
2121 takeLimit,
2222 whenText,
2323 } from "./limits.ts";
24 import { readRunLog } from "../runs/log.ts";
2425 import { pauseReason } from "./pacing.ts";
2526 import type { Outcome } from "./meter.ts";
2627 import type { SpendScope } from "./run_spend.ts";
@@ -50,6 +51,11 @@ export function limitEnding(s: LimitState): LimitEnding {
5051 // A per-minute refusal (a 429 naming no window): no account rests for it, the run waits a
5152 // minute or a few by who sent it, and the crew's own runs on that account hold a while so a
5253 // person's build gets the next minute. Plain words; the provider's are in the log.
54 // An OpenAI-type account that stays at 429 past the runner's own waits hands the run to the next
55 // account in order (#17889): it rests, so it is asked no more this run, and the cause is on the
56 // log. With nobody to take over it is not rested and the wait below is the run's.
outdated

Only a per-minute 429 is handed on here, and nothing records who this run already handed off from. Keep a per-run list of accounts handed from, skip them on the next pick, and when nobody is left after a hand-off, fail the run once with every cause listed.

57 const handed = connectionHandOff(s);
58 if (handed !== undefined) return handed;
5359 if (isRateLimited(result) && !s.aborted && perMinute(result.limit) && run.attempt < MAX_PAUSES) {
5460 const now = new Date();
5561 const at = new Date(now.getTime() + breathWait(run.attempt, run.sent));
@@ -128,3 +134,52 @@ export function limitEnding(s: LimitState): LimitEnding {
128134 write(`paused ${MAX_PAUSES} times already; not waiting again`);
129135 return { limitLifts: resumeAt(result.limit, new Date()) };
130136 }
137
138 /** The accounts this run was already handed from, and why: read back from the run's own log. */
139 function handedFrom(app: App, runId: string): Map<string, string> {
140 const out = new Map<string, string>();
141 for (const line of readRunLog(app.config.dataDir, runId).lines) {
142 const m = /^handed off: (.+?) refused \((.*)\) and rests until /.exec(line);
143 if (m !== null) out.set(m[1]!, m[2]!);
144 }
145 return out;
146 }
147
148 /**
149 * A connection's per-minute refusal, handed to the next account when one is awake: the refused
150 * account rests and the run's log says from whom, to whom and why. An account is handed from once
151 * a run (the log is the record); when no account is left after a hand-off, the run fails once with
152 * each account's cause. Absent when the run is not on a connection, was not refused that way, or
153 * nobody has been handed from and nobody may take it.
154 */
155 function connectionHandOff(s: LimitState): { readonly outcome: Outcome } | undefined {
156 const { app, run, picked, scope, result, write } = s;
157 if (picked.kind !== "ready" || picked.connection === undefined) return undefined;
158 if (!isRateLimited(result) || s.aborted || !perMinute(result.limit)) return undefined;
159 const now = new Date();
160 const was = picked.subscription;
161 const before = handedFrom(app, run.id);
162 const { until, said } = takeLimit(app.db, was.id, result.limit, result.reason, now);
163 const next = before.has(was.name) ? undefined : pickSubscription(app.db, app.config.dataDir, scope, now, undefined, crewPick(app, run.id));
164 const to = next?.kind === "env" ? "the forge's own token" : next?.kind === "ready" && next.subscription.id !== was.id && !before.has(next.subscription.name) ? next.subscription.name : undefined;
165 if (to === undefined) {
166 if (before.size === 0) {
167 wakeSubscription(app.db, was.id);
168 return undefined;
169 }
170 before.set(was.name, said);
171 const causes = [...before].map(([name, why]) => `${name}: ${why}`).join("; ");
172 write(`every account has failed this run: ${causes}`);
173 return { outcome: { state: "failed", summary: `every account failed: ${causes}`.slice(0, 500), sessionId: result.sessionId, costUsd: result.costUsd } };
174 }
175 write(`handed off: ${was.name} refused (${said}) and rests until ${whenText(until)}; ${to} takes the run`);
176 return {
177 outcome: {
178 state: "paused",
179 summary: `paused: ${pauseReason(was.name, undefined, said)}; ${to} takes over`,
180 resumeAt: now.toISOString(),
181 sessionId: result.sessionId,
182 costUsd: result.costUsd,
183 },
184 };
185 }
test/crew-openai-account.test.ts +111 −2
@@ -33,7 +33,7 @@ import { runnerFor, useRunner, type AgentRun, type AgentRunner, type RunnerLimit
3333 import { costOf, priceOf } from "../src/crew/openai_price.ts";
3434 import { effortFor, isOpenAISession, MAX_TURNS, openaiRunner, runOpenAI } from "../src/crew/openai_runner.ts";
3535 import { runAccount } from "../src/crew/runner_env.ts";
36 import { readRunLog } from "../src/runs/log.ts";
36 import { appendRunLog, readRunLog } from "../src/runs/log.ts";
3737 import { seedAdmin } from "./helpers/admin.ts";
3838 import { agentRunSettled, startStandInCrew, stopStandInCrew, type StandInCrew } from "./helpers/crew-standin.ts";
3939 import { quietLogs, withoutEnv } from "./helpers/globals.ts";
@@ -267,7 +267,7 @@ describe("a refusal, and the wait after it", () => {
267267 run: { id: "a-run", attempt, sent: false } as Run,
268268 result: { ok: false, sessionId: "s", result: "", costUsd: 0, turns, tokensIn: 0, tokensOut: 0, contextTokens: 0, contextWindow: 0, reason: "error", limit },
269269 });
270 const now = (): Pick => pickSubscription(app.db, dir, { ...scope, ownerId: alice.id }, new Date(), undefined, { fallback: false, ownToken: true });
270 const now = (ownToken = true): Pick => pickSubscription(app.db, dir, { ...scope, ownerId: alice.id }, new Date(), undefined, { fallback: false, ownToken });
271271
272272 test("a full plan beside a connection that refuses, or is spent: the run waits for the plan's reset and spends no try", () => {
273273 const plan = claude("Plan", PLAN);
@@ -288,6 +288,115 @@ describe("a refusal, and the wait after it", () => {
288288 app.db.run("DELETE FROM subscription_measure");
289289 });
290290
291 test("a 429 from the first OpenAI account hands the run to the second, once: the log names both and the cause, and the first is charged only what it answered (#17889)", async () => {
292 const serve = (status: number) => {
293 const heard: string[] = [];
294 const srv = Bun.serve({
295 port: 0, hostname: "127.0.0.1",
296 async fetch(req) {
297 heard.push(req.headers.get("authorization") ?? "");
298 if (status === 429) return new Response("slow down", { status });
299 return Response.json({ choices: [{ message: { role: "assistant", content: "done" } }], usage: { prompt_tokens: 1000, completion_tokens: 10 } });
300 },
301 });
302 return { srv, heard };
303 };
304 const one = serve(429);
305 const two = serve(200);
306 try {
307 const first = connect("First", { base: `http://127.0.0.1:${one.srv.port}/v1` });
308 const second = connect("Second", { base: `http://127.0.0.1:${two.srv.port}/v1` });
309 app.db.run("UPDATE subscription SET rank = 1 WHERE id = ?1", [first]);
310 app.db.run("UPDATE subscription SET rank = 2 WHERE id = ?1", [second]);
311 setGrants(app.db, "repo", EVERYONE, [first, second]);
312 const picked = now(false);
313 expect(named(picked)).toBe("First");
314 const account = runAccount(picked, {});
315 const run: AgentRun = {
316 binary: "", cwd: dir, prompt: "p", appendSystemPrompt: "s", model: "subq-savant-1.4", budgetUsd: 1, env: {}, account,
317 sandbox: { allowHosts: [], denyRead: [], enforced: false, readAllow: [] } as AgentRun["sandbox"],
318 timeoutMs: 20_000, log: () => {}, signal: new AbortController().signal,
319 };
320 const refused = await runOpenAI(run, {}, {}, [0]);
321 expect(refused).toMatchObject({ ok: false, reason: "rate_limited", costUsd: 0 });
322 const lines: string[] = [];
323 const handed = limitEnding({
324 app, picked, scope: { ...scope, ownerId: alice.id }, aborted: false, write: (l) => lines.push(l),
325 run: { id: "a-run", attempt: 0, sent: false } as Run, result: refused,
326 });
327 expect(handed).toMatchObject({ outcome: { state: "paused", summary: expect.stringContaining("Second takes over") } });
328 expect(lines.join("\n")).toMatch(/handed off: First refused \(429.*\) and rests until .*; Second takes the run/);
329 expect(getSubscriptionByName(app.db, "First")!.restingUntil).not.toBeNull();
330 // The next pick is the second, and it says the first was passed over with its cause.
331 const next = now(false);
332 expect(named(next)).toBe("Second");
333 expect(next.kind === "ready" && next.order?.passed.map((p) => p.name)).toEqual(["First"]);
334 const finished = await runOpenAI({ ...run, account: runAccount(next, {}) }, {}, {}, [0]);
335 expect(finished).toMatchObject({ ok: true, result: "done" });
336 expect(two.heard).toEqual([`Bearer ${SUBQ}`]);
337 expect(one.heard).toHaveLength(2);
338 } finally {
339 one.srv.stop(true);
340 two.srv.stop(true);
341 }
342 });
343
344 test("every account refused with 429: the run fails once, listing each account and its cause; an account already handed from is not handed from again (#17889)", async () => {
345 const serve = () => Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("slow down", { status: 429 }) });
346 const one = serve();
347 const two = serve();
348 try {
349 const first = connect("First", { base: `http://127.0.0.1:${one.port}/v1` });
350 const second = connect("Second", { base: `http://127.0.0.1:${two.port}/v1` });
351 app.db.run("UPDATE subscription SET rank = 1 WHERE id = ?1", [first]);
352 app.db.run("UPDATE subscription SET rank = 2 WHERE id = ?1", [second]);
353 setGrants(app.db, "repo", EVERYONE, [first, second]);
354 const runId = "all-failed-run";
355 const write = (l: string): void => appendRunLog(dir, runId, l);
356 const refuse = async (picked: Pick) => {
357 const account = runAccount(picked, {});
358 const run: AgentRun = {
359 binary: "", cwd: dir, prompt: "p", appendSystemPrompt: "s", model: "subq-savant-1.4", budgetUsd: 1, env: {}, account,
360 sandbox: { allowHosts: [], denyRead: [], enforced: false, readAllow: [] } as AgentRun["sandbox"],
361 timeoutMs: 20_000, log: () => {}, signal: new AbortController().signal,
362 };
363 const result = await runOpenAI(run, {}, {}, [0]);
364 return limitEnding({ app, picked, scope: { ...scope, ownerId: alice.id }, aborted: false, write, run: { id: runId, attempt: 0, sent: false } as Run, result });
365 };
366 expect(await refuse(now(false))).toMatchObject({ outcome: { state: "paused", summary: expect.stringContaining("Second takes over") } });
367 const ended = await refuse(now(false));
368 expect(ended).toMatchObject({ outcome: { state: "failed" } });
369 const summary = "outcome" in ended ? ended.outcome.summary : "";
370 expect(summary).toMatch(/First: 429.*; Second: 429/);
371 // Once an account was handed from, a later refusal from it hands nothing on, though another
372 // is awake.
373 app.db.run("UPDATE subscription SET resting_until = NULL");
374 const again = await refuse(now(false));
375 expect(again).toMatchObject({ outcome: { state: "failed" } });
376 expect(readRunLog(dir, runId).lines.filter((l) => l.startsWith("handed off:"))).toHaveLength(1);
377 } finally {
378 one.stop(true);
379 two.stop(true);
380 }
381 });
382
383 test("an endpoint that never answers is cut at its own limit, not the run's deadline, and is reported as a failing account (#17889)", async () => {
384 const srv = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Promise<Response>(() => {}) });
385 try {
386 setGrants(app.db, "repo", EVERYONE, [connect("Hung", { base: `http://127.0.0.1:${srv.port}/v1` })]);
387 const picked = now(false);
388 const run: AgentRun = {
389 binary: "", cwd: dir, prompt: "p", appendSystemPrompt: "s", model: "subq-savant-1.4", budgetUsd: 1, env: {}, account: runAccount(picked, {}),
390 sandbox: { allowHosts: [], denyRead: [], enforced: false, readAllow: [] } as AgentRun["sandbox"],
391 timeoutMs: 20_000, log: () => {}, signal: new AbortController().signal,
392 };
393 const out = await runOpenAI(run, {}, {}, [0], 100);
394 expect(out).toMatchObject({ ok: false, reason: "error", limit: { said: expect.stringContaining("did not answer") } });
395 } finally {
396 srv.stop(true);
397 }
398 });
399
291400 test("a connection that fails after paid turns uses the run's tries; one that never answered does not", () => {
292401 setGrants(app.db, "repo", EVERYONE, [connect("SubQ")]);
293402 const picked = pickSubscription(app.db, dir, { ...scope, ownerId: alice.id }, new Date(), undefined, { fallback: false, ownToken: false });
test/job-slices.test.ts +1
@@ -323,6 +323,7 @@ const UNTIMED: Record<string, string> = {
323323 "release-main-idle": "a one-shot timer in release/main_check_idle.ts that only resolves the sleep between a release's looks at main's running check; no work of its own; the release-wait tests inject the sleep",
324324 "deploy-permit-ceiling": "a one-shot timer armed per deploy that only aborts it and resolves the race when a deploy outlives 30 minutes; permit-ceiling.test.ts and deploy-permit-ceiling.test.ts drive it with a short ceiling",
325325 "upstream-wait": "a one-shot timer that only aborts one proxied request when its app sends no headers in 30 s; no work of its own, cleared when the headers arrive; the upstream-wait tests drive it with a short wait",
326 "openai-headers": "a one-shot timer per OpenAI request, fired only when the endpoint has not answered within HEADERS_MS: it aborts that one request (crew/openai_runner.ts); crew-openai-account.test.ts drives a silent endpoint to it",
326327 "bring-wait": "a one-shot timer that only resolves a promise when a bring's mirror is still copying after 60 s, so the answer says it is copying (actions/bring.ts, bringToWork); no work of its own; talk-bring.test.ts brings a repository that settles first",
327328 "pinned-watch": "a one-shot timer between the pinned watch's looks at a pinned deploy (actions/pinned_watch.ts WATCH.sleep); it only resolves the sleep, no work of its own; pinned-watch tests drive the watch with a short sleep",
328329 "runner-wait": "one-shot timers that only resolve a promise: a runner's claim held open, a check's look at its job each second (checks/runner_jobs.ts, runner_step.ts) and the runner program's own pauses; off unless FORGE_CHECKS_PLACEMENT=runner, and checks-runner-placement.test.ts drives all three",

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs