From 3e280c4826e89ac31c4114904768cec8d1ef4f88 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 00:28:51 -0500 Subject: [PATCH] aa feed: keep last good on failure + skip unchanged query; rename v_latest_import_batch (code#3332) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A single transient Supabase Management API 403 blanked the AA explorer: the collector rebuilt the section from scratch every tick and emitted absent on any failure. It now keeps the last good section beside the feed (aa-last-good.json): a failed build degrades to that payload with a stale marker (the page shows a banner naming the failure and the good data's collection time), and absent is emitted only when no good build exists yet. A cheap batch probe runs first: while the ainventory import batch and the opencode config fingerprint are unchanged, the stored section is reused and the full payload query never runs — the every-5-minutes query pressure was itself causing intermittent 403s. Terminology (Drew, 2026-11-01): the ainventory view is renamed v_latest_workbook_batch -> v_latest_import_batch (new view created additively in Supabase; the old view remains until other consumers are audited), and workbook wording across the aggregator now says import where the database-resident data is meant. The sources.kind provenance value (drive-workbook) is data, not terminology, and is untouched. The explorer provenance card also drops its hardcoded v4.3.2 claim. --- .../aggregator/scripts/collect-fleet-feed.ts | 136 ++++++++++++++---- pm-stack/aggregator/src/aa.ts | 18 +-- pm-stack/aggregator/src/feed.ts | 2 +- pm-stack/aggregator/src/model.ts | 33 +++-- pm-stack/aggregator/src/render.ts | 29 ++-- pm-stack/aggregator/src/source.ts | 2 +- 6 files changed, 151 insertions(+), 69 deletions(-) diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index 3b1c2ed220..d7a8ca5676 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -39,11 +39,11 @@ // Any failure (no token, bws missing, GraphQL error) omits the // section and logs only that it was omitted. // - the AA cost explorer data — Supabase `ainventory` (the AA -// workbook import: v_rankings, v_threshold_metrics, +// import: v_rankings, v_threshold_metrics, // benchmark_results — both the AA Intelligence Index rows and the // Coding Agent Index rows, kept as separate benchmark families — -// the Test_Runs sheet, and the price event log's v_current_prices), -// read through v_latest_workbook_batch via the Management API SQL endpoint. +// the Test_Runs data, and the price event log's v_current_prices), +// read through v_latest_import_batch via the Management API SQL endpoint. // Token plumbing mirrors the Projects read: the Bitwarden secret // named `supabase.access-token-muse-cli` (the sbp_ management // token), resolved by resolveBwsSecret and sent only to @@ -73,11 +73,12 @@ import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { dnsSectionFromRegister } from "../src/dns.ts"; -import { disabledProvidersFromConfig, aaAbsent, aaSectionFromSupabase, type AaRawPayload } from "../src/aa.ts"; +import { disabledProvidersFromConfig, aaAbsent, aaSectionFromSupabase, isAaSection, type AaRawPayload } from "../src/aa.ts"; import { normalizeOrchestrationSection, orchestrationSectionProblem, type FleetFeed } from "../src/feed.ts"; import { computeCheckoutDrift } from "../src/checkout-drift.ts"; import type { AaFeedSection, + AaSection, DnsSection, JulesSummary, OrchestrationSection, @@ -265,18 +266,18 @@ async function resolveProjectToken(): Promise { // --- AA cost explorer (Supabase ainventory) --------------------------------- // One SQL statement returns the whole section payload as a single // jsonb object (keys pre-renamed to the section's camelCase). The -// Test_Runs sheet rides as raw rows; src/aa.ts maps them by the -// sheet's own header row and computes pool/catalog coverage. +// 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_workbook_batch), + '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_workbook_batch) + where import_batch = (select import_batch from ainventory.v_latest_import_batch) ), '[]'::jsonb), 'rankings', coalesce(( select jsonb_agg(jsonb_build_object( @@ -308,14 +309,14 @@ select jsonb_build_object( '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_workbook_batch) + 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_workbook_batch) + where sr.import_batch = (select import_batch from ainventory.v_latest_import_batch) and sr.sheet_name = 'Test_Runs' ), '[]'::jsonb), 'cai', coalesce(( @@ -332,7 +333,7 @@ select jsonb_build_object( '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_workbook_batch) + 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), @@ -347,37 +348,110 @@ select jsonb_build_object( ), '[]'::jsonb) ) as aa`; +const AA_BATCH_SQL = `select import_batch::text as batch from ainventory.v_latest_import_batch`; + /** - * Build the AA feed section. Fail-soft like every other section, but - * with the failure stated in the section itself (the absent form), so - * the dashboard explains the gap instead of silently going stale. - * The management token is only ever sent to api.supabase.com and is - * never logged or written to the feed. + * The last-good AA section store (code#3332): kept beside the feed so a + * transient Supabase failure degrades to the previous good payload + * instead of blanking the explorer. Keyed by the import batch and the + * opencode config fingerprint — the section is rebuilt when either + * changes and reused untouched while neither does. + */ +const aaLastGoodPath = join(dirname(outPath), "aa-last-good.json"); + +interface AaLastGood { + batch: string; + configFingerprint: string; + section: AaSection; +} + +async function readAaLastGood(): Promise { + try { + 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 }; + } catch { + return null; + } +} + +async function writeAaLastGood(entry: AaLastGood): Promise { + try { + const tmp = `${aaLastGoodPath}.tmp`; + await writeFile(tmp, JSON.stringify(entry)); + await rename(tmp, aaLastGoodPath); + } catch (err) { + console.error(`collector: AA last-good store write failed (${err instanceof Error ? err.message : "error"})`); + } +} + +/** 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 { + try { + const st = await stat(opencodeConfigPath); + return `${st.mtimeMs}:${st.size}`; + } catch { + return "unreadable"; + } +} + +async function supabaseQuery(token: string, ref: string, sql: string): Promise { + const res = await fetch(`https://api.supabase.com/v1/projects/${ref}/database/query`, { + method: "POST", + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + body: JSON.stringify({ query: sql }), + signal: AbortSignal.timeout(60_000), + }); + if (!res.ok) throw new Error(`Supabase query failed (HTTP ${res.status})`); + return res.json(); +} + +/** + * 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. */ async function collectAaSection(generatedAt: string): Promise { + const lastGood = await readAaLastGood(); + 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 aaAbsent("no Supabase management token available (bws)", generatedAt); + 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 res = await fetch(`https://api.supabase.com/v1/projects/${ref}/database/query`, { - method: "POST", - headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, - body: JSON.stringify({ query: AA_SQL }), - signal: AbortSignal.timeout(60_000), - }); - if (!res.ok) return aaAbsent(`Supabase query failed (HTTP ${res.status})`, generatedAt); - const rows = (await res.json()) as { aa?: unknown }[]; + 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 aaAbsent("Supabase returned no AA payload", generatedAt); + return degrade("Supabase returned no AA payload"); } raw = rows[0].aa as AaRawPayload; } catch (err) { - return aaAbsent(`Supabase unreachable (${err instanceof Error ? err.message : "error"})`, generatedAt); + 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 { @@ -385,10 +459,10 @@ async function collectAaSection(generatedAt: string): Promise { } catch { console.error("collector: opencode.jsonc unreadable; AA coverage omitted this run"); } - return ( - aaSectionFromSupabase(raw, configText, generatedAt) ?? - aaAbsent("Supabase payload failed its structural check", generatedAt) - ); + const section = aaSectionFromSupabase(raw, configText, generatedAt); + if (!section) return degrade("Supabase payload failed its structural check"); + await writeAaLastGood({ batch: section.batch, configFingerprint: fingerprint, section }); + return section; } async function main(): Promise { diff --git a/pm-stack/aggregator/src/aa.ts b/pm-stack/aggregator/src/aa.ts index 191ea8fc7d..80db563b31 100644 --- a/pm-stack/aggregator/src/aa.ts +++ b/pm-stack/aggregator/src/aa.ts @@ -1,7 +1,7 @@ // The AA cost explorer as data. The source of record is the Supabase -// `ainventory` schema (the AA workbook import: v_rankings, -// v_threshold_metrics, benchmark_results, and the Test_Runs sheet in -// sheet_rows, all read through v_latest_workbook_batch). The collector +// `ainventory` schema (the AA import: v_rankings, +// v_threshold_metrics, benchmark_results, and the Test_Runs data in +// sheet_rows, all read through v_latest_import_batch). The collector // queries it, assembles the section with the helpers here, and embeds // it in the fleet feed; the aggregator renders the section as-is. // Everything in this module is pure and unit-tested (test/aa.test.ts), @@ -44,9 +44,9 @@ function boolish(v: unknown): boolean { return v === true || v === 1 || v === "1" || v === "true"; } -// --- Test_Runs sheet mapping ------------------------------------------------- +// --- Test_Runs data mapping ------------------------------------------------- -/** One raw sheet_rows row for the Test_Runs sheet: cells as stored. */ +/** One raw sheet_rows row for the Test_Runs data: cells as stored. */ export interface SheetRow { rowIndex: number; cells: unknown[]; @@ -68,7 +68,7 @@ const TEST_RUN_FIELDS: Record = { /** * Map raw Test_Runs rows to timing records, keyed off the sheet's own * header row (the row carrying "test_run_key" among its cells) — a - * workbook column reorder changes nothing here. Rows without a key + * import column reorder changes nothing here. Rows without a key * are dropped; empty cells become nulls. */ export function testRunsFromSheetRows(rows: SheetRow[]): AaTestRun[] { @@ -262,7 +262,7 @@ const MODEL_ALIASES = new Map([ ["deepseek v4 flash", "deepseek v4 1 flash"], // Meta's config ids carry the 1.0 version the AA family name drops. ["muse wonder 1 0", "muse wonder"], - // AA's workbook family for Qwen's max checkpoint carries its date. + // AA's import family for Qwen's max checkpoint carries its date. ["qwen3 8 max 0902", "qwen3 8 max"], // Word order differs between the AA family and the config ids. ["claude haiku 4 5", "claude 4 5 haiku"], @@ -293,7 +293,7 @@ const byAlpha = (a: string, b: string): number => a.toLowerCase().localeCompare( /** * Compare the AA-measured model names against the catalog + pooled - * sets. Display names in the first three lists are the AA/workbook + * sets. Display names in the first three lists are the AA/import * names; the fourth lists catalog ids verbatim (that is where a human * goes looking for them in the config). */ @@ -526,7 +526,7 @@ export function aaCaiPoints(rows: AaCaiRow[]): AaPoint[] { pointsPerSecond: null, scorePerDollar: b.score !== null && b.cost !== null && b.cost > 0 ? b.score / b.cost : null, scorePerSecond: b.score !== null && b.time !== null && b.time > 0 ? b.score / b.time : null, - // CAI rows are published results; the workbook's "eligible" flag + // CAI rows are published results; the import's "eligible" flag // is a rankings-view concept and does not exist for them. eligible: true, qualStatus: null, diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index 8cfed9ccc8..3be8f485d1 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -76,7 +76,7 @@ export interface FleetFeed { * state, read by the collector via GraphQL. Absent when the * collector had no Projects token or the read failed. */ projects?: ProjectPoolItem[]; - /** AA cost explorer section: the ainventory (AA workbook) data read + /** AA cost explorer section: the ainventory (AA import) data read * by the collector from Supabase, plus pool/catalog coverage computed * against the repo's opencode config. Present-but-absent * ({status:"absent", reason}) when Supabase was unreachable — the diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index d59de6df5a..c241f6867f 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -710,14 +710,14 @@ export interface DnsSection { } // --------------------------------------------------------------------------- -// AA cost explorer: the Artificial Analysis workbook data (Supabase +// AA cost explorer: the Artificial Analysis import data (Supabase // `ainventory`, latest import batch) as the collector embeds it in the -// fleet feed. The figures are the workbook snapshot's — AA Intelligence +// fleet feed. The figures are the import snapshot's — AA Intelligence // Index v4.3.2, Test_Runs snapshots of Sep–Oct 2026 — not a live AA pull; // the section's provenance says exactly which batch and files they are. // --------------------------------------------------------------------------- -/** One workbook source file behind the AA section (freshness evidence). */ +/** One import source file behind the AA section (freshness evidence). */ export interface AaSourceInfo { name: string; kind: string; @@ -776,7 +776,7 @@ export interface AaThreshold { export interface AaConfig { modelName: string; benchmark: string; - /** The workbook's effort label, verbatim (e.g. "Adaptive Reasoning, + /** The import's effort label, verbatim (e.g. "Adaptive Reasoning, * High Effort, Default Fallback") — never shortened or invented. */ effort: string | null; intelligence: number | null; @@ -785,7 +785,7 @@ export interface AaConfig { } /** One Test_Runs row, mapped by the sheet's own header row: per-config - * timing. Null timing = the workbook never measured it — the page says + * timing. Null timing = the import never measured it — the page says * "not measured", it does not estimate. */ export interface AaTestRun { testRunKey: string; @@ -802,7 +802,7 @@ export interface AaTestRun { /** * One Coding Agent Index row of ainventory.benchmark_results (the - * workbook's Coding_Agent_Results import): a model + effort + agent + * import's Coding_Agent_Results rows): a model + effort + agent * harness observation, kept strictly separate from the AA Intelligence * Index — no score conversion between the indexes (the ChatGPT * explorers' cross-benchmark rule). Component scores are the published @@ -899,15 +899,15 @@ export interface AaPoint { ttft: number | null; pointsPerDollar: number | null; pointsPerSecond: number | null; - /** score / cost, computed when the workbook's own column is absent. */ + /** score / cost, computed when the import's own column is absent. */ scorePerDollar: number | null; - /** score / time, computed when the workbook's own column is absent. */ + /** score / time, computed when the import's own column is absent. */ scorePerSecond: number | null; eligible: boolean; qualStatus: string | null; /** Agent harness (CAI points only; null on AA points). */ harness: string | null; - /** Total tokens per task (CAI points only; the workbook's AA rows + /** Total tokens per task (CAI points only; the import's AA rows * do not carry a per-task token count). */ tokensPerTask: number | null; /** CAI component scores as published fractions (CAI points only). */ @@ -928,7 +928,7 @@ export interface AaPoint { * (route ids whose expanded leaves include it), the plan the provider * door belongs to (collector-carried registry facts — see * AA_PLAN_FACTS in src/aa.ts), and its best AA measurement when the - * workbook measured a model of the same normalized name. Assembled by + * import measured a model of the same normalized name. Assembled by * aaCatalogFromConfig() in src/aa.ts. */ export interface AaCatalogEntry { @@ -996,7 +996,7 @@ export interface AaSection { status: "ok"; /** ISO timestamp of the collector run that built the section. */ generatedAt: string; - /** ainventory import batch (v_latest_workbook_batch) the rows came from. */ + /** ainventory import batch (v_latest_import_batch) the rows came from. */ batch: string; sources: AaSourceInfo[]; rankings: AaRanking[]; @@ -1015,11 +1015,18 @@ export interface AaSection { /** Current token prices from the ainventory price event log * (v_current_prices); absent on the same condition as cai. */ prices?: AaPrice[]; + /** Set by the collector when this section is the last good payload + * re-served after a failed collection (code#3332); absent on a fresh + * build. generatedAt stays the good build's time. */ + stale?: boolean; + /** Why the latest collection failed, when stale. */ + staleReason?: string; } /** The section's degraded form: the collector could not reach Supabase - * (or the payload failed its check) — the page renders the reason - * instead of stale numbers, and the feed never fails over it. */ + * (or the payload failed its check) and no last good payload exists + * to fall back to (code#3332) — the page renders the reason, and the + * feed never fails over it. */ export interface AaAbsentSection { status: "absent"; reason: string; diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 3bbae6c34d..adc273694a 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -2841,7 +2841,7 @@ export function renderDns(section: DnsSection | null, provenance: Provenance, de return layout("DNS register", body, provenance, "/dns", "", chips); } -// --- AA cost explorer page (ainventory workbook data via the fleet feed) ----- +// --- AA cost explorer page (ainventory import data via the fleet feed) ----- /** * The Cost Explorer's client side: tabs, the shared filter bar, the @@ -3002,7 +3002,7 @@ const AA_EXPLORER_SCRIPT = `