diff --git a/pm-stack/aggregator/src/aa.ts b/pm-stack/aggregator/src/aa.ts index 1fddb2d443..853809ffc9 100644 --- a/pm-stack/aggregator/src/aa.ts +++ b/pm-stack/aggregator/src/aa.ts @@ -1157,6 +1157,37 @@ export function aaSectionFromSupabase( }; } +/** + * Re-derive a section's current-price overlay from `prices` (#8211). + * + * The batch-bound payload (rankings, configs, thresholds, test runs, + * sources, cai, coverage, catalog membership) is untouched; only the + * two price-derived facets move: the section's `prices` list and each + * catalog entry's `rate`, recomputed through the same lookup + * `aaCatalogFromConfig` uses (full id, then bare model part). This is + * what lets a cached historical batch report current rates at serve + * time without refetching any of its batch-bound measurements: the + * overlay is batch-independent by definition (`v_current_prices`), so + * freezing it into the per-batch cache was the defect. The input + * section is not mutated. + */ +export function aaApplyPriceOverlay(section: AaSection, prices: AaPrice[]): AaSection { + const rates = catalogRates(prices); + const out: AaSection = { ...section }; + if (section.catalog) { + out.catalog = section.catalog.map((entry) => ({ + ...entry, + rate: rates.get(entry.id) ?? rates.get(`part:${normalizeModelName(modelPart(entry.id))}`) ?? null, + })); + } + if (prices.length) { + out.prices = [...prices]; + } else { + delete out.prices; + } + return out; +} + /** Structural check shared by the collector and the live source. */ export function isAaSection(v: unknown): v is AaFeedSection { if (typeof v !== "object" || v === null) return false; diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 69d08ed62e..d365e02393 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -8,8 +8,8 @@ import { createHash } from "node:crypto"; import { dirname, join } from "node:path"; import type { Config } from "../config.ts"; import { applyBoardDonePolicy, isRetiredDoneTableTitle } from "../board-policy.ts"; -import { isAaSection } from "../aa.ts"; -import { aaCacheFileName, isAaBatchCacheEntry } from "../aa-batches.ts"; +import { aaApplyPriceOverlay, isAaSection } from "../aa.ts"; +import { aaCacheFileName, aaPricesFingerprint, isAaBatchCacheEntry } from "../aa-batches.ts"; import { isBatchUuid } from "../aa-batch-sql.ts"; import { isDnsSection } from "../dns.ts"; import { @@ -1824,16 +1824,46 @@ export function liveSource( // the old catalog and coverage with no warning, so honour the // index's cache-validity flag. const staleCache = batchList.find((b) => b.importBatch === batch)?.cached === false; - provenance.aa = `live (fleet feed · historical batch ${batch.slice(0, 8)} · collected ${parsed.section.generatedAt}${staleCache ? " · awaiting rebuild" : ""})`; - return staleCache - ? { - ...parsed.section, - batches: batchList, - stale: true, - staleReason: - "this version is awaiting rebuilding — its opencode config or the current-price overlay changed since it was built", - } - : { ...parsed.section, batches: batchList }; + if (staleCache) { + provenance.aa = `live (fleet feed · historical batch ${batch.slice(0, 8)} · collected ${parsed.section.generatedAt} · awaiting rebuild)`; + return { + ...parsed.section, + batches: batchList, + stale: true, + staleReason: + "this version is awaiting rebuilding — its opencode config or the current-price overlay changed since it was built", + }; + } + // #8211: the cached payload is batch-bound, but its prices are + // the batch-independent current overlay (v_current_prices). + // When the entry was built under a different overlay than the + // feed's latest section now carries, re-derive the served + // section's prices and catalog rates from the current overlay + // instead of serving the frozen snapshot — no batch data is + // refetched. When the feed carries no current overlay to + // refresh from, frozen prices are served stale-marked, never + // silently. + const currentPrices = + feed?.aa && isAaSection(feed.aa) && feed.aa.status === "ok" ? feed.aa.prices : undefined; + if (currentPrices !== undefined) { + if ((parsed.pricesFingerprint ?? null) === aaPricesFingerprint(currentPrices)) { + provenance.aa = `live (fleet feed · historical batch ${batch.slice(0, 8)} · collected ${parsed.section.generatedAt})`; + return { ...parsed.section, batches: batchList }; + } + provenance.aa = `live (fleet feed · historical batch ${batch.slice(0, 8)} · collected ${parsed.section.generatedAt} · price overlay refreshed at serve)`; + return { ...aaApplyPriceOverlay(parsed.section, currentPrices), batches: batchList }; + } + provenance.aa = `live (fleet feed · historical batch ${batch.slice(0, 8)} · collected ${parsed.section.generatedAt})`; + if (parsed.section.prices?.length) { + return { + ...parsed.section, + batches: batchList, + stale: true, + staleReason: + "the current price overlay is unavailable in the latest feed, so this version's token prices are shown as collected and may be out of date", + }; + } + return { ...parsed.section, batches: batchList }; } } catch { // No cache file yet — fall through to the honest absent form. diff --git a/pm-stack/aggregator/test/aa-batches.test.ts b/pm-stack/aggregator/test/aa-batches.test.ts index 066ce66143..8fe65dac73 100644 --- a/pm-stack/aggregator/test/aa-batches.test.ts +++ b/pm-stack/aggregator/test/aa-batches.test.ts @@ -358,4 +358,148 @@ describe("live AA batch selection", () => { expect(html).toContain("The latest collection failed"); expect(html).toContain("rebuilding"); }); + + test("a cached batch built under an old price overlay is served with the current overlay (#8211)", async () => { + const dir = await mkdtemp(join(tmpdir(), "aa-batch-overlay-")); + const feedFile = join(dir, "fleet-feed.json"); + const priceRow = (input: number, output: number) => ({ + modelName: "openai/gpt-6-luna", + inputPer1M: input, + outputPer1M: output, + cacheReadPer1M: null, + cacheWritePer1M: null, + contextMinTokens: null, + contextMaxTokens: null, + windowKind: "flat", + }); + const oldPrices = [priceRow(1, 4)]; + const newPrices = [priceRow(9.9, 39.6)]; + const summary = (importBatch: string, latest: boolean, cached: boolean) => ({ + importBatch, + name: "workbook.xlsx", + importedAt: latest ? "2026-10-31T15:00:00Z" : "2026-10-21T10:00:00Z", + driveModifiedAt: null, + ranAt: null, + insertedCounts: null, + label: latest ? "2026-10-31 · workbook.xlsx" : "2026-10-21 · workbook.xlsx", + fingerprint: latest ? "latest" : "historical", + cached, + latest, + }); + const historical = { + ...FIXTURE_AA, + batch: B3, + prices: oldPrices, + catalog: FIXTURE_AA.catalog?.map((e) => + e.id === "openai/gpt-6-luna" + ? { + ...e, + rate: { + bands: [ + { + minTokens: null, + maxTokens: null, + input: 1, + output: 4, + cacheRead: null, + cacheWrite: null, + window: "flat", + }, + ], + windowed: false, + }, + } + : e, + ), + }; + await writeFile( + feedFile, + JSON.stringify({ + version: 1, + generatedAt: new Date().toISOString(), + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], + aa: { + ...FIXTURE_AA, + batch: B1, + prices: newPrices, + batches: [summary(B1, true, true), summary(B3, false, true)], + }, + }), + ); + const cacheDir = join(dir, "aa-batches"); + await mkdir(cacheDir); + await writeFile( + join(cacheDir, aaCacheFileName(B3)), + JSON.stringify({ + batch: B3, + configFingerprint: "config", + fingerprint: "historical", + pricesFingerprint: aaPricesFingerprint(oldPrices), + builtAt: historical.generatedAt, + section: historical, + }), + ); + + const source = liveSource(loadConfig({ PM_AGG_SOURCE: "live", PM_AGG_FEED_FILE: feedFile })); + const selected = await source.aa(B3); + if (selected?.status !== "ok") throw new Error("expected an ok section"); + expect(selected.stale).toBeUndefined(); + // The batch-bound payload is the cached one; the prices and the + // price-derived catalog rates are the current overlay's. + expect(selected.batch).toBe(B3); + expect(selected.prices).toEqual(newPrices); + const luna = selected.catalog?.find((e) => e.id === "openai/gpt-6-luna"); + expect(luna?.rate?.bands[0].input).toBe(9.9); + expect(luna?.rate?.bands[0].output).toBe(39.6); + }); + + test("a cached batch with prices is served stale when the feed has no current overlay (#8211)", async () => { + const dir = await mkdtemp(join(tmpdir(), "aa-batch-nooverlay-")); + const feedFile = join(dir, "fleet-feed.json"); + const historical = { + ...FIXTURE_AA, + batch: B3, + prices: [ + { + modelName: "openai/gpt-6-luna", + inputPer1M: 1, + outputPer1M: 4, + cacheReadPer1M: null, + cacheWritePer1M: null, + contextMinTokens: null, + contextMaxTokens: null, + windowKind: "flat", + }, + ], + }; + await writeFile( + feedFile, + JSON.stringify({ + version: 1, + generatedAt: new Date().toISOString(), + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], + }), + ); + const cacheDir = join(dir, "aa-batches"); + await mkdir(cacheDir); + await writeFile( + join(cacheDir, aaCacheFileName(B3)), + JSON.stringify({ + batch: B3, + configFingerprint: "config", + fingerprint: "historical", + pricesFingerprint: "some-old-overlay", + builtAt: historical.generatedAt, + section: historical, + }), + ); + + const source = liveSource(loadConfig({ PM_AGG_SOURCE: "live", PM_AGG_FEED_FILE: feedFile })); + const selected = await source.aa(B3); + if (selected?.status !== "ok") throw new Error("expected an ok section"); + expect(selected.stale).toBe(true); + expect(selected.staleReason).toContain("price overlay"); + }); }); diff --git a/pm-stack/aggregator/test/aa.test.ts b/pm-stack/aggregator/test/aa.test.ts index bdfcba886a..a325400b3c 100644 --- a/pm-stack/aggregator/test/aa.test.ts +++ b/pm-stack/aggregator/test/aa.test.ts @@ -15,6 +15,7 @@ import { aaPoints, caiFamily, num, + aaApplyPriceOverlay, aaSectionFromSupabase, computeAaCoverage, effortRank, @@ -601,6 +602,62 @@ describe("Coding Agent Index points (Coding agents perspective)", () => { }); }); +describe("price overlay re-derivation (#8211)", () => { + const price = (input: number, output: number): AaPrice[] => [ + { + modelName: "openai/gpt-6-luna", + inputPer1M: input, + outputPer1M: output, + cacheReadPer1M: null, + cacheWritePer1M: null, + contextMinTokens: null, + contextMaxTokens: null, + windowKind: "flat", + }, + ]; + const sectionWith = (batch: string, prices: AaPrice[]) => { + const raw = rawPayload(); + raw.batch = batch; + raw.prices = prices; + return aaSectionFromSupabase(raw, CONFIG_SNIPPET, "2026-10-26T18:05:00Z")!; + }; + + test("two cached batches with differing prices both report the refreshed overlay's rates", () => { + const oldPrices = price(1.0, 4.0); + const midPrices = price(2.0, 8.0); + const newPrices = price(3.5, 14.0); + const latest = sectionWith("8152e746-4805-4a11-9664-317b44ca9f1b", midPrices); + const historical = sectionWith("8152e746-4805-4a11-9664-317b44ca9f1c", oldPrices); + // Sanity: before the refresh, each section serves its own frozen rates. + expect(historical.prices).toEqual(oldPrices); + expect(historical.catalog?.find((e) => e.id === "openai/gpt-6-luna")?.rate?.bands[0].input).toBe(1.0); + + const refreshedLatest = aaApplyPriceOverlay(latest, newPrices); + const refreshedHistorical = aaApplyPriceOverlay(historical, newPrices); + for (const served of [refreshedLatest, refreshedHistorical]) { + expect(served.prices).toEqual(newPrices); + const luna = served.catalog?.find((e) => e.id === "openai/gpt-6-luna"); + expect(luna?.rate?.bands).toHaveLength(1); + expect(luna?.rate?.bands[0].input).toBe(3.5); + expect(luna?.rate?.bands[0].output).toBe(14.0); + } + // Batch-bound data is untouched and the inputs are not mutated. + expect(refreshedHistorical.batch).toBe(historical.batch); + expect(refreshedHistorical.rankings).toEqual(historical.rankings); + expect(refreshedHistorical.configs).toEqual(historical.configs); + expect(historical.prices).toEqual(oldPrices); + expect(historical.catalog?.find((e) => e.id === "openai/gpt-6-luna")?.rate?.bands[0].input).toBe(1.0); + expect(isAaSection(refreshedHistorical)).toBe(true); + }); + + test("an empty overlay clears prices and nulls catalog rates, like a fresh build", () => { + const section = sectionWith("8152e746-4805-4a11-9664-317b44ca9f1b", price(1.0, 4.0)); + const cleared = aaApplyPriceOverlay(section, []); + expect(cleared.prices).toBeUndefined(); + expect(cleared.catalog?.find((e) => e.id === "openai/gpt-6-luna")?.rate).toBeNull(); + }); +}); + describe("aa-explorer manifest + render", () => { test("PAGES carries the aa-explorer page with unique routes", () => { const page = PAGES.find((p) => p.id === "aa-explorer");