diff --git a/docs/data-pipeline.md b/docs/data-pipeline.md index d30e4aa52..b123311dc 100644 --- a/docs/data-pipeline.md +++ b/docs/data-pipeline.md @@ -439,6 +439,22 @@ also unioned back into the window rather than dropped. Only after that volume-we aggregation is the semantic `[0, 1]` bound applied as a guard against residual counter timing skew. Older rows without the component rate series retain the stored-ratio fallback. +### Speculative Decoding Algorithm and Draft Model + +`configs.spec_method` is the matrix label (`mtp`, `draft_model`, `none`) and says neither +which algorithm a server ran nor what drafted. InferenceX results carry `spec_algorithm` +(`mtp`, `dspark`, `dflash`, `eagle3`, in the golden AL identity vocabulary) and +`spec_draft_model` (the drafter's repo, or `native` when the served checkpoint drafts for +itself). Ingest stores both in `metrics`, and the AgentX tooltip shows them, for example +"DFlash (RadixArk/Muse-Spark-Open-DFlash2)" or "DSpark (native)". Points without them fall +back to the label. + +`db:backfill-spec-algorithm` fills both for stored AgentX points from their server logs +(`etl/server-log-speculation.ts`): vLLM's and ATOM's `SpeculativeConfig`, SGLang's +`server_args`, TensorRT-LLM's speculative config, and TileRT's `num_mtp`. Engines often name +the served checkpoint, or a directory inside `/model`, as the draft model, so only a separate +drafter's name (DSpark, DFlash, EAGLE, NextN, MTP or draft) is reported as one. + ### Server-Log Artifact Bundles Server-log artifacts are stored as filename-keyed bundles rather than as a hard-coded list of diff --git a/packages/app/src/components/inference/types.ts b/packages/app/src/components/inference/types.ts index 8f6acd585..5d110e78e 100644 --- a/packages/app/src/components/inference/types.ts +++ b/packages/app/src/components/inference/types.ts @@ -141,6 +141,8 @@ export interface AggDataEntry { kv_p2p_transfer?: string; router_name?: string; router_version?: string; + spec_algorithm?: string; + spec_draft_model?: string; server_gpu_cache_hit_rate?: number; server_external_cache_hit_rate?: number; server_cpu_cache_hit_rate?: number; diff --git a/packages/app/src/components/inference/utils/tooltip-utils.test.ts b/packages/app/src/components/inference/utils/tooltip-utils.test.ts index e78314597..6109a17e4 100644 --- a/packages/app/src/components/inference/utils/tooltip-utils.test.ts +++ b/packages/app/src/components/inference/utils/tooltip-utils.test.ts @@ -463,6 +463,28 @@ describe('generateTooltipContent', () => { ).not.toContain('data-action="view-logs"'); }); + it.each([ + [{ spec_decoding: 'draft_model' }, 'Draft Model'], + [ + { + spec_decoding: 'draft_model', + spec_algorithm: 'dflash', + spec_draft_model: 'RadixArk/Muse-Spark-Open-DFlash2', + }, + 'DFlash (RadixArk/Muse-Spark-Open-DFlash2)', + ], + [ + { spec_decoding: 'mtp', spec_algorithm: 'dspark', spec_draft_model: 'native' }, + 'DSpark (native)', + ], + [{ spec_decoding: 'none', spec_algorithm: 'dspark', spec_draft_model: 'native' }, 'Off'], + ])('labels speculative decoding by what the server ran: %j', (fields, label) => { + const html = generateTooltipContent( + tooltipConfig({ data: pt({ id: 3, benchmark_type: 'agentic_traces', ...fields }) }), + ); + expect(html).toContain(`Speculative Decoding: ${label}`); + }); + it('routes fixed-sequence log actions to the fixed benchmark log viewer', () => { const html = generateTooltipContent( tooltipConfig({ diff --git a/packages/app/src/components/inference/utils/tooltipUtils.ts b/packages/app/src/components/inference/utils/tooltipUtils.ts index b38fc9655..f4a4a13f7 100644 --- a/packages/app/src/components/inference/utils/tooltipUtils.ts +++ b/packages/app/src/components/inference/utils/tooltipUtils.ts @@ -514,6 +514,7 @@ const AGENTIC_STRINGS = { en: { speculativeDecoding: 'Speculative Decoding', off: 'Off', + native: 'native', requests: 'Requests', promptTokens: 'Prompt Tokens', generatedTokens: 'Generated Tokens', @@ -521,26 +522,39 @@ const AGENTIC_STRINGS = { zh: { speculativeDecoding: '投机解码', off: '关闭', + native: '原生', requests: '请求', promptTokens: '提示 token', generatedTokens: '生成 token', }, } as const; +const SPEC_ALGORITHM_LABELS: Record = { + mtp: 'MTP', + dspark: 'DSpark', + dflash: 'DFlash', + eagle: 'EAGLE', + eagle3: 'EAGLE3', + nextn: 'NextN', +}; + +const speculativeDecodingLabel = ( + d: InferenceData, + t: (typeof AGENTIC_STRINGS)[Locale], +): string => { + const specMethod = d.spec_decoding ?? 'none'; + if (specMethod === 'none' || specMethod === '') return t.off; + if (!d.spec_algorithm) return specMethodDisplayLabel(d.model, specMethod); + const algorithm = SPEC_ALGORITHM_LABELS[d.spec_algorithm] ?? d.spec_algorithm.toUpperCase(); + const draft = d.spec_draft_model; + return `${algorithm} (${!draft || draft === 'native' ? t.native : escapeHtml(draft)})`; +}; + const generateAgenticHTML = (d: InferenceData, locale: Locale): string => { if (d.benchmark_type !== 'agentic_traces') return ''; const t = AGENTIC_STRINGS[locale]; - const parts: string[] = []; - const specMethod = d.spec_decoding ?? 'none'; - parts.push( - tooltipLine( - t.speculativeDecoding, - specMethod === 'none' || specMethod === '' - ? t.off - : specMethodDisplayLabel(d.model, specMethod), - ), - ); + const parts: string[] = [tooltipLine(t.speculativeDecoding, speculativeDecodingLabel(d, t))]; if (d.num_requests_total !== undefined && d.num_requests_successful !== undefined) { const successPct = diff --git a/packages/app/src/lib/api/api-route-catalog.ts b/packages/app/src/lib/api/api-route-catalog.ts index 5127b27ef..d3a27bf24 100644 --- a/packages/app/src/lib/api/api-route-catalog.ts +++ b/packages/app/src/lib/api/api-route-catalog.ts @@ -1478,7 +1478,7 @@ export const apiContractSourceDigests = [ }, { source: 'src/lib/benchmarks/benchmark-transform.ts', - sourceSha256: '97b97962a9c09df7d7abfe84b6f4cb78d0b0500c9e41bf1fd785d040fcb59ad4', + sourceSha256: '7ade60009996367fbd6bfcbcfd7ba155fd96e1676dcb0d320ca26821f948ba7a', reviewArea: { en: 'Raw benchmark means and derived reciprocal mean-TPOT interactivity used by Dashboard and read-only views.', zh: '仪表板和只读视图共用的原始 benchmark 均值与 mean TPOT 倒数形式的 interactivity。', diff --git a/packages/app/src/lib/benchmarks/benchmark-transform.ts b/packages/app/src/lib/benchmarks/benchmark-transform.ts index 00105e1ac..6338ebe78 100644 --- a/packages/app/src/lib/benchmarks/benchmark-transform.ts +++ b/packages/app/src/lib/benchmarks/benchmark-transform.ts @@ -430,6 +430,8 @@ export function rowToAggDataEntry( kv_p2p_transfer: stringMetric('kv_p2p_transfer'), router_name: stringMetric('router_name'), router_version: stringMetric('router_version'), + spec_algorithm: stringMetric('spec_algorithm'), + spec_draft_model: stringMetric('spec_draft_model'), server_gpu_cache_hit_rate: m.server_gpu_cache_hit_rate, server_external_cache_hit_rate: m.server_external_cache_hit_rate, server_cpu_cache_hit_rate: m.server_cpu_cache_hit_rate, diff --git a/packages/constants/src/framework-aliases.ts b/packages/constants/src/framework-aliases.ts index 6acaa805b..a9b6290b8 100644 --- a/packages/constants/src/framework-aliases.ts +++ b/packages/constants/src/framework-aliases.ts @@ -40,6 +40,7 @@ export const FRAMEWORK_LABELS: Record = { ]), ), mtp: 'MTP', + draft_model: 'Draft Model', aiperf: 'AIPerf', }; diff --git a/packages/db/package.json b/packages/db/package.json index 265abf276..ad1ebd194 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -41,6 +41,7 @@ "db:backfill-runtime-metadata": "bun --env-file=../../.env src/backfill-runtime-metadata.ts", "db:backfill-sequence-length-sketches": "bun --env-file=../../.env src/backfill-sequence-length-sketches.ts", "db:backfill-server-log-files": "bun --env-file=../../.env src/backfill-server-log-files.ts", + "db:backfill-spec-algorithm": "bun --env-file=../../.env src/backfill-spec-algorithm.ts", "db:compact-server-logs": "bun --env-file=../../.env src/compact-server-logs.ts", "db:reset": "bun --env-file=../../.env src/reset-db.ts", "db:sync-public": "bun --env-file=../../.env src/sync-public-db.ts", diff --git a/packages/db/src/backfill-spec-algorithm.ts b/packages/db/src/backfill-spec-algorithm.ts new file mode 100644 index 000000000..4e8629a99 --- /dev/null +++ b/packages/db/src/backfill-spec-algorithm.ts @@ -0,0 +1,27 @@ +import { hasNoSslFlag } from './cli-utils.js'; +import { createAdminSql } from './etl/db-utils.js'; +import { runBackfillMain, runCandidateIdBackfill } from './lib/backfill-runner.js'; +import { + backfillSpecAlgorithm, + loadSpecAlgorithmCandidates, +} from './lib/spec-algorithm-backfill.js'; + +const sql = createAdminSql({ noSsl: hasNoSslFlag(), max: 2, onnotice: () => {} }); + +async function main(): Promise { + console.log('=== backfill-spec-algorithm ==='); + await runCandidateIdBackfill( + () => loadSpecAlgorithmCandidates(sql), + async (id) => { + const speculation = await backfillSpecAlgorithm(sql, id); + if (!speculation) { + console.log(` id=${id}: no speculative config in the server log`); + return 'skipped'; + } + console.log(` id=${id}: ${speculation.spec_algorithm} (${speculation.spec_draft_model})`); + return 'ok'; + }, + ); +} + +runBackfillMain('backfill-spec-algorithm', sql, main); diff --git a/packages/db/src/etl/benchmark-mapper.ts b/packages/db/src/etl/benchmark-mapper.ts index d3c015821..517d82918 100644 --- a/packages/db/src/etl/benchmark-mapper.ts +++ b/packages/db/src/etl/benchmark-mapper.ts @@ -64,6 +64,8 @@ const NON_METRIC_KEYS = new Set([ 'kv_offload_backend', 'kv_p2p_transfer', 'router', + 'spec_algorithm', + 'spec_draft_model', 'request_metrics', 'server_metrics', 'dataset', diff --git a/packages/db/src/etl/runtime-metadata.ts b/packages/db/src/etl/runtime-metadata.ts index a46539847..9064f710e 100644 --- a/packages/db/src/etl/runtime-metadata.ts +++ b/packages/db/src/etl/runtime-metadata.ts @@ -5,6 +5,8 @@ export interface RuntimeMetadata { kv_p2p_transfer?: string; router_name?: string; router_version?: string; + spec_algorithm?: string; + spec_draft_model?: string; } function nonEmptyString(value: unknown): string | undefined { @@ -42,5 +44,10 @@ export function extractRuntimeMetadata(row: Record): RuntimeMet if (router.version) metadata.router_version = router.version; } + const algorithm = nonEmptyString(row.spec_algorithm); + if (algorithm) metadata.spec_algorithm = algorithm; + const draftModel = nonEmptyString(row.spec_draft_model); + if (draftModel) metadata.spec_draft_model = draftModel; + return metadata; } diff --git a/packages/db/src/etl/server-log-speculation.test.ts b/packages/db/src/etl/server-log-speculation.test.ts new file mode 100644 index 000000000..1485c8dc4 --- /dev/null +++ b/packages/db/src/etl/server-log-speculation.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest'; + +import { speculationFromServerLog } from './server-log-speculation'; + +describe('speculationFromServerLog', () => { + it.each([ + [ + 'vLLM with a separate drafter copied to local disk', + 'kimik3', + "speculative_config=SpeculativeConfig(method='dspark', model='/data/models/Kimi-K3-DSpark', num_spec_tokens=7)", + { spec_algorithm: 'dspark', spec_draft_model: 'Inferact/Kimi-K3-DSpark' }, + ], + [ + 'vLLM drafting from a directory inside the served checkpoint', + 'minimaxm31flash', + "speculative_config=SpeculativeConfig(method='dspark', model='/model/dspark', num_spec_tokens=7)", + { spec_algorithm: 'dspark', spec_draft_model: 'native' }, + ], + [ + 'SGLang naming the served checkpoint as its MTP drafter', + 'qwen3.8next', + "'speculative_algorithm': 'EAGLE'\n'speculative_draft_model_path': 'nvidia/Qwen3.8-Flash-Next-NVFP4'", + { spec_algorithm: 'mtp', spec_draft_model: 'native' }, + ], + [ + 'SGLang DFlash with a separate drafter repo', + 'musespark', + "'speculative_algorithm': 'DFLASH'\n'speculative_draft_model_path': 'RadixArk/Muse-Spark-Open-DFlash2'", + { spec_algorithm: 'dflash', spec_draft_model: 'RadixArk/Muse-Spark-Open-DFlash2' }, + ], + [ + 'TensorRT-LLM engine args with a local drafter copy', + 'musespark', + "'speculative_config': {'attention_backend': 'VANILLA', 'decoding_type': 'DFlash', 'max_draft_len': 7, 'speculative_model': '/raid/common-models/muse-spark-open-dflash2'}", + { spec_algorithm: 'dflash', spec_draft_model: 'RadixArk/Muse-Spark-Open-DFlash2' }, + ], + [ + "TensorRT-LLM's EAGLE3 config for MiniMax-M3", + 'minimaxm3', + "speculative_model=PosixPath('/data/models/MiniMax-M3-EAGLE3-GQA')\ndecoding_type='Eagle3'", + { spec_algorithm: 'eagle3', spec_draft_model: 'Inferact/MiniMax-M3-EAGLE3-GQA' }, + ], + [ + 'ATOM loading a separate drafter after the target', + 'kimik3', + "SpeculativeConfig(method='dspark', num_spec_tokens=4)\nLoading safetensors shards[moonshotai/Kimi-K3]\nLoading safetensors shards[Inferact/Kimi-K3-DSpark]", + { spec_algorithm: 'dspark', spec_draft_model: 'Inferact/Kimi-K3-DSpark' }, + ], + [ + "TileRT's MTP heads", + 'glm5.3', + 'num_mtp 3', + { spec_algorithm: 'mtp', spec_draft_model: 'native' }, + ], + ])('%s', (_, modelPrefix, log, expected) => { + expect(speculationFromServerLog(log, modelPrefix)).toEqual(expected); + }); + + it.each([ + 'speculative_config=None', + "'speculative_algorithm': None\n'speculative_draft_model_path': None", + 'num_mtp 0', + '', + ])('reports nothing for a server that did not draft: %j', (log) => { + expect(speculationFromServerLog(log, 'glm5.2')).toBeNull(); + }); +}); diff --git a/packages/db/src/etl/server-log-speculation.ts b/packages/db/src/etl/server-log-speculation.ts new file mode 100644 index 000000000..a135ba25c --- /dev/null +++ b/packages/db/src/etl/server-log-speculation.ts @@ -0,0 +1,105 @@ +/** + * The speculative decoding algorithm and draft model a benchmark's server actually ran, read + * from its server log in the vocabulary InferenceX results use (`spec_algorithm`, + * `spec_draft_model`). Results written before InferenceX emitted those fields only have the + * matrix label, which says neither. + */ + +export interface ServerLogSpeculation { + spec_algorithm: string; + spec_draft_model: string; +} + +/** + * Lines (or line fragments) that state the speculative config, as one Postgres ARE so callers + * can extract them server-side instead of downloading whole logs. + */ +export const SPECULATION_LOG_PATTERN = [ + String.raw`SpeculativeConfig\([^)]*\)`, + String.raw`'speculative_algorithm': '[^']*'`, + String.raw`speculative_algorithm='[^']*'`, + String.raw`'speculative_draft_model_path': '[^']*'`, + String.raw`speculative_draft_model_path='[^']*'`, + String.raw`'decoding_type': '[^']*'`, + String.raw`decoding_type='[^']*'`, + String.raw`'speculative_model': '[^']*'`, + String.raw`speculative_model=PosixPath\('[^']*'\)`, + String.raw`speculative_model='[^']*'`, + String.raw`draft model loaded from [^ \n]+`, + String.raw`Loading safetensors shards\[[^]\n]+\]`, + String.raw`num_mtp [0-9]+`, +].join('|'); + +// Engines often name the served checkpoint (or a directory inside it) as the draft model; only +// a separate drafter's name says it drafts. +const SEPARATE_DRAFTER = /dspark|dflash|eagle|nextn|mtp|draft/iu; +// Separate drafters servers loaded from a local copy, by lowercase directory name. +const DRAFTER_REPOS: Readonly> = { + 'kimi-k3-dspark': 'Inferact/Kimi-K3-DSpark', + 'inferact-kimi-k3-dspark': 'Inferact/Kimi-K3-DSpark', + 'minimax-m3-eagle3': 'Inferact/MiniMax-M3-EAGLE3', + 'minimax-m3-eagle3-gqa': 'Inferact/MiniMax-M3-EAGLE3-GQA', + 'muse-spark-open-dflash2': 'RadixArk/Muse-Spark-Open-DFlash2', + 'deepseek-r1-nextn': 'SGLang/DeepSeek-R1-NextN', +}; + +const HF_CACHE_REPO = /models--(?[^/]+)--(?[^/]+)/u; +const REPO_ID = /^[\w.-]+\/[\w.-]+$/u; + +function firstCapture(text: string, patterns: readonly RegExp[]): string | undefined { + for (const pattern of patterns) { + for (const match of text.matchAll(new RegExp(pattern.source, `${pattern.flags}gu`))) { + const value = match.groups?.v; + if (value && value !== 'None') return value; + } + } + return undefined; +} + +function normalizeAlgorithm(modelPrefix: string, method: string): string { + const lower = method.toLowerCase(); + if (lower === 'eagle' || lower === 'nextn') return modelPrefix === 'minimaxm3' ? 'eagle3' : 'mtp'; + return lower; +} + +function drafterName(path: string): string { + const cached = HF_CACHE_REPO.exec(path); + if (cached?.groups) return `${cached.groups.org}/${cached.groups.name}`; + if (REPO_ID.test(path) && !path.startsWith('/')) return path; + const base = path.replace(/\/+$/u, '').split('/').pop() ?? path; + return DRAFTER_REPOS[base.toLowerCase()] ?? base; +} + +export function speculationFromServerLog( + text: string, + modelPrefix: string, +): ServerLogSpeculation | null { + const method = + firstCapture(text, [ + /SpeculativeConfig\(method='(?[^']+)'/, + /'speculative_algorithm': '(?[^']+)'/, + /speculative_algorithm='(?[^']+)'/, + /'decoding_type': '(?[^']+)'/, + /decoding_type='(?[^']+)'/, + ]) ?? (/num_mtp [1-9]/u.test(text) ? 'mtp' : undefined); + if (!method) return null; + + const draft = firstCapture(text, [ + /SpeculativeConfig\([^)]*model='(?[^']+)'/, + /'speculative_draft_model_path': '(?[^']+)'/, + /speculative_draft_model_path='(?[^']+)'/, + /'speculative_model': '(?[^']+)'/, + /speculative_model=PosixPath\('(?[^']+)'\)/, + /speculative_model='(?[^']+)'/, + /draft model loaded from (?[^ \n]+)/, + /Loading safetensors shards\[(?[^\]]*(?:dspark|dflash|eagle|nextn|mtp|draft)[^\]]*)\]/i, + ]); + // Recipes mount the served checkpoint at /model; a drafter inside it ships with the model. + const name = + draft === undefined || /^\/model(?:\/|$)/u.test(draft) ? undefined : drafterName(draft); + return { + spec_algorithm: normalizeAlgorithm(modelPrefix, method), + spec_draft_model: + name === undefined || !SEPARATE_DRAFTER.test(name.split('/').pop() ?? name) ? 'native' : name, + }; +} diff --git a/packages/db/src/lib/spec-algorithm-backfill.test.ts b/packages/db/src/lib/spec-algorithm-backfill.test.ts new file mode 100644 index 000000000..394d7076f --- /dev/null +++ b/packages/db/src/lib/spec-algorithm-backfill.test.ts @@ -0,0 +1,81 @@ +import type { PGlite } from '@electric-sql/pglite'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { backfillSpecAlgorithm, loadSpecAlgorithmCandidates } from './spec-algorithm-backfill'; +import { migratedPglite, pgliteSql, type PgliteSql } from './test-pglite'; + +let db: PGlite; +let sql: PgliteSql; + +async function point( + id: number, + { + spec, + log, + file, + metrics = {}, + }: { spec: string; log?: string; file?: string; metrics?: object }, +) { + const [config] = await sql` + insert into configs (hardware, framework, model, precision, spec_method, disagg, is_multinode, + prefill_tp, prefill_ep, prefill_dp_attention, prefill_num_workers, + decode_tp, decode_ep, decode_dp_attention, decode_num_workers, num_prefill_gpu, num_decode_gpu) + values ('b300', 'vllm', 'kimik3', 'fp4', ${spec}, false, false, 8, 1, false, 0, 8, 1, false, 0, 8, 8) + on conflict (hardware, framework, model, precision, spec_method, disagg, is_multinode, + prefill_tp, prefill_ep, prefill_dp_attention, prefill_num_workers, + decode_tp, decode_ep, decode_dp_attention, decode_num_workers, num_prefill_gpu, num_decode_gpu) + do update set hardware = excluded.hardware + returning id + `; + await sql`insert into server_logs (id, server_log) values (${id}, ${log ?? ''})`; + if (file) { + await sql`insert into server_log_files (server_log_id, file_name, log_text) + values (${id}, 'decode.log', ${file})`; + } + await sql` + insert into benchmark_results (id, workflow_run_id, config_id, benchmark_type, date, conc, metrics, + server_log_id, offload_mode) + values (${id}, 1, ${config!.id}, 'agentic_traces', '2026-08-16', ${id}, ${JSON.stringify(metrics)}::jsonb, + ${id}, 'on') + `; +} + +beforeAll(async () => { + db = await migratedPglite(); + sql = pgliteSql(db); + await sql` + insert into workflow_runs (id, github_run_id, run_attempt, name, head_sha, head_branch, created_at, date) + values (1, 31893747354, 2, 'run', 'sha', 'main', '2026-08-16T00:00:00Z', '2026-08-16') + `; + const drafting = `INFO [core.py:122] Initializing a V1 LLM engine with config: model='/scratch/models/Kimi-K3', speculative_config=SpeculativeConfig(method='dspark', model='/data/models/Kimi-K3-DSpark', num_spec_tokens=7), tokenizer='x'`; + await point(1, { spec: 'mtp', file: drafting }); + await point(2, { spec: 'mtp', log: "speculative_config=None, tokenizer='x'" }); + await point(3, { spec: 'none', log: drafting }); + await point(4, { spec: 'mtp', log: drafting, metrics: { spec_algorithm: 'mtp' } }); +}); + +afterAll(async () => { + await db.close(); +}); + +describe('spec algorithm backfill', () => { + it('selects labeled-speculative AgentX points that lack the algorithm', async () => { + expect(await loadSpecAlgorithmCandidates(sql)).toEqual([1, 2]); + }); + + it('merges what the server log says it ran and leaves non-drafting servers alone', async () => { + expect(await backfillSpecAlgorithm(sql, 1)).toEqual({ + spec_algorithm: 'dspark', + spec_draft_model: 'Inferact/Kimi-K3-DSpark', + }); + expect(await backfillSpecAlgorithm(sql, 2)).toBeNull(); + const rows = await sql<{ id: number; metrics: Record }[]>` + select id, metrics from benchmark_results where id in (1, 2) order by id + `; + expect(rows.map((row) => row.metrics)).toEqual([ + { spec_algorithm: 'dspark', spec_draft_model: 'Inferact/Kimi-K3-DSpark' }, + {}, + ]); + expect(await loadSpecAlgorithmCandidates(sql)).toEqual([2]); + }); +}); diff --git a/packages/db/src/lib/spec-algorithm-backfill.ts b/packages/db/src/lib/spec-algorithm-backfill.ts new file mode 100644 index 000000000..765e1ccb3 --- /dev/null +++ b/packages/db/src/lib/spec-algorithm-backfill.ts @@ -0,0 +1,50 @@ +import type { Sql } from '../etl/db-utils.js'; +import { + SPECULATION_LOG_PATTERN, + type ServerLogSpeculation, + speculationFromServerLog, +} from '../etl/server-log-speculation.js'; + +// Engines print their speculative config at startup; the head of each log file is enough. +const LOG_HEAD_CHARS = 40_000_000; + +/** AgentX points labeled speculative whose metrics do not yet say what the server ran. */ +export async function loadSpecAlgorithmCandidates(sql: Sql): Promise { + const rows = await sql<{ id: number }[]>` + select br.id from benchmark_results br + join configs c on c.id = br.config_id + where br.benchmark_type = 'agentic_traces' and c.spec_method <> 'none' + and br.error is null and br.server_log_id is not null + and br.metrics ->> 'spec_algorithm' is null + order by br.id + `; + return rows.map((row) => Number(row.id)); +} + +/** Read one point's speculative config from its stored server log and merge it into metrics. */ +export async function backfillSpecAlgorithm( + sql: Sql, + id: number, +): Promise { + const [row] = await sql<{ model: string; hits: string[] }[]>` + select c.model, + array( + select distinct (regexp_matches(substr(src.t, 1, ${LOG_HEAD_CHARS}), ${`(${SPECULATION_LOG_PATTERN})`}, 'g'))[1] + from ( + select sl.server_log as t from server_logs sl where sl.id = br.server_log_id + union all + select f.log_text from server_log_files f where f.server_log_id = br.server_log_id + ) src + ) as hits + from benchmark_results br join configs c on c.id = br.config_id + where br.id = ${id} + `; + const speculation = row ? speculationFromServerLog(row.hits.join('\n'), row.model) : null; + if (!speculation) return null; + await sql` + update benchmark_results + set metrics = metrics || ${sql.json(speculation as unknown as Record)} + where id = ${id} + `; + return speculation; +}