Skip to content
Merged
338 changes: 219 additions & 119 deletions pm-stack/aggregator/scripts/collect-fleet-feed.ts

Large diffs are not rendered by default.

635 changes: 635 additions & 0 deletions pm-stack/aggregator/src/aa-batch-sql.ts

Large diffs are not rendered by default.

221 changes: 221 additions & 0 deletions pm-stack/aggregator/src/aa-batches.ts
Original file line number Diff line number Diff line change
@@ -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<string, number> | 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<string, number> | null {
if (typeof v !== "object" || v === null || Array.isArray(v)) return null;
const out: Record<string, number> = {};
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<string>();
for (const entry of raw) {
if (typeof entry !== "object" || entry === null) continue;
const r = entry as Record<string, unknown>;
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<string, unknown>;
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<AaBatchIndexRow, "name" | "importedAt" | "driveModifiedAt">): 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<string, unknown>)
.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<string, unknown>;
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<string, { fingerprint: string | null; cached: boolean }>,
): AaBatchSummary[] {
const kept: AaBatchSummary[] = [];
const seen = new Set<string>();
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<AaBatchCacheEntry>;
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
);
}
33 changes: 33 additions & 0 deletions pm-stack/aggregator/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1069,13 +1069,46 @@ 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<string, number> | 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";
/** ISO timestamp of the collector run that built the section. */
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[];
Expand Down
32 changes: 28 additions & 4 deletions pm-stack/aggregator/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];
Expand Down Expand Up @@ -5815,13 +5815,37 @@ export function renderAa(section: AaFeedSection | null, provenance: Provenance,
</div>`
: `<div class="banner">The collector has not carried the fleet catalog yet — it is built from the same <code>.opencode/opencode.jsonc</code> read as the coverage section and appears once a collector build that knows it has run. No catalog is shown rather than a stale one.</div>`;
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) =>
`<option value="${esc(b.importBatch)}"${b.importBatch === s.batch ? " selected" : ""}>${esc(b.label)}${b.importBatch === latestBatch ? " (latest)" : ""}${b.cached ? "" : " — not cached yet"}</option>`,
)
.join("");
const batchSelector =
batches.length > 1
? `<div class="card" id="aa-batch-picker"><label><strong>Dataset version</strong>
<select id="xf-batch" onchange="location.href = this.value ? '/aa?batch=' + encodeURIComponent(this.value) : '/aa'">${batchOptions}</select></label>
<span class="muted">Older versions show that import's rankings, thresholds, timings and coding-agent rows. The latest is the default. Token prices remain the current <code>v_current_prices</code> overlay, not a historical price snapshot.</span></div>`
: "";
const body = `<h1>Cost Explorer</h1>
${s.stale ? `<div class="banner">The latest collection failed (${esc(s.staleReason ?? "unknown error")}) — showing the last good data, collected ${fmtDate(s.generatedAt)}. It refreshes automatically on the next successful collection.</div>` : ""}
<p class="muted">${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 <code>${esc(s.batch.slice(0, 8))}…</code>. Machine-first: <a href="/api/aa.json">/api/aa.json</a>.</p>
${batchSelector}
<p class="muted">${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 <code>${esc(s.batch.slice(0, 8))}…</code>${selectedIsLatest ? " (latest)" : " (historical version)"}. Machine-first: <a href="/api/aa.json${selectedIsLatest ? "" : `?batch=${encodeURIComponent(s.batch)}`}">/api/aa.json${selectedIsLatest ? "" : `?batch=${encodeURIComponent(s.batch)}`}</a>.</p>
<div class="card"><strong>Provenance</strong><br>
<span class="muted">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.</span>
<span class="muted">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 <code>v_current_prices</code>, a current-price overlay that is not scoped to the selected dataset version.</span>
<ul>${sourcesHtml || '<li class="muted">source files not recorded for this batch</li>'}</ul></div>
<div class="xtabs" role="tablist"><button type="button" class="xtab" data-xtab="aa">AA Explorer</button><button type="button" class="xtab" data-xtab="models">Model Explorer</button></div>
<div class="card xpl-filters" id="xpl-filters">
Expand Down
4 changes: 2 additions & 2 deletions pm-stack/aggregator/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1779,10 +1779,10 @@ async function handler(req: Request): Promise<Response> {
}

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" });
}

Expand Down
6 changes: 4 additions & 2 deletions pm-stack/aggregator/src/source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@ export interface Source {
dns(): Promise<DnsSection | null>;
/** 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<AaFeedSection | null>;
* ({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<AaFeedSection | null>;
/** The identity registry (#906 §3): durable session records, oldest sources merged. */
registry(): Promise<SessionRecord[]>;
/** The GitHub Project pool (#910 stage 5) from the fleet feed; empty when not collected. */
Expand Down
Loading
Loading