From 385949aa486ee97dc4912975df58c7a2c533e395 Mon Sep 17 00:00:00 2001 From: rebuildup Date: Fri, 13 Nov 2026 15:32:51 +0900 Subject: [PATCH] fix(agent): validate non-table fallback profiles and state the real spend ceiling (#152) Two review findings merged unresolved with #150. 1. `agent check` accepted a profile whose value is not a table. `parseFallbackProfile` returned null for a present-but-non-table profile, and `cmdCheck` iterated `listFallbackProfiles` (which skips exactly those keys), so a config that `agent fallback` cannot even find reported "config OK". Now a present value that is not a table throws a schema error naming the profile; a genuinely absent id still returns null. `cmdCheck` iterates every key under `[fallback_profile]` instead of the skipping helper, so the reported profile count reflects profiles actually validated. `agent fallback` on such an id already rejected it; the two paths now agree. Reproduced before the fix: [fallback_profile] / good = "this-should-be-a-table" agent check -> config OK (exit 0) agent fallback good -> agent: fallback profile not found: good (exit 2) 2. ADR-0018 overstated what a positive `max_spend` guarantees. For a positive budget, `max_spend` is a pre-execution admission check, not an enforced billing ceiling: the launcher never observes provider spend, cannot attribute cost after a candidate is handed to a harness, and cannot see a provider-side reprice. Only `global_max_spend = 0` is a hard stop (it admits only candidates that cannot bill at all). ADR-0018 and docs/agent-launcher.md now say this plainly and re-state that an account-side hard stop remains the only guaranteed ceiling. Tests: 745 pass. The non-table case is mutation-verified (reverting the guard fails the new test). All gates green. --- docs/adr/ADR-0018.md | 15 ++++++++++++++- docs/agent-launcher.md | 10 ++++++++-- script/agent.test.ts | 35 +++++++++++++++++++++++++++++++++++ script/agent.ts | 21 +++++++++++++++------ script/agent/fallback.ts | 25 ++++++++++++++++++++----- 5 files changed, 92 insertions(+), 14 deletions(-) diff --git a/docs/adr/ADR-0018.md b/docs/adr/ADR-0018.md index 3bddf5e..83d6e8c 100644 --- a/docs/adr/ADR-0018.md +++ b/docs/adr/ADR-0018.md @@ -102,7 +102,20 @@ the running total, so a budget-only check let it slip under a zero budget. Candidates whose billing can bill at all are therefore rejected outright on a zero-budget profile. Under a **positive** budget a billable candidate must declare an explicit cap, otherwise `totalSpend` counts it as 0 and any budget -admits it — the cap would only bound spend someone remembered to declare. +admits it. + +**What a positive `max_spend` does and does not guarantee.** Only +`global_max_spend = 0` is a hard stop, because it admits only candidates that +cannot bill at all. A positive cap (or a positive `global_max_spend`) is a +**pre-execution admission check, not an enforced billing ceiling**: the launcher +never observes the provider's actual spend, cannot attribute cost after a +candidate is handed to a harness, and cannot see a provider-side reprice or a +model that becomes paid mid-run. Do not read "the resolver accepted this +candidate" as "this run is capped at `max_spend`". The only guaranteed ceiling +remains an **account-side** hard stop (a spend limit that rejects requests, or +pay-as-you-go switched off) — the launcher cannot see or change those settings +and does not claim to. The same caveat applies to `openrouter-free` and every +provider whose price the launcher cannot verify. A **present** spend cap must be valid. The generic optional-integer helper mapped any malformed value to "absent", which for a cap means "uncapped", so diff --git a/docs/agent-launcher.md b/docs/agent-launcher.md index 4860ac2..828aa24 100644 --- a/docs/agent-launcher.md +++ b/docs/agent-launcher.md @@ -186,11 +186,17 @@ agent fallback opencode-requesty-quota # Requesty exhausted -> Kilo (OpenCode) agent fallback --json # redacted machine-readable form ``` -Each profile declares `global_max_spend = 0`, so the resolver's spend checks -can never authorise paid usage. Candidates are `billing = "free"` and are +Each profile declares `global_max_spend = 0`, so the resolver admits only +candidates that cannot bill at all. Candidates are `billing = "free"` and are bound to the harness of their primary route (OMP has no native Requesty or OVHcloud provider, so those cannot appear in an `omp` profile). +`global_max_spend = 0` is the **only** value that is a hard stop. A positive +`max_spend`/budget is an admission-time check, **not** an enforced billing +ceiling: the launcher never observes the provider's actual spend and cannot +attribute cost after a candidate is handed to a harness. An account-side hard +stop (a spend limit, or pay-as-you-go off) remains the only guaranteed ceiling. + The resolver is the enforcement point, not the profile author's intent. It rejects a candidate when: diff --git a/script/agent.test.ts b/script/agent.test.ts index 3356b09..582cabb 100644 --- a/script/agent.test.ts +++ b/script/agent.test.ts @@ -3331,3 +3331,38 @@ candidates = [ check(checkRun.stderr.toString().includes(needle), `${label}: ${checkRun.stderr.toString()}`); }); })); + +test("test_check_rejects_non_table_profile", withFixture((fixture) => { + // A profile key whose VALUE is not a table must fail validation. It used to + // be counted as a valid profile by `agent check` while `agent fallback` + // reported "not found" — a config that cannot work passed CI. + const base = ` +[providers.p1] +label = "P1" +base_url = "https://api.example.com" +secret = "DEEPSEEK_API_KEY" +env = "DEEPSEEK_API_KEY" +default_model = "m1" +models = ["m1"] + +[harnesses.omp] +label = "OMP" +command = "omp" +adapter = "omp" + +[routes."omp.p1"] + +[fallback_profile] +good = "this-should-be-a-table" +`; + const config = join(fixture.tmp, "nontable.toml"); + writeFileSync(config, base); + const result = fixture.run(["check"], { config }); + check(result.exitCode === 2, `expected exit 2, got ${result.exitCode}: ${result.stderr.toString()}`); + check( + result.stderr.toString().includes("fallback_profile.good") && + result.stderr.toString().includes("table expected"), + `expected a table-expected error naming the profile: ${result.stderr.toString()}`, + ); + check(!result.stderr.toString().includes("Bun v"), "no raw stack trace"); +})); diff --git a/script/agent.ts b/script/agent.ts index 37f6e6c..c8918d6 100755 --- a/script/agent.ts +++ b/script/agent.ts @@ -63,7 +63,6 @@ import { import { effectiveQuotaKey, loadCatalog, type Catalog } from "./agent/catalog"; import { buildFallbackCatalog, - listFallbackProfiles, mergeAttestations, parseFallbackProfile, resolveFallbackProfile, @@ -2520,14 +2519,24 @@ function cmdModels(config: Config, providerKey: string): number { function cmdCheck(config: Config): number { // Validate every declared fallback profile, not just the provider/route - // tables: a malformed profile (bad primary_route, bad cap, bad billing) must - // fail CI here rather than at `agent fallback` time with a stack trace. + // tables: a malformed profile (bad primary_route, bad cap, bad billing, or a + // value that is not a table at all) must fail CI here rather than at + // `agent fallback` time. let profileCount = 0; try { const parsedToml = Bun.TOML.parse(readFileSync(config.path, "utf8")) as Record; - for (const id of listFallbackProfiles(parsedToml)) { - parseFallbackProfile(parsedToml, id); - profileCount++; + // Iterate every key under [fallback_profile], not listFallbackProfiles(): + // that helper deliberately skips non-table values, which is exactly the + // case that must fail validation. + const section = parsedToml["fallback_profile"]; + if (section !== undefined && section !== null) { + if (!isPlainObject(section)) { + throw new ContractError("schema", "fallback_profile: table expected"); + } + for (const id of Object.keys(section).sort()) { + parseFallbackProfile(parsedToml, id); + profileCount++; + } } } catch (error) { if (error instanceof ContractError) { diff --git a/script/agent/fallback.ts b/script/agent/fallback.ts index bc64419..c03ade6 100644 --- a/script/agent/fallback.ts +++ b/script/agent/fallback.ts @@ -266,7 +266,11 @@ function validateProfileVersion(v: unknown, where: string): number { /** * Parse a fallback profile from the `[fallback_profile.]` table in - * config/agents.toml. Returns null if the profile doesn't exist. + * config/agents.toml. + * + * Returns `null` only when the profile is genuinely ABSENT. A profile that is + * present but not a table is a schema error and throws, so `agent check` + * cannot report a config "OK" while `agent fallback` cannot find the profile. */ export function parseFallbackProfile( toml: Record, @@ -274,11 +278,22 @@ export function parseFallbackProfile( ): FallbackProfile | null { // Bun.TOML.parse returns nested structure: { fallback_profile: { "omp-mistral-quota": {...} } } const fallbackSection = toml.fallback_profile; - if (!fallbackSection || typeof fallbackSection !== "object" || Array.isArray(fallbackSection)) return null; - const table = (fallbackSection as Record)[profileId]; - if (!table || typeof table !== "object" || Array.isArray(table)) return null; + if (fallbackSection === undefined || fallbackSection === null) return null; + if (typeof fallbackSection !== "object" || Array.isArray(fallbackSection)) { + throw new ContractError("schema", "fallback_profile: table expected"); + } + const raw = (fallbackSection as Record)[profileId]; + if (raw === undefined) return null; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + // Present but not a table: the id EXISTS, its value is wrong. Returning + // null here would be reported as "not found" and skipped by validation. + throw new ContractError( + "schema", + `fallback_profile.${profileId}: table expected (the profile is defined but is not a table)`, + ); + } - const t = table as Record; + const t = raw as Record; const key = `fallback_profile.${profileId}`; // Required fields const id = requireStr(t, "id", key);