From 592ef208df70c7adbd5bedd782579d58486876c9 Mon Sep 17 00:00:00 2001 From: repo-worker-code-g Date: Sat, 7 Nov 2026 08:11:29 -0600 Subject: [PATCH] archive: janitor sweep 2026-11-07 (dirty worktree 4924) --- .../aggregator/scripts/collect-fleet-feed.ts | 300 +++++---- pm-stack/aggregator/src/aa-batch-sql.ts | 619 ++++++++++++++++++ pm-stack/aggregator/src/aa-batches.ts | 179 +++++ pm-stack/aggregator/src/model.ts | 33 + pm-stack/aggregator/src/render.ts | 32 +- pm-stack/aggregator/src/server.ts | 4 +- pm-stack/aggregator/src/source.ts | 6 +- pm-stack/aggregator/src/sources/live.ts | 34 +- pm-stack/aggregator/test/aa-batches.test.ts | 203 ++++++ 9 files changed, 1280 insertions(+), 130 deletions(-) create mode 100644 pm-stack/aggregator/src/aa-batch-sql.ts create mode 100644 pm-stack/aggregator/src/aa-batches.ts create mode 100644 pm-stack/aggregator/test/aa-batches.test.ts diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index b91592a87a..fdb1f7e059 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -68,7 +68,7 @@ // fallback default: the muse-dev2 project), // AA_OPENCODE_CONFIG_PATH (default: the repo's .opencode/opencode.jsonc). import { execFile } from "node:child_process"; -import { access, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; +import { access, mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -80,6 +80,16 @@ import { isAaSection, type AaRawPayload, } from "../src/aa.ts"; +import { AA_BATCH_INDEX_SQL, aaPayloadSql } from "../src/aa-batch-sql.ts"; +import { + aaBatchFingerprint, + aaCacheFileName, + isAaBatchCacheEntry, + parseBatchIndex, + summarizeBatches, + type AaBatchCacheEntry, + type AaBatchIndexRow, +} from "../src/aa-batches.ts"; import { feedSectionStatus, normalizeOrchestrationSection, @@ -90,6 +100,7 @@ import { } from "../src/feed.ts"; import { computeCheckoutDrift } from "../src/checkout-drift.ts"; import type { + AaBatchSummary, AaFeedSection, AaSection, DnsSection, @@ -317,86 +328,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 @@ -406,10 +341,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; } @@ -418,7 +361,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; } @@ -434,6 +382,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 { @@ -456,51 +429,37 @@ 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); - const token = await resolveBwsSecret("supabase.access-token-muse-cli"); - if (!token) return degrade("no Supabase management token available (bws)"); - // Project ref: env override, else the Bitwarden supabase.project-ref - // secret (the same resolve-by-name discipline as the token), else the - // muse-dev2 project — never the retired muse-dev project. - const ref = - process.env.SUPABASE_PROJECT_REF ?? (await resolveBwsSecret("supabase.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. - 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. - } - let raw: AaRawPayload; - 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; - } catch (err) { - const msg = err instanceof Error ? err.message : "error"; - return degrade(msg.startsWith("Supabase query failed") ? msg : `Supabase unreachable (${msg})`); - } + + // Batch-independent config reads, done once for every assembly. let configText: string | null = null; try { configText = await readFile(opencodeConfigPath, "utf8"); @@ -515,10 +474,111 @@ async function collectAaSection(generatedAt: string): Promise { } catch { runtimeText = null; } - 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; + + 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, + builtAt: generatedAt, + section, + }); + cacheMeta.set(section.batch, { fingerprint: contentFingerprint, cached }); + return section; + }; + + const token = await resolveBwsSecret("supabase.access-token-muse-cli"); + if (!token) return degrade("no Supabase management token available (bws)"); + // Project ref: env override, else the Bitwarden supabase.project-ref + // secret (the same resolve-by-name discipline as the token), else the + // muse-dev2 project — never the retired muse-dev project. + const ref = + process.env.SUPABASE_PROJECT_REF ?? (await resolveBwsSecret("supabase.project-ref")) ?? "keihfchslgjetkmnmzra"; + + // 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_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})`); + } + if (index.length === 0) return degrade("no workbook batches in ainventory.sources"); + + // Read every batch cache once; a changed config invalidates all of them. + const cachedSections = new Map(); + for (const row of index) { + const cached = await readAaBatchCache(row.importBatch); + if (cached && cached.configFingerprint === fingerprint) { + 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 }); + } + } + 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, + 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})`); + } + } + 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, + section: latestSection, + }); + + // Build a bounded number of missing historical payloads per tick. Failures + // are logged without detail and retried on a later tick. + let built = 0; + for (const row of index) { + if (built >= AA_HISTORICAL_BUILDS_PER_TICK) break; + if (row.importBatch === latestSection.batch) continue; + if (cacheMeta.get(row.importBatch)?.cached) continue; + try { + const section = await assemble(await fetchAaPayload(token, ref, row.importBatch)); + if (section) built++; + } catch (err) { + console.error(`collector: AA historical batch build failed (${err instanceof Error ? err.message : "error"})`); + } + } + + const batches: AaBatchSummary[] = summarizeBatches(index, cacheMeta); + return { ...latestSection, batches }; } 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..bea7b29093 --- /dev/null +++ b/pm-stack/aggregator/src/aa-batch-sql.ts @@ -0,0 +1,619 @@ +// 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 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..fbca67aafc --- /dev/null +++ b/pm-stack/aggregator/src/aa-batches.ts @@ -0,0 +1,179 @@ +// 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; + 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 ?? "")); +} + +/** 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" && + 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 68d227e9ac..fb54880322 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -1004,6 +1004,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"; @@ -1011,6 +1041,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 d753c48127..d39881fd7b 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -5795,7 +5795,7 @@ const AA_EXPLORER_SCRIPT = `