diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index 896edc8280..67891d8d0a 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -88,7 +88,7 @@ import { isAaSection, type AaRawPayload, } from "../src/aa.ts"; -import { AA_BATCH_INDEX_SQL, AA_PRICES_SQL, aaPayloadSql } from "../src/aa-batch-sql.ts"; +import { AA_BATCH_INDEX_SQL, AA_PAYLOAD_SQL_REVISION, AA_PRICES_SQL, aaPayloadSql } from "../src/aa-batch-sql.ts"; import { aaBatchFingerprint, aaCacheFileName, @@ -465,6 +465,8 @@ interface AaLastGood { configFingerprint: string; /** sha256 of the batch-bound semantic data (aa-batches.ts). */ fingerprint?: string; + /** aaPayloadSql revision the section was built with (#8817). */ + sqlRevision?: number; section: AaSection; } @@ -477,6 +479,7 @@ async function readAaLastGood(): Promise { batch: parsed.batch, configFingerprint: parsed.configFingerprint, fingerprint: typeof parsed.fingerprint === "string" ? parsed.fingerprint : undefined, + sqlRevision: typeof parsed.sqlRevision === "number" ? parsed.sqlRevision : undefined, section: parsed.section, }; } catch { @@ -596,6 +599,7 @@ async function collectAaSection(generatedAt: string): Promise { configFingerprint: fingerprint, fingerprint: contentFingerprint, pricesFingerprint: aaPricesFingerprint(section.prices ?? []), + sqlRevision: AA_PAYLOAD_SQL_REVISION, builtAt: generatedAt, section, }); @@ -639,15 +643,17 @@ async function collectAaSection(generatedAt: string): Promise { return degrade(msg.startsWith("Supabase query failed") ? msg : `Supabase unreachable (${msg})`); } - // Read every batch cache once; a changed config — or a changed - // current-price overlay — invalidates all of them. + // Read every batch cache once; a changed config, a changed + // current-price overlay, or a moved aaPayloadSql revision (#8817) + // 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 + (cached.pricesFingerprint ?? null) === currentPricesFingerprint && + (cached.sqlRevision ?? 0) === AA_PAYLOAD_SQL_REVISION ) { cacheMeta.set(row.importBatch, { fingerprint: cached.fingerprint, cached: true }); cachedSections.set(row.importBatch, cached.section); @@ -665,6 +671,7 @@ async function collectAaSection(generatedAt: string): Promise { lastGood && lastGood.batch === latestBatch && lastGood.configFingerprint === fingerprint && + (lastGood.sqlRevision ?? 0) === AA_PAYLOAD_SQL_REVISION && lastGood.fingerprint ) { // Reuse the last good latest section without re-running the full query. @@ -674,6 +681,7 @@ async function collectAaSection(generatedAt: string): Promise { configFingerprint: fingerprint, fingerprint: lastGood.fingerprint, pricesFingerprint: aaPricesFingerprint(lastGood.section.prices ?? []), + sqlRevision: AA_PAYLOAD_SQL_REVISION, builtAt: latestSection.generatedAt, section: latestSection, }); @@ -693,6 +701,7 @@ async function collectAaSection(generatedAt: string): Promise { batch: latestSection.batch, configFingerprint: fingerprint, fingerprint: cacheMeta.get(latestSection.batch)?.fingerprint ?? undefined, + sqlRevision: AA_PAYLOAD_SQL_REVISION, section: latestSection, }); @@ -723,6 +732,7 @@ async function collectAaSection(generatedAt: string): Promise { batch: withIndex.batch, configFingerprint: fingerprint, fingerprint: cacheMeta.get(withIndex.batch)?.fingerprint ?? undefined, + sqlRevision: AA_PAYLOAD_SQL_REVISION, section: withIndex, }); return withIndex; diff --git a/pm-stack/aggregator/src/aa-batch-sql.ts b/pm-stack/aggregator/src/aa-batch-sql.ts index 6d5f9517e0..05325a7f33 100644 --- a/pm-stack/aggregator/src/aa-batch-sql.ts +++ b/pm-stack/aggregator/src/aa-batch-sql.ts @@ -552,15 +552,31 @@ select coalesce(( * * Tranche 2 of code#4401 (2026-11-11): the 'configs' and 'cai' sections no * longer read the frozen ainventory.benchmark_results table; they read the - * canonical ainventory.measurement_events store. Canonical events carry no - * sheet import_batch identity, so those two sections ignore the batch - * expression and scope to the latest workbook-import ingest batch — the - * events' own equivalent of the latest import batch — with the filters that - * reproduce the retired table's latest-batch rows exactly (verified by - * full-row EXCEPT comparison before the table was dropped: configs 35/35, - * cai 27/27, zero differences either way). benchmark_results is dropped; + * canonical ainventory.measurement_events store, with the filters that + * reproduce the retired table's rows exactly (verified by full-row EXCEPT + * comparison before the table was dropped: configs 35/35, cai 27/27, zero + * differences either way). benchmark_results is dropped; * measurement_events is the one canonical read path for benchmark facts. + * + * code#8817: measurement events ARE keyed by workbook import — + * ingest_batch_id is the importing batch's ainventory.sources.import_batch + * (verified live 2026-11-12) — but not every workbook import produces + * benchmark events (the imports after 2026-10-26 have none yet). The two + * sections therefore scope AS-OF the selected batch: the newest + * workbook-import event batch imported at or before it. For the latest + * batch that is exactly the newest event batch (the previous behaviour); + * for a historical batch it reconstructs that batch's own sections + * instead of silently mixing the newest sections into a payload cached + * under the historical UUID; a batch older than every event batch gets + * empty sections rather than another batch's data. */ +/** Revision of the aaPayloadSql semantics. The collector validity-keys + * every cached batch payload with this number: entries built under older + * SQL carry no revision (read as 0) and are rebuilt, never served as + * current, once the payload semantics move. Bump when a change alters + * what a cached payload means. (#8817: configs/cai scoping.) */ +export const AA_PAYLOAD_SQL_REVISION = 1; + export function aaPayloadSql(batch: string | null): string { const b = batchExpression(batch); const rankings = RANKINGS_BODY.replace("{{BATCH}}", b); @@ -605,8 +621,13 @@ select jsonb_build_object( 'intelligence', value_num, 'costPerTaskUsd', cost_per_task_usd, 'speedTps', output_tps ) order by model_name, effort) from ainventory.measurement_events br - where br.ingest_batch_id = (select ingest_batch_id from ainventory.measurement_events - where source_kind = 'workbook-import' order by ingested_at desc limit 1) + where br.ingest_batch_id = (select me.ingest_batch_id from ainventory.measurement_events me + where me.source_kind = 'workbook-import' + and me.ingest_batch_id in (select s.import_batch from ainventory.sources s + where s.kind = 'drive-workbook' + and s.imported_at <= (select max(s2.imported_at) from ainventory.sources s2 + where s2.import_batch = ${b} and s2.kind = 'drive-workbook')) + order by me.ingested_at desc limit 1) and br.benchmark like 'AA Intelligence Index%' and br.metric = 'intelligence_index' and br.benchmark_version is null @@ -631,8 +652,13 @@ 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.measurement_events br - where br.ingest_batch_id = (select ingest_batch_id from ainventory.measurement_events - where source_kind = 'workbook-import' order by ingested_at desc limit 1) + where br.ingest_batch_id = (select me.ingest_batch_id from ainventory.measurement_events me + where me.source_kind = 'workbook-import' + and me.ingest_batch_id in (select s.import_batch from ainventory.sources s + where s.kind = 'drive-workbook' + and s.imported_at <= (select max(s2.imported_at) from ainventory.sources s2 + where s2.import_batch = ${b} and s2.kind = 'drive-workbook')) + order by me.ingested_at desc limit 1) and br.benchmark like 'Artificial Analysis Coding Agent Index%' and br.metric = 'cai_index_score' and br.raw->>'benchmark_version' is not null diff --git a/pm-stack/aggregator/src/aa-batches.ts b/pm-stack/aggregator/src/aa-batches.ts index 1010bf3072..07e1c479ba 100644 --- a/pm-stack/aggregator/src/aa-batches.ts +++ b/pm-stack/aggregator/src/aa-batches.ts @@ -34,6 +34,12 @@ export interface AaBatchCacheEntry { * before the overlay was validity-keyed; such entries are * treated as stale and rebuilt. */ pricesFingerprint?: string | null; + /** aaPayloadSql revision the section was built with + * (AA_PAYLOAD_SQL_REVISION in aa-batch-sql.ts). Absent on entries + * written before the revision was stamped; the collector reads those + * as revision 0 and rebuilds them when the SQL semantics have moved + * on (#8817). */ + sqlRevision?: number; builtAt: string; section: AaSection; } @@ -214,6 +220,7 @@ export function isAaBatchCacheEntry(v: unknown): v is AaBatchCacheEntry { (e.pricesFingerprint === undefined || e.pricesFingerprint === null || typeof e.pricesFingerprint === "string") && + (e.sqlRevision === undefined || typeof e.sqlRevision === "number") && typeof e.builtAt === "string" && typeof e.section === "object" && e.section !== null diff --git a/pm-stack/aggregator/test/aa-batches.test.ts b/pm-stack/aggregator/test/aa-batches.test.ts index 8fe65dac73..11e0d90558 100644 --- a/pm-stack/aggregator/test/aa-batches.test.ts +++ b/pm-stack/aggregator/test/aa-batches.test.ts @@ -78,6 +78,27 @@ describe("parameterized payload SQL", () => { expect(sql).toContain("power(intel_eff_norm, 0.7)"); }); + test("configs/cai scope as-of the selected batch, not to the newest event batch (#8817)", () => { + const sql = aaPayloadSql(B2); + // The pre-#8817 predicate pinned both sections to the newest + // workbook-import event batch regardless of the selected batch, so a + // historical payload silently mixed the newest configs/CAI into data + // cached under the historical batch's UUID. + expect(sql).not.toContain("where source_kind = 'workbook-import' order by ingested_at desc limit 1"); + // Both sections now take the as-of mapping: an event batch is eligible + // only when its workbook import is no newer than the selected batch. + const asOf = "s.imported_at <= (select max(s2.imported_at) from ainventory.sources s2"; + expect(sql.split(asOf).length - 1).toBe(2); + expect(sql).toContain("me.ingest_batch_id in (select s.import_batch from ainventory.sources s"); + expect(sql).toContain(`s2.import_batch = '${B2}'::uuid`); + }); + + test("the default (latest) payload keeps the as-of configs/cai scoping (#8817)", () => { + const sql = aaPayloadSql(null); + expect(sql).not.toContain("where source_kind = 'workbook-import' order by ingested_at desc limit 1"); + expect(sql.split("s.imported_at <=").length - 1).toBe(2); + }); + test("the default query still pins v_latest_import_batch", () => { expect(aaPayloadSql(null)).toContain("(select import_batch from ainventory.v_latest_import_batch)"); }); @@ -170,6 +191,13 @@ describe("batch summaries", () => { expect(out.every((b) => b.fingerprint === null)).toBe(true); }); + test("cache entries may carry a numeric sql revision (#8817)", () => { + const base = { batch: B1, configFingerprint: "c", fingerprint: "f", builtAt: "t", section: {} }; + expect(isAaBatchCacheEntry(base)).toBe(true); + expect(isAaBatchCacheEntry({ ...base, sqlRevision: 1 })).toBe(true); + expect(isAaBatchCacheEntry({ ...base, sqlRevision: "1" })).toBe(false); + }); + test("cache names are uuid-only and label is human-readable", () => { expect(aaCacheFileName(B1)).toBe(`aa-batch-${B1}.json`); expect(() => aaCacheFileName("../escape")).toThrow();