diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index 3634769e39..2a02e8afbd 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -76,12 +76,29 @@ // AA_OPENCODE_CONFIG_PATH (default: the repo's .opencode/opencode.jsonc). import { execFile } from "node:child_process"; import { createHash, randomUUID } from "node:crypto"; -import { access, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; +import { access, mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { dnsSectionFromRegister, dnsSectionFromRegisterJson, parseDnsRegister } from "../src/dns.ts"; -import { aaAbsent, aaSectionFromSupabase, isAaSection, type AaRawPayload } from "../src/aa.ts"; +import { + disabledProvidersFromConfig, + aaAbsent, + aaSectionFromSupabase, + isAaSection, + type AaRawPayload, +} from "../src/aa.ts"; +import { AA_BATCH_INDEX_SQL, AA_PRICES_SQL, aaPayloadSql } from "../src/aa-batch-sql.ts"; +import { + aaBatchFingerprint, + aaCacheFileName, + aaPricesFingerprint, + isAaBatchCacheEntry, + parseBatchIndex, + summarizeBatches, + type AaBatchCacheEntry, + type AaBatchIndexRow, +} from "../src/aa-batches.ts"; import { feedSectionStatus, normalizeOrchestrationSection, @@ -93,6 +110,7 @@ import { import { computeCheckoutDrift } from "../src/checkout-drift.ts"; import { assembleCollectorFeed } from "../src/feed-contract.ts"; import type { + AaBatchSummary, AaFeedSection, AaSection, DnsSection, @@ -414,86 +432,10 @@ async function resolveProjectToken(): Promise { // Test_Runs data rides as raw rows; src/aa.ts maps them by // their own header row and computes pool/catalog coverage. -const AA_SQL = ` -select jsonb_build_object( - 'batch', (select import_batch::text from ainventory.v_latest_import_batch), - 'sources', coalesce(( - select jsonb_agg(jsonb_build_object( - 'name', name, 'kind', kind, 'importedAt', imported_at, 'driveModifiedAt', drive_modified_at - ) order by id) - from ainventory.sources - where import_batch = (select import_batch from ainventory.v_latest_import_batch) - ), '[]'::jsonb), - 'rankings', coalesce(( - select jsonb_agg(jsonb_build_object( - 'rowIndex', row_index, 'testRunKey', test_run_key, 'modelVariantKey', model_variant_key, - 'family', family, 'creator', creator, 'effort', effort, - 'benchmarkVersionKey', benchmark_version_key, 'rawScore', raw_score, - 'adjustedScore', adjusted_score, 'costTask', cost_task, 'timeTaskSec', time_task_sec, - 'speedTps', speed_tps, 'qualStatus', qual_status, 'availability', availability, - 'eligible', (eligible = 1), 'intelEffPerUsd', intel_eff_per_usd, - 'usdPerUsableUnit', usd_per_usable_unit, 'pointsPerDollar', points_per_dollar, - 'pointsPerSecond', points_per_second, 'balancedValue', balanced_value, - 'smartValue', smart_value, 'speedValue', speed_value, 'rankBalanced', rank_balanced, - 'rankSmart', rank_smart, 'rankSpeed', rank_speed, 'rankIntelligence', rank_intelligence, - 'rankLowCost', rank_low_cost - ) order by rank_balanced nulls last, row_index) - from ainventory.v_rankings - ), '[]'::jsonb), - 'thresholds', coalesce(( - select jsonb_agg(jsonb_build_object( - 'testRunKey', test_run_key, 'target', target, 'usable', (usable = 1), - 'levelledScore', levelled_score, 'costTask', cost_task, 'timeMin', time_min, - 'usdPerUsablePoint', usd_per_usable_point - ) order by test_run_key, target) - from ainventory.v_threshold_metrics - ), '[]'::jsonb), - 'configs', coalesce(( - select jsonb_agg(jsonb_build_object( - 'modelName', model_name, 'benchmark', benchmark, 'effort', effort, - 'intelligence', value_num, 'costPerTaskUsd', cost_per_task_usd, 'speedTps', speed_tps - ) order by model_name, effort) - from ainventory.benchmark_results br - where br.import_batch = (select import_batch from ainventory.v_latest_import_batch) - and br.benchmark like 'AA Intelligence Index%' - and br.metric = 'intelligence_index' - ), '[]'::jsonb), - 'testRunRows', coalesce(( - select jsonb_agg(jsonb_build_object('rowIndex', row_index, 'cells', data->'cells') order by row_index) - from ainventory.sheet_rows sr - where sr.import_batch = (select import_batch from ainventory.v_latest_import_batch) - and sr.sheet_name = 'Test_Runs' - ), '[]'::jsonb), - 'cai', coalesce(( - select jsonb_agg(jsonb_build_object( - 'modelName', model_name, 'effort', effort, 'version', raw->>'benchmark_version', - 'score', value_num, 'cost', cost_per_task_usd, - 'wallSec', nullif(raw->>'time_per_task_seconds', '')::numeric, - 'tokensPerTask', nullif(raw->>'token_usage_per_task', '')::numeric, - 'harness', raw->>'agent_harness', - 'creatorSlug', split_part(raw->>'observation_key', '|', 3), - 'deepSwe', nullif(raw->>'deep_swe_v1_1_pct', '')::numeric, - 'terminalBench', nullif(raw->>'terminal_bench_4_0_pct', '')::numeric, - 'sweAtlas', nullif(raw->>'swe_atlas_qna_pct', '')::numeric, - 'snapshotDate', nullif(raw->>'snapshot_date', ''), 'sourceUrl', nullif(raw->>'source_url', '') - ) order by value_num desc nulls last, model_name) - from ainventory.benchmark_results br - where br.import_batch = (select import_batch from ainventory.v_latest_import_batch) - and br.benchmark like 'Artificial Analysis Coding Agent Index%' - and br.metric = 'cai_index_score' - ), '[]'::jsonb), - 'prices', coalesce(( - select jsonb_agg(jsonb_build_object( - 'modelName', model_name, 'inputPer1M', input_usd_per_1m, 'outputPer1M', output_usd_per_1m, - 'cacheReadPer1M', cached_input_usd_per_1m, 'cacheWritePer1M', cache_write_usd_per_1m, - 'contextMinTokens', context_min_tokens, 'contextMaxTokens', context_max_tokens, - 'windowKind', window_kind - ) order by model_name, context_min_tokens nulls first) - from ainventory.v_current_prices - ), '[]'::jsonb) -) as aa`; - -const AA_BATCH_SQL = `select import_batch::text as batch from ainventory.v_latest_import_batch`; +// The AA payload SQL is generated per selected batch by src/aa-batch-sql.ts +// (#3302): the v_rankings / v_threshold_metrics bodies are copied verbatim +// from ainventory with only their latest-batch CTE parameterized, so the +// default (latest) query returns exactly what it did before. /** * The last-good AA section store (code#3332): kept beside the feed so a @@ -503,10 +445,18 @@ const AA_BATCH_SQL = `select import_batch::text as batch from ainventory.v_lates * changes and reused untouched while neither does. */ const aaLastGoodPath = join(dirname(outPath), "aa-last-good.json"); +/** Per-batch payload cache (#3302), beside the feed. */ +const aaBatchDir = join(dirname(outPath), "aa-batches"); +/** How many missing historical payloads one tick may build. The latest is + * always fresh; history fills in over ticks so no single run storms the + * Management API (#3332). */ +const AA_HISTORICAL_BUILDS_PER_TICK = 2; interface AaLastGood { batch: string; configFingerprint: string; + /** sha256 of the batch-bound semantic data (aa-batches.ts). */ + fingerprint?: string; section: AaSection; } @@ -515,7 +465,12 @@ async function readAaLastGood(): Promise { const parsed = JSON.parse(await readFile(aaLastGoodPath, "utf8")) as Partial; if (typeof parsed.batch !== "string" || typeof parsed.configFingerprint !== "string") return null; if (!isAaSection(parsed.section) || parsed.section.status !== "ok") return null; - return { batch: parsed.batch, configFingerprint: parsed.configFingerprint, section: parsed.section }; + return { + batch: parsed.batch, + configFingerprint: parsed.configFingerprint, + fingerprint: typeof parsed.fingerprint === "string" ? parsed.fingerprint : undefined, + section: parsed.section, + }; } catch { return null; } @@ -531,6 +486,31 @@ async function writeAaLastGood(entry: AaLastGood): Promise { } } +async function readAaBatchCache(batch: string): Promise { + try { + const parsed: unknown = JSON.parse(await readFile(join(aaBatchDir, aaCacheFileName(batch)), "utf8")); + if (!isAaBatchCacheEntry(parsed) || parsed.batch !== batch) return null; + if (!isAaSection(parsed.section) || parsed.section.status !== "ok") return null; + return parsed; + } catch { + return null; + } +} + +async function writeAaBatchCache(entry: AaBatchCacheEntry): Promise { + try { + await mkdir(aaBatchDir, { recursive: true }); + const path = join(aaBatchDir, aaCacheFileName(entry.batch)); + const tmp = `${path}.tmp`; + await writeFile(tmp, JSON.stringify(entry)); + await rename(tmp, path); + return true; + } catch (err) { + console.error(`collector: AA batch cache write failed (${err instanceof Error ? err.message : "error"})`); + return false; + } +} + /** The coverage half of the AA section is computed from the opencode * config, so the reuse key includes the config's fingerprint. */ async function opencodeConfigFingerprint(): Promise { @@ -553,17 +533,68 @@ async function supabaseQuery(token: string, ref: string, sql: string): Promise { + const raw = aaRawFromRows(await supabaseQuery(token, ref, aaPayloadSql(batch))); + if (!raw) throw new Error("Supabase returned no AA payload"); + return raw; +} + /** * Build the AA feed section. Fail-soft like every other section: a * failed build degrades to the last good payload with a stale marker * (code#3332), or to the absent form when no good payload exists yet, * so the dashboard explains the gap. The management token is only ever * sent to api.supabase.com and is never logged or written to the feed. + * + * #3302: the index comes from ainventory.sources (complete); each batch + * payload is cached under aa-batches/. The latest batch is refreshed + * every tick, history fills in at a bounded rate, and the default + * section is byte-compatible with the pre-#3302 latest payload. */ async function collectAaSection(generatedAt: string): Promise { const lastGood = await readAaLastGood(); + const fingerprint = await opencodeConfigFingerprint(); const degrade = (reason: string): AaFeedSection => lastGood ? { ...lastGood.section, stale: true, staleReason: reason } : aaAbsent(reason, generatedAt); + // Batch-independent config reads, done once for every assembly. + let configText: string | null = null; + try { + configText = await readFile(opencodeConfigPath, "utf8"); + } catch { + console.error("collector: opencode.jsonc unreadable; AA coverage omitted this run"); + } + // #4544: the sync-models-owned provider catalogs live in the runtime + // overlay; read it when present so AA coverage sees the effective config. + let runtimeText: string | null = null; + try { + runtimeText = await readFile(opencodeRuntimeConfigPath, "utf8"); + } catch { + runtimeText = null; + } + + const cacheMeta = new Map(); + const assemble = async (raw: AaRawPayload): Promise => { + const section = aaSectionFromSupabase(raw, configText, generatedAt, runtimeText); + if (!section) return null; + const contentFingerprint = aaBatchFingerprint(raw); + const cached = await writeAaBatchCache({ + batch: section.batch, + configFingerprint: fingerprint, + fingerprint: contentFingerprint, + pricesFingerprint: aaPricesFingerprint(section.prices ?? []), + builtAt: generatedAt, + section, + }); + cacheMeta.set(section.batch, { fingerprint: contentFingerprint, cached }); + return section; + }; + const token = await resolveBwsSecret("supabase.muse-dev2.access-token-muse-cli"); if (!token) return degrade("no Supabase management token available (bws)"); // Project ref: env override, else the Bitwarden supabase.muse-dev2.project-ref @@ -573,51 +604,120 @@ async function collectAaSection(generatedAt: string): Promise { process.env.SUPABASE_PROJECT_REF ?? (await resolveBwsSecret("supabase.muse-dev2.project-ref")) ?? "keihfchslgjetkmnmzra"; - const fingerprint = await opencodeConfigFingerprint(); - // Cheap batch probe first (code#3332): the payload only changes on a - // new import or a config change, so most ticks reuse the last good - // section instead of re-running the full payload query — the query - // pressure was itself causing intermittent Management API 403s. + + // The workbook index is the complete sources register; ingest_batches is + // optional metadata and a missing join row does not hide a batch. + let index: AaBatchIndexRow[]; try { - const rows = (await supabaseQuery(token, ref, AA_BATCH_SQL)) as { batch?: unknown }[]; - const batchNow = Array.isArray(rows) && typeof rows[0]?.batch === "string" ? rows[0].batch : null; - if (batchNow && lastGood && batchNow === lastGood.batch && fingerprint === lastGood.configFingerprint) { - console.error("collector: AA section reused (import batch + config unchanged)"); - return lastGood.section; - } - } catch { - // Probe failed — fall through to the full query, which produces - // the authoritative result or the degrade reason. + const rows = (await supabaseQuery(token, ref, AA_BATCH_INDEX_SQL)) as { batches?: unknown }[]; + index = parseBatchIndex(Array.isArray(rows) ? rows[0]?.batches : null); + } catch (err) { + const msg = err instanceof Error ? err.message : "error"; + return degrade(msg.startsWith("Supabase query failed") ? msg : `Supabase unreachable (${msg})`); } - let raw: AaRawPayload; + if (index.length === 0) return degrade("no workbook batches in ainventory.sources"); + + // The current-price overlay, hashed once per tick: it is the + // validity key for every cached section's prices and price-derived + // catalog (#3302 review). A price-only change — no new workbook, + // no config change — must still rebuild the caches, because the + // page presents these prices as current. + let currentPricesFingerprint: string; try { - const rows = (await supabaseQuery(token, ref, AA_SQL)) as { aa?: unknown }[]; - if (!Array.isArray(rows) || typeof rows[0]?.aa !== "object" || rows[0].aa === null) { - return degrade("Supabase returned no AA payload"); - } - raw = rows[0].aa as AaRawPayload; + const rows = (await supabaseQuery(token, ref, AA_PRICES_SQL)) as { prices?: unknown }[]; + currentPricesFingerprint = aaPricesFingerprint(Array.isArray(rows) ? rows[0]?.prices : null); } catch (err) { const msg = err instanceof Error ? err.message : "error"; return degrade(msg.startsWith("Supabase query failed") ? msg : `Supabase unreachable (${msg})`); } - let configText: string | null = null; - try { - configText = await readFile(opencodeConfigPath, "utf8"); - } catch { - console.error("collector: opencode.jsonc unreadable; AA coverage omitted this run"); + + // Read every batch cache once; a changed config — or a changed + // current-price overlay — invalidates all of them. + const cachedSections = new Map(); + for (const row of index) { + const cached = await readAaBatchCache(row.importBatch); + if ( + cached && + cached.configFingerprint === fingerprint && + (cached.pricesFingerprint ?? null) === currentPricesFingerprint + ) { + cacheMeta.set(row.importBatch, { fingerprint: cached.fingerprint, cached: true }); + cachedSections.set(row.importBatch, cached.section); + } else { + cacheMeta.set(row.importBatch, { fingerprint: cached?.fingerprint ?? null, cached: false }); + } } - // #4544: the sync-models-owned provider catalogs live in the runtime - // overlay; read it when present so AA coverage sees the effective config. - let runtimeText: string | null = null; - try { - runtimeText = await readFile(opencodeRuntimeConfigPath, "utf8"); - } catch { - runtimeText = null; + const latestBatch = index[0]?.importBatch ?? null; + + let latestSection: AaSection | null = null; + if (latestBatch && cachedSections.has(latestBatch)) { + latestSection = cachedSections.get(latestBatch) ?? null; + } else if ( + latestBatch && + lastGood && + lastGood.batch === latestBatch && + lastGood.configFingerprint === fingerprint && + lastGood.fingerprint + ) { + // Reuse the last good latest section without re-running the full query. + latestSection = lastGood.section; + const cached = await writeAaBatchCache({ + batch: latestBatch, + configFingerprint: fingerprint, + fingerprint: lastGood.fingerprint, + pricesFingerprint: aaPricesFingerprint(lastGood.section.prices ?? []), + builtAt: latestSection.generatedAt, + section: latestSection, + }); + cacheMeta.set(latestBatch, { fingerprint: lastGood.fingerprint, cached }); + } else if (latestBatch) { + try { + latestSection = await assemble(await fetchAaPayload(token, ref, latestBatch)); + if (!latestSection) return degrade("Supabase payload failed its structural check"); + } catch (err) { + const msg = err instanceof Error ? err.message : "error"; + return degrade(msg.startsWith("Supabase query failed") ? msg : `Supabase unreachable (${msg})`); + } } - const section = aaSectionFromSupabase(raw, configText, generatedAt, runtimeText); - if (!section) return degrade("Supabase payload failed its structural check"); - await writeAaLastGood({ batch: section.batch, configFingerprint: fingerprint, section }); - return section; + if (!latestSection) return degrade("no AA payload for the latest workbook batch"); + + await writeAaLastGood({ + batch: latestSection.batch, + configFingerprint: fingerprint, + fingerprint: cacheMeta.get(latestSection.batch)?.fingerprint ?? undefined, + section: latestSection, + }); + + // Build a bounded number of missing historical payloads per tick. The + // budget is consumed before each fetch, so a failing or unassemblable + // batch still counts against the tick limit — an upstream outage can + // never turn this loop into an unbounded run of 60 s queries. + let attempts = 0; + for (const row of index) { + if (attempts >= AA_HISTORICAL_BUILDS_PER_TICK) break; + if (row.importBatch === latestSection.batch) continue; + if (cacheMeta.get(row.importBatch)?.cached) continue; + attempts++; + try { + await assemble(await fetchAaPayload(token, ref, row.importBatch)); + } catch (err) { + console.error(`collector: AA historical batch build failed (${err instanceof Error ? err.message : "error"})`); + } + } + + const batches: AaBatchSummary[] = summarizeBatches(index, cacheMeta); + const withIndex: AaSection = { ...latestSection, batches }; + // #3302 review: the last-good payload must carry the selector index. + // Re-writing it after the index exists means a later transient failure + // degrades to a page that still offers every cached version, instead + // of silently losing the picker until the next successful collection. + await writeAaLastGood({ + batch: withIndex.batch, + configFingerprint: fingerprint, + fingerprint: cacheMeta.get(withIndex.batch)?.fingerprint ?? undefined, + section: withIndex, + }); + return withIndex; } async function main(): Promise { diff --git a/pm-stack/aggregator/src/aa-batch-sql.ts b/pm-stack/aggregator/src/aa-batch-sql.ts new file mode 100644 index 0000000000..920a0eb627 --- /dev/null +++ b/pm-stack/aggregator/src/aa-batch-sql.ts @@ -0,0 +1,635 @@ +// Parameterized AA payload SQL for a selected ainventory import batch (#3302). +// +// The live ainventory views v_rankings and v_threshold_metrics each pin +// v_latest_workbook_batch in their opening `batch` CTE, so filtering around +// them still returns the latest batch. The two bodies below are verbatim +// copies of those view definitions (read read-only from pg_views on +// 2026-11-03; see the parity test in test/aa-batches.test.ts) with only that +// CTE replaced by the selected batch. The maths is untouched. +// +// A null batch keeps the default latest behaviour by substituting the same +// `v_latest_import_batch` subselect the collector used before this module. +// A uuid is emitted as a validated SQL literal, never as user text. + +const BATCH_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +export function isBatchUuid(value: unknown): value is string { + return typeof value === "string" && BATCH_UUID_RE.test(value); +} + +/** The batch expression the payload is scoped to: latest when null. */ +export function batchExpression(batch: string | null): string { + if (batch === null) return "(select import_batch from ainventory.v_latest_import_batch)"; + if (!isBatchUuid(batch)) throw new Error("aa payload: invalid batch uuid"); + return `'${batch}'::uuid`; +} + +// --- verbatim ainventory view bodies, batch CTE parameterized --------------- + +const RANKINGS_BODY = ` +WITH batch AS (SELECT {{BATCH}}::uuid AS import_batch), ctrl AS ( + SELECT max( + CASE + WHEN (sr.row_index = 7) THEN (NULLIF(((sr.data -> 'cells'::text) ->> 2), ''::text))::numeric + ELSE NULL::numeric + END) AS target, + max( + CASE + WHEN (sr.row_index = 8) THEN (NULLIF(((sr.data -> 'cells'::text) ->> 2), ''::text))::numeric + ELSE NULL::numeric + END) AS intel_weight, + max( + CASE + WHEN (sr.row_index = 9) THEN (NULLIF(((sr.data -> 'cells'::text) ->> 2), ''::text))::numeric + ELSE NULL::numeric + END) AS speed_weight, + max( + CASE + WHEN (sr.row_index = 10) THEN ((sr.data -> 'cells'::text) ->> 2) + ELSE NULL::text + END) AS status_filter, + max( + CASE + WHEN (sr.row_index = 11) THEN ((sr.data -> 'cells'::text) ->> 2) + ELSE NULL::text + END) AS availability_filter, + max( + CASE + WHEN (sr.row_index = 12) THEN ((sr.data -> 'cells'::text) ->> 2) + ELSE NULL::text + END) AS benchmark_version + FROM ainventory.sheet_rows sr, + batch b + WHERE ((sr.sheet_name = 'Controls'::text) AND (sr.import_batch = b.import_batch)) + ), bv AS ( + SELECT ((sr.data -> 'cells'::text) ->> 0) AS benchmark_version_key, + (NULLIF(((sr.data -> 'cells'::text) ->> 8), ''::text))::numeric AS cumulative_factor + FROM ainventory.sheet_rows sr, + batch b + WHERE ((sr.sheet_name = 'Benchmark_Versions'::text) AND (sr.import_batch = b.import_batch) AND (sr.row_index >= 2) AND (COALESCE(((sr.data -> 'cells'::text) ->> 0), ''::text) <> ''::text)) + ), rk_raw AS ( + SELECT sr.row_index, + ((sr.data -> 'cells'::text) ->> 0) AS test_run_key, + ((sr.data -> 'cells'::text) ->> 1) AS model_variant_key, + ((sr.data -> 'cells'::text) ->> 2) AS family, + ((sr.data -> 'cells'::text) ->> 3) AS creator, + ((sr.data -> 'cells'::text) ->> 4) AS effort, + ((sr.data -> 'cells'::text) ->> 5) AS benchmark_version_key, + (NULLIF(((sr.data -> 'cells'::text) ->> 6), ''::text))::numeric AS raw_score, + (NULLIF(((sr.data -> 'cells'::text) ->> 9), ''::text))::numeric AS cost_task, + (NULLIF(((sr.data -> 'cells'::text) ->> 10), ''::text))::numeric AS time_task_sec, + (NULLIF(((sr.data -> 'cells'::text) ->> 11), ''::text))::numeric AS speed_tps, + ((sr.data -> 'cells'::text) ->> 12) AS qual_status, + ((sr.data -> 'cells'::text) ->> 13) AS availability, + c.target, + c.intel_weight, + c.speed_weight, + c.status_filter, + c.availability_filter, + c.benchmark_version + FROM ainventory.sheet_rows sr, + (batch b + CROSS JOIN ctrl c) + WHERE ((sr.sheet_name = 'Rankings'::text) AND (sr.import_batch = b.import_batch) AND (sr.row_index >= 4) AND (COALESCE(((sr.data -> 'cells'::text) ->> 0), ''::text) <> ''::text)) + ), base AS ( + SELECT r.row_index, + r.test_run_key, + r.model_variant_key, + r.family, + r.creator, + r.effort, + r.benchmark_version_key, + r.raw_score, + r.cost_task, + r.time_task_sec, + r.speed_tps, + r.qual_status, + r.availability, + r.target, + r.intel_weight, + r.speed_weight, + r.status_filter, + r.availability_filter, + r.benchmark_version, + COALESCE(bv.cumulative_factor, (1)::numeric) AS version_level_factor + FROM (rk_raw r + LEFT JOIN bv ON ((bv.benchmark_version_key = r.benchmark_version_key))) + ), calc AS ( + SELECT base.row_index, + base.test_run_key, + base.model_variant_key, + base.family, + base.creator, + base.effort, + base.benchmark_version_key, + base.raw_score, + base.cost_task, + base.time_task_sec, + base.speed_tps, + base.qual_status, + base.availability, + base.target, + base.intel_weight, + base.speed_weight, + base.status_filter, + base.availability_filter, + base.benchmark_version, + base.version_level_factor, + CASE + WHEN (base.raw_score IS NULL) THEN NULL::numeric + ELSE (base.raw_score * base.version_level_factor) + END AS adjusted_score, + CASE + WHEN (COALESCE(base.benchmark_version_key, ''::text) <> COALESCE(base.benchmark_version, ''::text)) THEN 0 + WHEN ((base.status_filter = 'Contender'::text) AND (COALESCE(base.qual_status, ''::text) <> 'Contender'::text)) THEN 0 + WHEN ((base.status_filter = 'Contender+Close'::text) AND (COALESCE(base.qual_status, ''::text) <> ALL (ARRAY['Contender'::text, 'Close'::text]))) THEN 0 + WHEN ((base.availability_filter = 'Current'::text) AND (COALESCE(base.availability, ''::text) <> ALL (ARRAY['yes'::text, 'limited'::text]))) THEN 0 + ELSE 1 + END AS eligible + FROM base + ), calc2 AS ( + SELECT calc.row_index, + calc.test_run_key, + calc.model_variant_key, + calc.family, + calc.creator, + calc.effort, + calc.benchmark_version_key, + calc.raw_score, + calc.cost_task, + calc.time_task_sec, + calc.speed_tps, + calc.qual_status, + calc.availability, + calc.target, + calc.intel_weight, + calc.speed_weight, + calc.status_filter, + calc.availability_filter, + calc.benchmark_version, + calc.version_level_factor, + calc.adjusted_score, + calc.eligible, + CASE + WHEN (calc.adjusted_score IS NULL) THEN NULL::numeric + ELSE (calc.adjusted_score - (calc.target - (1)::numeric)) + END AS usable_units, + calc.target AS target_value + FROM calc + ), calc3 AS ( + SELECT calc2.row_index, + calc2.test_run_key, + calc2.model_variant_key, + calc2.family, + calc2.creator, + calc2.effort, + calc2.benchmark_version_key, + calc2.raw_score, + calc2.cost_task, + calc2.time_task_sec, + calc2.speed_tps, + calc2.qual_status, + calc2.availability, + calc2.target, + calc2.intel_weight, + calc2.speed_weight, + calc2.status_filter, + calc2.availability_filter, + calc2.benchmark_version, + calc2.version_level_factor, + calc2.adjusted_score, + calc2.eligible, + calc2.usable_units, + calc2.target_value, + CASE + WHEN ((calc2.eligible = 0) OR (calc2.usable_units IS NULL) OR (calc2.usable_units <= (0)::numeric) OR (calc2.cost_task IS NULL) OR (calc2.cost_task = (0)::numeric)) THEN NULL::numeric + ELSE (calc2.usable_units / calc2.cost_task) + END AS intel_eff_per_usd, + CASE + WHEN ((calc2.eligible = 0) OR (calc2.usable_units IS NULL) OR (calc2.usable_units <= (0)::numeric) OR (calc2.cost_task IS NULL)) THEN NULL::numeric + ELSE (calc2.cost_task / calc2.usable_units) + END AS usd_per_usable_unit, + CASE + WHEN ((calc2.eligible = 0) OR (calc2.usable_units IS NULL) OR (calc2.usable_units <= (0)::numeric) OR (calc2.cost_task IS NULL) OR (calc2.cost_task = (0)::numeric) OR (calc2.time_task_sec IS NULL) OR (calc2.time_task_sec = (0)::numeric)) THEN NULL::numeric + ELSE (calc2.usable_units / (calc2.cost_task * (calc2.time_task_sec / (60)::numeric))) + END AS speed_eff_per_usd_minute + FROM calc2 + ), normed AS ( + SELECT calc3.row_index, + calc3.test_run_key, + calc3.model_variant_key, + calc3.family, + calc3.creator, + calc3.effort, + calc3.benchmark_version_key, + calc3.raw_score, + calc3.cost_task, + calc3.time_task_sec, + calc3.speed_tps, + calc3.qual_status, + calc3.availability, + calc3.target, + calc3.intel_weight, + calc3.speed_weight, + calc3.status_filter, + calc3.availability_filter, + calc3.benchmark_version, + calc3.version_level_factor, + calc3.adjusted_score, + calc3.eligible, + calc3.usable_units, + calc3.target_value, + calc3.intel_eff_per_usd, + calc3.usd_per_usable_unit, + calc3.speed_eff_per_usd_minute, + CASE + WHEN ((calc3.eligible = 0) OR (calc3.adjusted_score IS NULL)) THEN NULL::numeric + ELSE (calc3.adjusted_score / max(calc3.adjusted_score) FILTER (WHERE (calc3.eligible = 1)) OVER ()) + END AS abs_intel_norm, + CASE + WHEN ((calc3.eligible = 0) OR (calc3.speed_tps IS NULL)) THEN NULL::numeric + ELSE (calc3.speed_tps / max(calc3.speed_tps) FILTER (WHERE (calc3.eligible = 1)) OVER ()) + END AS abs_speed_norm, + CASE + WHEN ((calc3.eligible = 0) OR (calc3.cost_task IS NULL)) THEN NULL::numeric + ELSE (min(calc3.cost_task) FILTER (WHERE ((calc3.eligible = 1) AND (calc3.cost_task > (0)::numeric))) OVER () / calc3.cost_task) + END AS cost_norm, + CASE + WHEN (calc3.intel_eff_per_usd IS NULL) THEN NULL::numeric + ELSE (calc3.intel_eff_per_usd / max(calc3.intel_eff_per_usd) FILTER (WHERE (calc3.eligible = 1)) OVER ()) + END AS intel_eff_norm, + CASE + WHEN (calc3.speed_eff_per_usd_minute IS NULL) THEN NULL::numeric + ELSE (calc3.speed_eff_per_usd_minute / max(calc3.speed_eff_per_usd_minute) FILTER (WHERE (calc3.eligible = 1)) OVER ()) + END AS speed_eff_norm + FROM calc3 + ), valued AS ( + SELECT normed.row_index, + normed.test_run_key, + normed.model_variant_key, + normed.family, + normed.creator, + normed.effort, + normed.benchmark_version_key, + normed.raw_score, + normed.cost_task, + normed.time_task_sec, + normed.speed_tps, + normed.qual_status, + normed.availability, + normed.target, + normed.intel_weight, + normed.speed_weight, + normed.status_filter, + normed.availability_filter, + normed.benchmark_version, + normed.version_level_factor, + normed.adjusted_score, + normed.eligible, + normed.usable_units, + normed.target_value, + normed.intel_eff_per_usd, + normed.usd_per_usable_unit, + normed.speed_eff_per_usd_minute, + normed.abs_intel_norm, + normed.abs_speed_norm, + normed.cost_norm, + normed.intel_eff_norm, + normed.speed_eff_norm, + CASE + WHEN ((normed.intel_eff_norm IS NULL) OR (normed.speed_eff_norm IS NULL)) THEN NULL::numeric + ELSE sqrt((normed.intel_eff_norm * normed.speed_eff_norm)) + END AS balanced_value, + CASE + WHEN ((normed.intel_eff_norm IS NULL) OR (normed.speed_eff_norm IS NULL)) THEN NULL::numeric + ELSE (power(normed.intel_eff_norm, normed.intel_weight) * power(normed.speed_eff_norm, normed.speed_weight)) + END AS smart_value, + CASE + WHEN ((normed.intel_eff_norm IS NULL) OR (normed.speed_eff_norm IS NULL)) THEN NULL::numeric + ELSE (power(normed.intel_eff_norm, normed.speed_weight) * power(normed.speed_eff_norm, normed.intel_weight)) + END AS speed_value, + CASE + WHEN ((normed.abs_intel_norm IS NULL) OR (normed.abs_speed_norm IS NULL)) THEN NULL::numeric + ELSE sqrt((normed.abs_intel_norm * normed.abs_speed_norm)) + END AS speed_x_intel, + CASE + WHEN ((normed.adjusted_score IS NULL) OR (normed.cost_task IS NULL) OR (normed.cost_task = (0)::numeric)) THEN NULL::numeric + ELSE (normed.adjusted_score / normed.cost_task) + END AS points_per_dollar, + CASE + WHEN ((normed.adjusted_score IS NULL) OR (normed.time_task_sec IS NULL) OR (normed.time_task_sec = (0)::numeric)) THEN NULL::numeric + ELSE (normed.adjusted_score / normed.time_task_sec) + END AS points_per_second + FROM normed + ) + SELECT row_index, + test_run_key, + model_variant_key, + family, + creator, + effort, + benchmark_version_key, + raw_score, + version_level_factor, + adjusted_score, + cost_task, + time_task_sec, + speed_tps, + qual_status, + availability, + eligible, + target_value AS target, + usable_units, + intel_eff_per_usd, + usd_per_usable_unit, + speed_eff_per_usd_minute, + abs_intel_norm, + abs_speed_norm, + cost_norm, + intel_eff_norm, + speed_eff_norm, + balanced_value, + smart_value, + speed_value, + speed_x_intel, + points_per_dollar, + points_per_second, + CASE + WHEN (balanced_value IS NULL) THEN NULL::bigint + ELSE ((rank() OVER (ORDER BY balanced_value DESC NULLS LAST) + row_number() OVER (PARTITION BY balanced_value ORDER BY row_index)) - 1) + END AS rank_balanced, + CASE + WHEN (smart_value IS NULL) THEN NULL::bigint + ELSE ((rank() OVER (ORDER BY smart_value DESC NULLS LAST) + row_number() OVER (PARTITION BY smart_value ORDER BY row_index)) - 1) + END AS rank_smart, + CASE + WHEN (speed_value IS NULL) THEN NULL::bigint + ELSE ((rank() OVER (ORDER BY speed_value DESC NULLS LAST) + row_number() OVER (PARTITION BY speed_value ORDER BY row_index)) - 1) + END AS rank_speed, + CASE + WHEN ((eligible = 0) OR (adjusted_score IS NULL)) THEN NULL::bigint + ELSE ((rank() OVER (PARTITION BY eligible ORDER BY adjusted_score DESC NULLS LAST) + row_number() OVER (PARTITION BY eligible, adjusted_score ORDER BY row_index)) - 1) + END AS rank_intelligence, + CASE + WHEN ((eligible = 0) OR (speed_tps IS NULL)) THEN NULL::bigint + ELSE ((rank() OVER (PARTITION BY eligible ORDER BY speed_tps DESC NULLS LAST) + row_number() OVER (PARTITION BY eligible, speed_tps ORDER BY row_index)) - 1) + END AS rank_abs_speed, + CASE + WHEN ((eligible = 0) OR (cost_task IS NULL) OR (cost_task = (0)::numeric)) THEN NULL::bigint + ELSE ((rank() OVER (PARTITION BY ((eligible = 1) AND (cost_task > (0)::numeric)) ORDER BY cost_task) + row_number() OVER (PARTITION BY ((eligible = 1) AND (cost_task > (0)::numeric)), cost_task ORDER BY row_index)) - 1) + END AS rank_low_cost + FROM valued`; + +const THRESHOLD_BODY = ` +WITH batch AS (SELECT {{BATCH}}::uuid AS import_batch), rm AS ( + SELECT sr.row_index, + (NULLIF(((sr.data -> 'cells'::text) ->> 5), ''::text))::numeric AS levelled_score, + (NULLIF(((sr.data -> 'cells'::text) ->> 6), ''::text))::numeric AS cost_task, + (NULLIF(((sr.data -> 'cells'::text) ->> 8), ''::text))::numeric AS time_min + FROM ainventory.sheet_rows sr, + batch b + WHERE ((sr.sheet_name = 'Run_Metrics'::text) AND (sr.import_batch = b.import_batch) AND (sr.row_index >= 2)) + ), tm_raw AS ( + SELECT sr.row_index, + ((sr.data -> 'cells'::text) ->> 0) AS test_run_key, + ((sr.data -> 'cells'::text) ->> 1) AS model_variant_key, + ((sr.data -> 'cells'::text) ->> 2) AS benchmark_version_key, + (NULLIF(((sr.data -> 'cells'::text) ->> 3), ''::text))::integer AS run_metric_row, + (NULLIF(((sr.data -> 'cells'::text) ->> 4), ''::text))::numeric AS target + FROM ainventory.sheet_rows sr, + batch b + WHERE ((sr.sheet_name = 'Threshold_Metrics'::text) AND (sr.import_batch = b.import_batch) AND (sr.row_index >= 2)) + ), base AS ( + SELECT t.row_index, + t.test_run_key, + t.model_variant_key, + t.benchmark_version_key, + t.run_metric_row, + t.target, + rm.levelled_score, + rm.cost_task, + rm.time_min + FROM (tm_raw t + LEFT JOIN rm ON ((rm.row_index = t.run_metric_row))) + ), calc AS ( + SELECT base.row_index, + base.test_run_key, + base.model_variant_key, + base.benchmark_version_key, + base.run_metric_row, + base.target, + base.levelled_score, + base.cost_task, + base.time_min, + CASE + WHEN (base.levelled_score IS NULL) THEN NULL::numeric + ELSE (base.levelled_score - (base.target - (1)::numeric)) + END AS usable_surplus + FROM base + ), calc2 AS ( + SELECT calc.row_index, + calc.test_run_key, + calc.model_variant_key, + calc.benchmark_version_key, + calc.run_metric_row, + calc.target, + calc.levelled_score, + calc.cost_task, + calc.time_min, + calc.usable_surplus, + CASE + WHEN (calc.usable_surplus > (0)::numeric) THEN 1 + ELSE 0 + END AS usable, + CASE + WHEN ((calc.usable_surplus > (0)::numeric) AND (calc.cost_task IS NOT NULL) AND (calc.cost_task <> (0)::numeric)) THEN (calc.usable_surplus / calc.cost_task) + ELSE NULL::numeric + END AS intel_eff_surplus_per_usd, + CASE + WHEN ((calc.usable_surplus > (0)::numeric) AND (calc.usable_surplus <> (0)::numeric) AND (calc.cost_task IS NOT NULL)) THEN (calc.cost_task / calc.usable_surplus) + ELSE NULL::numeric + END AS usd_per_usable_point, + CASE + WHEN ((calc.usable_surplus > (0)::numeric) AND (calc.cost_task IS NOT NULL) AND (calc.cost_task <> (0)::numeric) AND (calc.time_min IS NOT NULL) AND (calc.time_min <> (0)::numeric)) THEN (calc.usable_surplus / (calc.cost_task * calc.time_min)) + ELSE NULL::numeric + END AS speed_eff_surplus_per_usd_minute + FROM calc + ), normed AS ( + SELECT calc2.row_index, + calc2.test_run_key, + calc2.model_variant_key, + calc2.benchmark_version_key, + calc2.run_metric_row, + calc2.target, + calc2.levelled_score, + calc2.cost_task, + calc2.time_min, + calc2.usable_surplus, + calc2.usable, + calc2.intel_eff_surplus_per_usd, + calc2.usd_per_usable_point, + calc2.speed_eff_surplus_per_usd_minute, + CASE + WHEN (calc2.intel_eff_surplus_per_usd IS NULL) THEN NULL::numeric + ELSE (calc2.intel_eff_surplus_per_usd / max(calc2.intel_eff_surplus_per_usd) OVER (PARTITION BY calc2.target)) + END AS intel_eff_norm, + CASE + WHEN (calc2.speed_eff_surplus_per_usd_minute IS NULL) THEN NULL::numeric + ELSE (calc2.speed_eff_surplus_per_usd_minute / max(calc2.speed_eff_surplus_per_usd_minute) OVER (PARTITION BY calc2.target)) + END AS speed_eff_norm + FROM calc2 + ) + SELECT row_index, + test_run_key, + model_variant_key, + benchmark_version_key, + run_metric_row, + target, + levelled_score, + cost_task, + time_min, + usable_surplus, + usable, + intel_eff_surplus_per_usd, + usd_per_usable_point, + speed_eff_surplus_per_usd_minute, + intel_eff_norm, + speed_eff_norm, + CASE + WHEN ((intel_eff_norm IS NULL) OR (speed_eff_norm IS NULL)) THEN NULL::numeric + ELSE sqrt((intel_eff_norm * speed_eff_norm)) + END AS balanced_50_50, + CASE + WHEN ((intel_eff_norm IS NULL) OR (speed_eff_norm IS NULL)) THEN NULL::numeric + ELSE (power(intel_eff_norm, 0.7) * power(speed_eff_norm, 0.3)) + END AS smart_70_30, + CASE + WHEN ((intel_eff_norm IS NULL) OR (speed_eff_norm IS NULL)) THEN NULL::numeric + ELSE (power(intel_eff_norm, 0.3) * power(speed_eff_norm, 0.7)) + END AS speed_30_70 + FROM normed`; + +/** + * The workbook batch index. `sources` is the complete register: every + * workbook import row carries its batch id and timestamps. `ingest_batches` + * is left-joined only for optional metadata — recent workbook rows have no + * matching row and must not disappear from the list. + */ +export const AA_BATCH_INDEX_SQL = ` +select coalesce(jsonb_agg(jsonb_build_object( + 'importBatch', s.import_batch::text, + 'name', s.name, + 'importedAt', s.imported_at, + 'driveModifiedAt', s.drive_modified_at, + 'ranAt', ib.ran_at, + 'insertedCounts', ib.inserted_counts +) order by s.imported_at desc nulls last), '[]'::jsonb) as batches +from ainventory.sources s +left join ainventory.ingest_batches ib on ib.id = s.import_batch +where s.kind = 'drive-workbook' +`; + +/** The current-price overlay alone, in exactly the shape and order + * aaPayloadSql embeds it as `prices` (#3302): the collector hashes + * this every tick to validity-key the per-batch caches, because the + * overlay is current data, not batch-bound data. */ +export const AA_PRICES_SQL = ` +select coalesce(( + select jsonb_agg(jsonb_build_object( + 'modelName', model_name, 'inputPer1M', input_usd_per_1m, 'outputPer1M', output_usd_per_1m, + 'cacheReadPer1M', cached_input_usd_per_1m, 'cacheWritePer1M', cache_write_usd_per_1m, + 'contextMinTokens', context_min_tokens, 'contextMaxTokens', context_max_tokens, + 'windowKind', window_kind + ) order by model_name, context_min_tokens nulls first) + from ainventory.v_current_prices +), '[]'::jsonb) as prices +`; + +/** + * The full AA section payload for one batch (null = latest). This mirrors the + * collector's previous AA_SQL exactly except that every batch predicate and + * both latest-pinned views now take the same batch expression. + */ +export function aaPayloadSql(batch: string | null): string { + const b = batchExpression(batch); + const rankings = RANKINGS_BODY.replace("{{BATCH}}", b); + const thresholds = THRESHOLD_BODY.replace("{{BATCH}}", b); + return ` +select jsonb_build_object( + 'batch', ${b}::text, + 'sources', coalesce(( + select jsonb_agg(jsonb_build_object( + 'name', name, 'kind', kind, 'importedAt', imported_at, 'driveModifiedAt', drive_modified_at + ) order by id) + from ainventory.sources + where import_batch = ${b} + ), '[]'::jsonb), + 'rankings', coalesce(( + select jsonb_agg(jsonb_build_object( + 'rowIndex', row_index, 'testRunKey', test_run_key, 'modelVariantKey', model_variant_key, + 'family', family, 'creator', creator, 'effort', effort, + 'benchmarkVersionKey', benchmark_version_key, 'rawScore', raw_score, + 'adjustedScore', adjusted_score, 'costTask', cost_task, 'timeTaskSec', time_task_sec, + 'speedTps', speed_tps, 'qualStatus', qual_status, 'availability', availability, + 'eligible', (eligible = 1), 'intelEffPerUsd', intel_eff_per_usd, + 'usdPerUsableUnit', usd_per_usable_unit, 'pointsPerDollar', points_per_dollar, + 'pointsPerSecond', points_per_second, 'balancedValue', balanced_value, + 'smartValue', smart_value, 'speedValue', speed_value, 'rankBalanced', rank_balanced, + 'rankSmart', rank_smart, 'rankSpeed', rank_speed, 'rankIntelligence', rank_intelligence, + 'rankLowCost', rank_low_cost + ) order by rank_balanced nulls last, row_index) + from (${rankings}) vr + ), '[]'::jsonb), + 'thresholds', coalesce(( + select jsonb_agg(jsonb_build_object( + 'testRunKey', test_run_key, 'target', target, 'usable', (usable = 1), + 'levelledScore', levelled_score, 'costTask', cost_task, 'timeMin', time_min, + 'usdPerUsablePoint', usd_per_usable_point + ) order by test_run_key, target) + from (${thresholds}) vt + ), '[]'::jsonb), + 'configs', coalesce(( + select jsonb_agg(jsonb_build_object( + 'modelName', model_name, 'benchmark', benchmark, 'effort', effort, + 'intelligence', value_num, 'costPerTaskUsd', cost_per_task_usd, 'speedTps', speed_tps + ) order by model_name, effort) + from ainventory.benchmark_results br + where br.import_batch = ${b} + and br.benchmark like 'AA Intelligence Index%' + and br.metric = 'intelligence_index' + ), '[]'::jsonb), + 'testRunRows', coalesce(( + select jsonb_agg(jsonb_build_object('rowIndex', row_index, 'cells', data->'cells') order by row_index) + from ainventory.sheet_rows sr + where sr.import_batch = ${b} + and sr.sheet_name = 'Test_Runs' + ), '[]'::jsonb), + 'cai', coalesce(( + select jsonb_agg(jsonb_build_object( + 'modelName', model_name, 'effort', effort, 'version', raw->>'benchmark_version', + 'score', value_num, 'cost', cost_per_task_usd, + 'wallSec', nullif(raw->>'time_per_task_seconds', '')::numeric, + 'tokensPerTask', nullif(raw->>'token_usage_per_task', '')::numeric, + 'harness', raw->>'agent_harness', + 'creatorSlug', split_part(raw->>'observation_key', '|', 3), + 'deepSwe', nullif(raw->>'deep_swe_v1_1_pct', '')::numeric, + 'terminalBench', nullif(raw->>'terminal_bench_4_0_pct', '')::numeric, + 'sweAtlas', nullif(raw->>'swe_atlas_qna_pct', '')::numeric, + 'snapshotDate', nullif(raw->>'snapshot_date', ''), 'sourceUrl', nullif(raw->>'source_url', '') + ) order by value_num desc nulls last, model_name) + from ainventory.benchmark_results br + where br.import_batch = ${b} + and br.benchmark like 'Artificial Analysis Coding Agent Index%' + and br.metric = 'cai_index_score' + ), '[]'::jsonb), + 'prices', coalesce(( + select jsonb_agg(jsonb_build_object( + 'modelName', model_name, 'inputPer1M', input_usd_per_1m, 'outputPer1M', output_usd_per_1m, + 'cacheReadPer1M', cached_input_usd_per_1m, 'cacheWritePer1M', cache_write_usd_per_1m, + 'contextMinTokens', context_min_tokens, 'contextMaxTokens', context_max_tokens, + 'windowKind', window_kind + ) order by model_name, context_min_tokens nulls first) + from ainventory.v_current_prices + ), '[]'::jsonb) +) as aa`; +} diff --git a/pm-stack/aggregator/src/aa-batches.ts b/pm-stack/aggregator/src/aa-batches.ts new file mode 100644 index 0000000000..1010bf3072 --- /dev/null +++ b/pm-stack/aggregator/src/aa-batches.ts @@ -0,0 +1,221 @@ +// AA dataset-version index and per-batch cache shape (#3302). +// +// The selectable versions come from ainventory.sources rows with +// kind='drive-workbook' — the complete register. ingest_batches is optional +// metadata: recent workbook rows have no matching row, so a missing join +// must never hide a batch. +// +// Carriers of the same workbook (re-imports with different timestamps) are +// collapsed only when a stable fingerprint of the batch-bound semantic data +// matches. source_ref, inserted_counts, names and timestamps are NOT dedupe +// keys: the packet records repeated refs/count metadata that do not imply +// identical content. +import { createHash } from "node:crypto"; +import type { AaBatchSummary, AaSection } from "./model.ts"; +import { isBatchUuid } from "./aa-batch-sql.ts"; + +/** One raw ainventory.sources workbook row (AA_BATCH_INDEX_SQL shape). */ +export interface AaBatchIndexRow { + importBatch: string; + name: string | null; + importedAt: string | null; + driveModifiedAt: string | null; + ranAt: string | null; + insertedCounts: Record | null; +} + +/** The on-disk shape of one cached batch payload. */ +export interface AaBatchCacheEntry { + batch: string; + configFingerprint: string; + fingerprint: string; + /** sha256 of the current-price overlay the section was built + * with (aaPricesFingerprint). Absent/null on entries written + * before the overlay was validity-keyed; such entries are + * treated as stale and rebuilt. */ + pricesFingerprint?: string | null; + builtAt: string; + section: AaSection; +} + +function str(v: unknown): string | null { + return typeof v === "string" && v !== "" ? v : null; +} + +function counts(v: unknown): Record | null { + if (typeof v !== "object" || v === null || Array.isArray(v)) return null; + const out: Record = {}; + for (const [k, n] of Object.entries(v)) { + if (typeof n === "number" && Number.isFinite(n)) out[k] = n; + } + return Object.keys(out).length > 0 ? out : null; +} + +/** + * Parse AA_BATCH_INDEX_SQL's `batches` array. Rows without a uuid batch id + * are dropped; everything else is optional metadata. Sorted newest first. + */ +export function parseBatchIndex(raw: unknown): AaBatchIndexRow[] { + if (!Array.isArray(raw)) return []; + const rows: AaBatchIndexRow[] = []; + const seen = new Set(); + for (const entry of raw) { + if (typeof entry !== "object" || entry === null) continue; + const r = entry as Record; + const importBatch = str(r.importBatch); + if (!importBatch || !isBatchUuid(importBatch) || seen.has(importBatch)) continue; + seen.add(importBatch); + rows.push({ + importBatch, + name: str(r.name), + importedAt: str(r.importedAt), + driveModifiedAt: str(r.driveModifiedAt), + ranAt: str(r.ranAt), + insertedCounts: counts(r.insertedCounts), + }); + } + return rows.sort((a, b) => (b.importedAt ?? "").localeCompare(a.importedAt ?? "")); +} + +/** + * Fingerprint of the current-price overlay (v_current_prices) a + * section was built with. Prices are NOT batch-bound data — the + * page presents them as the current overlay — so they stay out of + * aaBatchFingerprint (batch identity) and carry their own validity + * key instead: when the live overlay changes, every cached + * section's prices (and its price-derived catalog) are stale and + * the cache must rebuild, however fresh its batch data and config + * still are. Rows are normalized to the AaPrice field set and + * sorted, so a raw payload row and a parsed section price hash + * identically. + */ +export function aaPricesFingerprint(prices: unknown): string { + const rows = Array.isArray(prices) ? prices : []; + const numOrNull = (v: unknown): number | null => + typeof v === "number" && Number.isFinite(v) ? v : null; + const norm = rows + .map((p) => { + const r = (p ?? {}) as Record; + return { + modelName: str(r.modelName), + inputPer1M: numOrNull(r.inputPer1M), + outputPer1M: numOrNull(r.outputPer1M), + cacheReadPer1M: numOrNull(r.cacheReadPer1M), + cacheWritePer1M: numOrNull(r.cacheWritePer1M), + contextMinTokens: numOrNull(r.contextMinTokens), + contextMaxTokens: numOrNull(r.contextMaxTokens), + windowKind: str(r.windowKind), + }; + }) + .sort((a, b) => canonicalJson(a).localeCompare(canonicalJson(b))); + return createHash("sha256").update(canonicalJson(norm)).digest("hex"); +} + +/** Human label: import date plus a shortened workbook name. */ +export function batchLabel(row: Pick): string { + const date = (row.importedAt ?? row.driveModifiedAt ?? "").slice(0, 10); + const name = row.name?.trim() ?? ""; + const short = name.length > 46 ? `${name.slice(0, 45)}…` : name; + if (date && short) return `${date} · ${short}`; + return date || short || "unnamed workbook"; +} + +/** Stable JSON: object keys sorted at every level. */ +export function canonicalJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; + if (typeof value === "object" && value !== null) { + const entries = Object.entries(value as Record) + .filter(([, v]) => v !== undefined) + .sort(([a], [b]) => a.localeCompare(b)); + return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`; + } + return JSON.stringify(value) ?? "null"; +} + +/** + * Fingerprint of the batch-bound semantic data only. `prices` is the + * non-batch v_current_prices overlay and source timestamps are carrier + * identity, so neither takes part. Two batches with the same fingerprint + * render the same tables/charts and are offered once. + */ +export function aaBatchFingerprint(raw: { + rankings?: unknown; + thresholds?: unknown; + configs?: unknown; + testRunRows?: unknown; + cai?: unknown; + sources?: unknown; +}): string { + const sources = Array.isArray(raw.sources) + ? raw.sources.map((s) => { + const r = (s ?? {}) as Record; + return { name: str(r.name), kind: str(r.kind) }; + }) + : []; + const semantic = { + rankings: raw.rankings ?? [], + thresholds: raw.thresholds ?? [], + configs: raw.configs ?? [], + testRunRows: raw.testRunRows ?? [], + cai: raw.cai ?? [], + sources, + }; + return createHash("sha256").update(canonicalJson(semantic)).digest("hex"); +} + +/** + * Turn the index + known cache fingerprints into the section's selector + * list. Newest first; a carrier whose fingerprint matches an already-kept + * entry is dropped. Null fingerprints (not built yet) are never collapsed + * because identity is unproven. + */ +export function summarizeBatches( + rows: AaBatchIndexRow[], + cache: Map, +): AaBatchSummary[] { + const kept: AaBatchSummary[] = []; + const seen = new Set(); + for (const row of rows) { + const meta = cache.get(row.importBatch); + const fingerprint = meta?.fingerprint ?? null; + if (fingerprint && seen.has(fingerprint)) continue; + if (fingerprint) seen.add(fingerprint); + kept.push({ + importBatch: row.importBatch, + name: row.name, + importedAt: row.importedAt, + driveModifiedAt: row.driveModifiedAt, + ranAt: row.ranAt, + insertedCounts: row.insertedCounts, + label: batchLabel(row), + fingerprint, + cached: meta?.cached ?? false, + latest: kept.length === 0, + }); + } + return kept; +} + +/** The per-batch cache filename; uuids only, so the name is path-safe. */ +export function aaCacheFileName(batch: string): string { + if (!isBatchUuid(batch)) throw new Error("aa cache: invalid batch uuid"); + return `aa-batch-${batch}.json`; +} + +/** Structural check for a cached payload file. */ +export function isAaBatchCacheEntry(v: unknown): v is AaBatchCacheEntry { + if (typeof v !== "object" || v === null) return false; + const e = v as Partial; + return ( + typeof e.batch === "string" && + isBatchUuid(e.batch) && + typeof e.configFingerprint === "string" && + typeof e.fingerprint === "string" && + (e.pricesFingerprint === undefined || + e.pricesFingerprint === null || + typeof e.pricesFingerprint === "string") && + typeof e.builtAt === "string" && + typeof e.section === "object" && + e.section !== null + ); +} diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index 5a731c6f72..54fe521922 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -1069,6 +1069,36 @@ export interface AaCatalogEntry { } | null; } +/** + * One selectable AA workbook version (#3302). The index is built from + * ainventory.sources rows with kind='drive-workbook' — the complete + * register; ingest_batches is optional metadata only. Carriers whose + * batch-bound semantic content has the same fingerprint are collapsed + * into the newest entry. + */ +export interface AaBatchSummary { + /** ainventory import batch id (the ?batch= value). */ + importBatch: string; + /** Workbook file name from sources.name. */ + name: string | null; + /** When ainventory imported the workbook. */ + importedAt: string | null; + /** The workbook file's own Drive modification time. */ + driveModifiedAt: string | null; + /** ingest_batches.ran_at when a metadata row exists, else null. */ + ranAt: string | null; + /** ingest_batches.inserted_counts when a metadata row exists. */ + insertedCounts: Record | null; + /** Human label: date + short file name. */ + label: string; + /** sha256 of the batch-bound semantic payload; null until built. */ + fingerprint: string | null; + /** Whether a usable per-batch payload file exists. */ + cached: boolean; + /** True for the newest surviving entry. */ + latest: boolean; +} + /** The AA explorer section as the collector embeds it in the fleet feed. */ export interface AaSection { status: "ok"; @@ -1076,6 +1106,9 @@ export interface AaSection { generatedAt: string; /** ainventory import batch (v_latest_import_batch) the rows came from. */ batch: string; + /** Selectable workbook versions, newest first, carrier duplicates + * collapsed by content fingerprint (#3302). Absent in older feeds. */ + batches?: AaBatchSummary[]; sources: AaSourceInfo[]; rankings: AaRanking[]; thresholds: AaThreshold[]; diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 714b432a8b..1c691228c0 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -5655,7 +5655,7 @@ import { applyInequalityFilters, bandIndex, computeRecommendations, logEdges, no }); function csvCell(v) { return '"' + String(v == null ? "" : v).replace(/"/g, '""') + '"'; } var dlJsonEl = document.getElementById("xf-dl-json"); - if (dlJsonEl) dlJsonEl.addEventListener("click", function () { downloadFile("cost-explorer-data.json", JSON.stringify(DATA, null, 2), "application/json"); }); + if (dlJsonEl) dlJsonEl.addEventListener("click", function () { downloadFile("cost-explorer-data-" + String(DATA.batch || "latest").slice(0, 8) + ".json", JSON.stringify(DATA, null, 2), "application/json"); }); var dlCsvEl = document.getElementById("xf-dl-csv"); if (dlCsvEl) dlCsvEl.addEventListener("click", function () { var lines = []; @@ -5815,13 +5815,37 @@ export function renderAa(section: AaFeedSection | null, provenance: Provenance, ` : ``; const explorerJson = jsonForScript( - JSON.stringify({ points: aaPoints(s), caiPoints: s.cai ? aaCaiPoints(s.cai) : [], catalog: catalog ?? null }), + JSON.stringify({ + batch: s.batch, + points: aaPoints(s), + caiPoints: s.cai ? aaCaiPoints(s.cai) : [], + catalog: catalog ?? null, + }), ); + // #3302: dataset-version selector. The selected batch scopes the whole + // explorer (charts, tables, recommendations) because the server hands + // renderAa that batch's section; downloads read the same embedded DATA. + const batches = s.batches ?? []; + const latestBatch = batches.find((b) => b.latest)?.importBatch ?? batches[0]?.importBatch ?? s.batch; + const selectedIsLatest = s.batch === latestBatch; + const batchOptions = batches + .map( + (b) => + ``, + ) + .join(""); + const batchSelector = + batches.length > 1 + ? `
+Older versions show that import's rankings, thresholds, timings and coding-agent rows. The latest is the default. Token prices remain the current v_current_prices overlay, not a historical price snapshot.
` + : ""; const body = `

Cost Explorer

${s.stale ? `` : ""} -

${s.rankings.length} ranked configurations · ${s.configs.length} AA Intelligence Index configurations · ${s.testRuns.length} timing rows${s.cai ? ` · ${s.cai.length} Coding Agent Index observations` : ""}${catalog ? ` · ${catalog.length} catalog models` : ""} · collected ${fmtDate(s.generatedAt)} from ainventory batch ${esc(s.batch.slice(0, 8))}…. Machine-first: /api/aa.json.

+${batchSelector} +

${s.rankings.length} ranked configurations · ${s.configs.length} AA Intelligence Index configurations · ${s.testRuns.length} timing rows${s.cai ? ` · ${s.cai.length} Coding Agent Index observations` : ""}${catalog ? ` · ${catalog.length} catalog models` : ""} · collected ${fmtDate(s.generatedAt)} from ainventory batch ${esc(s.batch.slice(0, 8))}…${selectedIsLatest ? " (latest)" : " (historical version)"}. Machine-first: /api/aa.json${selectedIsLatest ? "" : `?batch=${encodeURIComponent(s.batch)}`}.

Provenance
-These are the import snapshot's figures, not a live Artificial Analysis pull.${summary.snapshotVintage ? ` Test_Runs snapshots in this batch: ${esc(summary.snapshotVintage.min)} – ${esc(summary.snapshotVintage.max)}.` : ""} A new import (coding-plan-watch) flips the batch; the feed collector picks it up within minutes. The explorer renders from the feed alone — when the data pipeline lands new models (Terra, Beam), they appear here with no page change. +These are the import snapshot's figures, not a live Artificial Analysis pull.${summary.snapshotVintage ? ` Test_Runs snapshots in this batch: ${esc(summary.snapshotVintage.min)} – ${esc(summary.snapshotVintage.max)}.` : ""} A new import (coding-plan-watch) flips the batch; the feed collector picks it up within minutes. The explorer renders from the feed alone — when the data pipeline lands new models (Terra, Beam), they appear here with no page change. Token prices come from v_current_prices, a current-price overlay that is not scoped to the selected dataset version.
    ${sourcesHtml || '
  • source files not recorded for this batch
  • '}
diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 143d27af0b..da894ae731 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -1779,10 +1779,10 @@ async function handler(req: Request): Promise { } if (path === "/aa") { - return html(renderAa(await source.aa(), prov(), provDetail())); + return html(renderAa(await source.aa(url.searchParams.get("batch")), prov(), provDetail())); } if (path === "/api/aa.json") { - const section = await source.aa(); + const section = await source.aa(url.searchParams.get("batch")); return json(section ?? { status: "absent", reason: "no AA explorer section in the fleet feed yet" }); } diff --git a/pm-stack/aggregator/src/source.ts b/pm-stack/aggregator/src/source.ts index c2f7c43b46..2252666730 100644 --- a/pm-stack/aggregator/src/source.ts +++ b/pm-stack/aggregator/src/source.ts @@ -56,8 +56,10 @@ export interface Source { dns(): Promise; /** The AA cost explorer section (ainventory import data via the * fleet feed); null = not collected yet. The absent form - * ({status:"absent"}) is a real section: it renders its reason. */ - aa(): Promise; + * ({status:"absent"}) is a real section: it renders its reason. + * `batch` selects a cached historical workbook version (#3302); + * omitted keeps the latest/default behaviour. */ + aa(batch?: string | null): Promise; /** The identity registry (#906 §3): durable session records, oldest sources merged. */ registry(): Promise; /** The GitHub Project pool (#910 stage 5) from the fleet feed; empty when not collected. */ diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 28bd4593e4..4bf8e5e2ed 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -5,10 +5,12 @@ // provenance strings say exactly which facet is live vs fixture-backed. import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { createHash } from "node:crypto"; -import { dirname } from "node:path"; +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 { isBatchUuid } from "../aa-batch-sql.ts"; import { isDnsSection } from "../dns.ts"; import { diagnoseOrchestrationSection, @@ -1728,13 +1730,55 @@ export function liveSource( : "fixtures (no fleet feed file yet)"; return null; }, - async aa(): Promise { + async aa(batch?: string | null): Promise { // AA cost explorer: the section rides the fleet feed, read from // Supabase ainventory by the collector. Its absent form is a real // section (the page renders the reason); a missing section means // the collector has not embedded one yet. const feed = await getFeed(); const collection = feed?.meta?.sections.aa; + // #3302: a selected historical batch is a collector-built cache file + // beside the feed. The feed's latest section carries the index, so the + // historical render keeps the same selector list. + if (batch !== undefined && batch !== null && batch !== "") { + const batchList = + feed?.aa && isAaSection(feed.aa) && feed.aa.status === "ok" ? (feed.aa.batches ?? []) : []; + if (!isBatchUuid(batch)) { + provenance.aa = "live (fleet feed · invalid ?batch value)"; + return { status: "absent", reason: "invalid batch id", generatedAt: feed?.generatedAt ?? new Date().toISOString() }; + } + try { + const parsed: unknown = JSON.parse( + await readFile(join(dirname(cfg.feedFile), "aa-batches", aaCacheFileName(batch)), "utf8"), + ); + if (isAaBatchCacheEntry(parsed) && isAaSection(parsed.section) && parsed.section.status === "ok") { + // #3302: the collector marks a cache stale when the opencode config + // changed under it (configFingerprint mismatch) and rebuilds a few + // per tick. Serving such a payload as ordinary success would show + // 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 }; + } + } catch { + // No cache file yet — fall through to the honest absent form. + } + provenance.aa = `live (fleet feed · batch ${batch.slice(0, 8)} not cached yet)`; + return { + status: "absent", + reason: `batch ${batch} is indexed but its payload has not been built yet — the collector builds a few versions per tick`, + generatedAt: feed?.generatedAt ?? new Date().toISOString(), + }; + } if (feed?.aa && isAaSection(feed.aa)) { const detail = feed.aa.status === "ok" diff --git a/pm-stack/aggregator/test/aa-batches.test.ts b/pm-stack/aggregator/test/aa-batches.test.ts new file mode 100644 index 0000000000..066ce66143 --- /dev/null +++ b/pm-stack/aggregator/test/aa-batches.test.ts @@ -0,0 +1,361 @@ +// #3302 AA dataset version switching: batch index parsing, content-fingerprint +// dedupe, cache naming, parameterized SQL, and the /aa selector render. +import { describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { AA_BATCH_INDEX_SQL, aaPayloadSql, batchExpression, isBatchUuid } from "../src/aa-batch-sql.ts"; +import { + aaBatchFingerprint, + aaCacheFileName, + aaPricesFingerprint, + batchLabel, + canonicalJson, + isAaBatchCacheEntry, + parseBatchIndex, + summarizeBatches, +} from "../src/aa-batches.ts"; +import { renderAa } from "../src/render.ts"; +import { loadConfig } from "../src/config.ts"; +import { FIXTURE_AA } from "../src/sources/fixtures.ts"; +import { liveSource } from "../src/sources/live.ts"; +import type { AaBatchSummary, AaSection, Provenance } from "../src/model.ts"; + +const B1 = "11111111-1111-4111-8111-111111111111"; +const B2 = "22222222-2222-4222-8222-222222222222"; +const B3 = "33333333-3333-4333-8333-333333333333"; + +function rawRow(batch: string, importedAt: string, extra: Record = {}) { + return { + importBatch: batch, + name: "ai_model_benchmark_inventory_advanced_2026-10-21", + importedAt, + driveModifiedAt: importedAt, + ranAt: null, + insertedCounts: null, + ...extra, + }; +} + +describe("batch index", () => { + test("keeps workbook rows with no ingest_batches metadata", () => { + const rows = parseBatchIndex([ + rawRow(B2, "2026-10-31T14:00:00Z"), + rawRow(B1, "2026-10-31T15:00:00Z", { ranAt: "2026-10-31T14:58:00Z", insertedCounts: { sheet_rows: 4493 } }), + { importBatch: "not-a-uuid", name: "x", importedAt: "2026-11-01T00:00:00Z" }, + null, + ]); + expect(rows.map((r) => r.importBatch)).toEqual([B1, B2]); + expect(rows[0].insertedCounts).toEqual({ sheet_rows: 4493 }); + expect(rows[1].ranAt).toBeNull(); + expect(rows[1].insertedCounts).toBeNull(); + }); + + test("index SQL reads sources and only left-joins ingest_batches", () => { + expect(AA_BATCH_INDEX_SQL).toContain("from ainventory.sources s"); + expect(AA_BATCH_INDEX_SQL).toContain("left join ainventory.ingest_batches"); + expect(AA_BATCH_INDEX_SQL).toContain("kind = 'drive-workbook'"); + }); +}); + +describe("parameterized payload SQL", () => { + test("null keeps the latest subselect; a uuid becomes a validated literal", () => { + expect(batchExpression(null)).toContain("v_latest_import_batch"); + expect(batchExpression(B1)).toBe(`'${B1}'::uuid`); + expect(() => batchExpression("'; drop table x; --")).toThrow(); + expect(isBatchUuid(B1)).toBe(true); + expect(isBatchUuid("nope")).toBe(false); + }); + + test("a historical query never touches the latest-only views", () => { + const sql = aaPayloadSql(B2); + expect(sql).toContain(`'${B2}'::uuid`); + expect(sql).not.toContain("v_latest_workbook_batch"); + expect(sql).not.toContain("v_latest_import_batch"); + // The ranking/threshold maths is copied verbatim from the views. + expect(sql).toContain("rank_balanced"); + expect(sql).toContain("balanced_50_50"); + expect(sql).toContain("power(intel_eff_norm, 0.7)"); + }); + + test("the default query still pins v_latest_import_batch", () => { + expect(aaPayloadSql(null)).toContain("(select import_batch from ainventory.v_latest_import_batch)"); + }); +}); + +describe("semantic fingerprint", () => { + const base = { + rankings: [{ rowIndex: 1, family: "A", rawScore: "10" }], + thresholds: [{ testRunKey: "k", target: "20" }], + configs: [{ modelName: "A", intelligence: 10 }], + testRunRows: [{ rowIndex: 1, cells: ["test_run_key"] }], + cai: [], + sources: [{ name: "workbook.xlsx", kind: "drive-workbook", importedAt: "2026-10-01T00:00:00Z" }], + }; + + test("identical content with different source timestamps collapses", () => { + const other = { + ...base, + sources: [{ name: "workbook.xlsx", kind: "drive-workbook", importedAt: "2026-10-31T00:00:00Z" }], + }; + expect(aaBatchFingerprint(base)).toBe(aaBatchFingerprint(other)); + }); + + test("changed batch-bound content changes the fingerprint", () => { + const changed = { ...base, rankings: [{ rowIndex: 1, family: "A", rawScore: "11" }] }; + expect(aaBatchFingerprint(base)).not.toBe(aaBatchFingerprint(changed)); + }); + + test("the current-price overlay is not part of the fingerprint", () => { + const withPrices = { ...base, prices: [{ modelName: "A", inputPer1M: 1 }] } as typeof base; + expect(aaBatchFingerprint(withPrices)).toBe(aaBatchFingerprint(base)); + }); + + test("prices fingerprint is stable across key order and row order", () => { + // Oracle (#3302 review): the overlay validity key must depend + // only on the price values — the same overlay fetched twice + // (raw rows) or read back from a built section (parsed rows) + // hashes identically. + const a = [ + { modelName: "A", inputPer1M: 1, outputPer1M: 2, cacheReadPer1M: null, cacheWritePer1M: null, contextMinTokens: 0, contextMaxTokens: 100, windowKind: "fixed" }, + { modelName: "B", inputPer1M: 3, outputPer1M: 4, cacheReadPer1M: 1, cacheWritePer1M: 2, contextMinTokens: null, contextMaxTokens: null, windowKind: null }, + ]; + const b = [ + { windowKind: null, contextMaxTokens: null, contextMinTokens: null, cacheWritePer1M: 2, cacheReadPer1M: 1, outputPer1M: 4, inputPer1M: 3, modelName: "B" }, + { windowKind: "fixed", contextMaxTokens: 100, contextMinTokens: 0, cacheWritePer1M: null, cacheReadPer1M: null, outputPer1M: 2, inputPer1M: 1, modelName: "A" }, + ]; + expect(aaPricesFingerprint(a)).toBe(aaPricesFingerprint(b)); + }); + + test("prices fingerprint changes when any price changes", () => { + // Oracle (#3302 review): a price-only change — no new workbook, + // no config change — produces a different validity key, so + // cached sections rebuild instead of serving stale prices as + // the current overlay. + const base = [{ modelName: "A", inputPer1M: 1, outputPer1M: 2, cacheReadPer1M: null, cacheWritePer1M: null, contextMinTokens: null, contextMaxTokens: null, windowKind: null }]; + const changed = [{ ...base[0], inputPer1M: 5 }]; + expect(aaPricesFingerprint(base)).not.toBe(aaPricesFingerprint(changed)); + expect(aaPricesFingerprint([])).not.toBe(aaPricesFingerprint(base)); + expect(aaPricesFingerprint(undefined)).toBe(aaPricesFingerprint([])); + }); + + test("canonical JSON sorts keys at every level", () => { + expect(canonicalJson({ b: 1, a: { d: 2, c: 3 } })).toBe('{"a":{"c":3,"d":2},"b":1}'); + }); +}); + +describe("batch summaries", () => { + test("collapses equal fingerprints, keeps distinct ones, marks latest", () => { + const rows = parseBatchIndex([ + rawRow(B1, "2026-10-31T15:00:00Z"), + rawRow(B2, "2026-10-31T14:00:00Z"), + rawRow(B3, "2026-10-31T13:00:00Z"), + ]); + const cache = new Map([ + [B1, { fingerprint: "same", cached: true }], + [B2, { fingerprint: "same", cached: true }], + [B3, { fingerprint: "different", cached: false }], + ]); + const out = summarizeBatches(rows, cache); + expect(out.map((b) => b.importBatch)).toEqual([B1, B3]); + expect(out[0].latest).toBe(true); + expect(out[1].latest).toBe(false); + expect(out[1].cached).toBe(false); + }); + + test("uncached batches are never collapsed on unproven identity", () => { + const rows = parseBatchIndex([rawRow(B1, "2026-10-31T15:00:00Z"), rawRow(B2, "2026-10-31T14:00:00Z")]); + const out = summarizeBatches(rows, new Map()); + expect(out).toHaveLength(2); + expect(out.every((b) => b.fingerprint === null)).toBe(true); + }); + + test("cache names are uuid-only and label is human-readable", () => { + expect(aaCacheFileName(B1)).toBe(`aa-batch-${B1}.json`); + expect(() => aaCacheFileName("../escape")).toThrow(); + expect(isAaBatchCacheEntry({ batch: B1, configFingerprint: "c", fingerprint: "f", builtAt: "t", section: {} })).toBe(true); + expect(isAaBatchCacheEntry({ batch: "../x" })).toBe(false); + expect(batchLabel({ name: "ai_model_benchmark_inventory_advanced_2026-10-21", importedAt: "2026-10-31T15:00:00Z", driveModifiedAt: null })).toStartWith("2026-10-31"); + }); +}); + +describe("/aa selector", () => { + const PROV = new Proxy({}, { get: () => "fixture" }) as Provenance; + const batches: AaBatchSummary[] = [ + { + importBatch: B1, + name: "workbook", + importedAt: "2026-10-31T15:00:00Z", + driveModifiedAt: null, + ranAt: null, + insertedCounts: null, + label: "2026-10-31 · workbook (latest)", + fingerprint: "a", + cached: true, + latest: true, + }, + { + importBatch: B3, + name: "workbook", + importedAt: "2026-10-21T10:00:00Z", + driveModifiedAt: null, + ranAt: null, + insertedCounts: null, + label: "2026-10-21 · workbook", + fingerprint: "b", + cached: true, + latest: false, + }, + ]; + const section: AaSection = { + status: "ok", + generatedAt: "2026-10-31T15:01:00Z", + batch: B3, + batches, + sources: [], + rankings: [], + thresholds: [], + configs: [], + testRuns: [], + }; + + test("selected historical batch is marked and API/download links follow it", () => { + const html = renderAa(section, PROV); + expect(html).toContain('id="xf-batch"'); + expect(html).toContain(`value="${B3}" selected`); + expect(html).toContain("(latest)"); + expect(html).toContain("historical version"); + expect(html).toContain(`/api/aa.json?batch=${B3}`); + expect(html).toContain("current-price overlay"); + }); + + test("latest default keeps the plain API link", () => { + const html = renderAa({ ...section, batch: B1 }, PROV); + expect(html).toContain(`value="${B1}" selected`); + expect(html).toContain('href="/api/aa.json"'); + expect(html).not.toContain(`/api/aa.json?batch=${B1}`); + }); +}); + +describe("live AA batch selection", () => { + test("serves the selected cached payload while preserving latest as the default", async () => { + const dir = await mkdtemp(join(tmpdir(), "aa-batch-source-")); + const feedFile = join(dir, "fleet-feed.json"); + const historical = { ...FIXTURE_AA, batch: B3 }; + const latest = { + ...FIXTURE_AA, + batch: B1, + batches: [ + { + importBatch: B1, + name: "latest.xlsx", + importedAt: "2026-10-31T15:00:00Z", + driveModifiedAt: null, + ranAt: null, + insertedCounts: null, + label: "2026-10-31 · latest.xlsx", + fingerprint: "latest", + cached: true, + latest: true, + }, + { + importBatch: B3, + name: "historical.xlsx", + importedAt: "2026-10-21T10:00:00Z", + driveModifiedAt: null, + ranAt: null, + insertedCounts: null, + label: "2026-10-21 · historical.xlsx", + fingerprint: "historical", + cached: true, + latest: false, + }, + ], + }; + await writeFile( + feedFile, + JSON.stringify({ + version: 1, + generatedAt: new Date().toISOString(), + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], + aa: latest, + }), + ); + const cacheDir = join(dir, "aa-batches"); + await mkdir(cacheDir); + await writeFile( + join(cacheDir, aaCacheFileName(B3)), + JSON.stringify({ + batch: B3, + configFingerprint: "config", + fingerprint: "historical", + builtAt: historical.generatedAt, + section: historical, + }), + ); + + const source = liveSource(loadConfig({ PM_AGG_SOURCE: "live", PM_AGG_FEED_FILE: feedFile })); + expect((await source.aa())?.batch).toBe(B1); + const selected = await source.aa(B3); + expect(selected?.status).toBe("ok"); + expect(selected?.batch).toBe(B3); + expect(selected?.batches?.map((batch) => batch.importBatch)).toEqual([B1, B3]); + expect((await source.aa("44444444-4444-4444-8444-444444444444"))?.status).toBe("absent"); + }); + + test("a cache invalidated by a config change is served stale, not as ordinary success", async () => { + const dir = await mkdtemp(join(tmpdir(), "aa-batch-stale-")); + const feedFile = join(dir, "fleet-feed.json"); + const historical = { ...FIXTURE_AA, batch: B3 }; + 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, + }); + await writeFile( + feedFile, + JSON.stringify({ + version: 1, + generatedAt: new Date().toISOString(), + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], + aa: { + ...FIXTURE_AA, + batch: B1, + // The collector rebuilt the index under a new config fingerprint and + // has not rebuilt B3's payload yet. + batches: [summary(B1, true, true), summary(B3, false, false)], + }, + }), + ); + const cacheDir = join(dir, "aa-batches"); + await mkdir(cacheDir); + await writeFile( + join(cacheDir, aaCacheFileName(B3)), + JSON.stringify({ + batch: B3, + configFingerprint: "old-config", + fingerprint: "historical", + builtAt: historical.generatedAt, + section: historical, + }), + ); + + const source = liveSource(loadConfig({ PM_AGG_SOURCE: "live", PM_AGG_FEED_FILE: feedFile })); + const selected = await source.aa(B3); + expect(selected?.status).toBe("ok"); + expect(selected?.stale).toBe(true); + expect(selected?.staleReason).toContain("rebuilding"); + const html = renderAa(selected ?? null, new Proxy({}, { get: () => "live" }) as Provenance); + expect(html).toContain("The latest collection failed"); + expect(html).toContain("rebuilding"); + }); +});