SPB Git

Repository Public MIT

usage.test.ts 24.5 KB 387 lines typescript

1// @vitest-environment node2/**3 * =============================================================================4 *                  SP BOUCHER | SOFTWARE & RESEARCH5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : VQuant9 * File             : server/next/usage.test.ts10 * Module           : server11 * Repository       : https://git.spboucher.ai/vquant12 * Project Website  : https://vquant.spboucher.ai13 * Created          : 2026-11-2014 * Last Modified    : 2026-11-2015 *16 * Author           : Simon-Pierre Boucher17 * Position         : Professor of Finance18 * Institution      : Université du Québec en Outaouais (UQO)19 * Organization     : SP Boucher20 * Website          : https://spboucher.ai21 * Git              : https://git.spboucher.ai22 *23 * Preferred Contact: contact@spboucher.ai24 * Development      : dev@spboucher.ai25 * Support          : support@spboucher.ai26 * Security/Admin   : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * SPDX Identifier  : MIT35 * License          : MIT License36 * License File     : LICENSE37 *38 * Do not embed credentials, private keys, access tokens,39 * certificates or confidential personal information.40 *41 * =============================================================================42 * END OF SP BOUCHER SOURCE HEADER43 * =============================================================================44 */4546/**47 * Usage accounting, budgets, trace and provenance (contract §2.3, §2.4) on a temporary database. No model is called.48 */49import { afterAll, beforeAll, describe, expect, it } from "vitest";50import { bootTestApp, type TestApp } from "./testkit";51import { AVAILABLE_TOOLS } from "../services/claude/toolDefinitions";52import { AGENT_TOOLS } from "../services/claude/agentTools";5354let t: TestApp;55let usage: typeof import("./usage");56let trace: typeof import("./trace");57let runtime: typeof import("../services/toolRuntime");5859beforeAll(async () => {60  t = await bootTestApp(async (app) => {61    (await import("./usage")).registerUsageRoutes(app);62    (await import("./trace")).registerTraceRoutes(app);63  });64  usage = await import("./usage");65  trace = await import("./trace");66  runtime = await import("../services/toolRuntime");67});68afterAll(async () => {69  await t.close();70});7172describe("usage math", () => {73  it("prices a call from a price per million tokens, and refuses to price without one", () => {74    expect(usage.costFromPricing({ inputPerMTok: 2, outputPerMTok: 10 }, 1_000_000, 100_000)).toBeCloseTo(3, 10);75    expect(usage.costFromPricing({ inputPerMTok: 0, outputPerMTok: 0 }, 5000, 5000)).toBe(0);76    expect(usage.costFromPricing(null, 5000, 5000)).toBeNull();77    expect(usage.costFromPricing(undefined, 0, 0)).toBeNull();78  });7980  it("sums by model and role; a total with an unpriced call is null, with the priced part beside it", () => {81    const s = usage.summarizeUsage([82      { model: "lead-m", provider: "anthropic", role: "lead", inputTokens: 1000, outputTokens: 200, costUsd: 0.01 },83      { model: "lead-m", provider: "anthropic", role: "lead", inputTokens: 3000, outputTokens: 300, costUsd: 0.02 },84      { model: "worker-m", provider: "anthropic", role: "worker", inputTokens: 500, outputTokens: 50, costUsd: 0.001 },85      { model: "worker-m", provider: "anthropic", role: "auditor", inputTokens: 100, outputTokens: 10, costUsd: 0.0005 },86    ]);87    expect(s).toMatchObject({ inputTokens: 4600, outputTokens: 560, costUsd: 0.0315, knownCostUsd: 0.0315 });88    expect(s.byModel).toEqual([89      { model: "lead-m", provider: "anthropic", role: "lead", calls: 2, inputTokens: 4000, outputTokens: 500, costUsd: 0.03 },90      { model: "worker-m", provider: "anthropic", role: "worker", calls: 1, inputTokens: 500, outputTokens: 50, costUsd: 0.001 },91      { model: "worker-m", provider: "anthropic", role: "auditor", calls: 1, inputTokens: 100, outputTokens: 10, costUsd: 0.0005 },92    ]);9394    const mixed = usage.summarizeUsage([95      { model: "local:q", provider: "local", role: "lead", inputTokens: 10, outputTokens: 5, costUsd: null },96      { model: "worker-m", provider: "anthropic", role: "worker", inputTokens: 10, outputTokens: 5, costUsd: 0.25 },97    ]);98    expect(mixed.costUsd).toBeNull();99    expect(mixed.knownCostUsd).toBe(0.25);100    expect(mixed.byModel.find((g) => g.model === "local:q")!.costUsd).toBeNull();101    expect(mixed.byModel.find((g) => g.model === "worker-m")!.costUsd).toBe(0.25);102    expect(usage.summarizeUsage([])).toEqual({ inputTokens: 0, outputTokens: 0, costUsd: 0, knownCostUsd: 0, byModel: [] });103  });104});105106describe("usage ledger", () => {107  it("writes one row per model call with the generation and session, cost NULL when unknown", () => {108    const meter = new usage.UsageMeter({ owner: "alice", sessionId: "s1", generationId: "g1" });109    meter.add({ model: "lead-m", provider: "anthropic", role: "lead", inputTokens: 1200, outputTokens: 300, costUsd: 0.5 });110    meter.add({ model: "worker-m", provider: "anthropic", role: "worker", inputTokens: 800, outputTokens: 100, costUsd: 0.1 });111    meter.add({ model: "openrouter:x/y", provider: "openrouter", role: "lead", inputTokens: 50, outputTokens: 20, costUsd: null });112    const rows = t.db.prepare("SELECT owner, session_id, generation_id, model, provider, role, input_tokens, output_tokens, cost_usd FROM vq_usage WHERE generation_id = 'g1' ORDER BY id").all();113    expect(rows).toEqual([114      { owner: "alice", session_id: "s1", generation_id: "g1", model: "lead-m", provider: "anthropic", role: "lead", input_tokens: 1200, output_tokens: 300, cost_usd: 0.5 },115      { owner: "alice", session_id: "s1", generation_id: "g1", model: "worker-m", provider: "anthropic", role: "worker", input_tokens: 800, output_tokens: 100, cost_usd: 0.1 },116      { owner: "alice", session_id: "s1", generation_id: "g1", model: "openrouter:x/y", provider: "openrouter", role: "lead", input_tokens: 50, output_tokens: 20, cost_usd: null },117    ]);118    expect(meter.knownCostUsd()).toBeCloseTo(0.6, 10);119    expect(meter.summary().costUsd).toBeNull();120    expect(usage.usageOfGeneration("alice", "g1")).toEqual(meter.summary());121    expect(usage.usageOfGeneration("bob", "g1").byModel).toEqual([]); // another person's generation is not readable122  });123124  it("GET /api/v2/usage reports the person's own totals, by day and by model", async () => {125    new usage.UsageMeter({ owner: "bob", sessionId: "s2", generationId: "g2" }).add({ model: "lead-m", provider: "anthropic", role: "lead", inputTokens: 10, outputTokens: 10, costUsd: 9 });126    const r = await t.api("alice", "GET", "/api/v2/usage?days=7");127    expect(r.status).toBe(200);128    expect(r.body.totals).toEqual({ calls: 3, inputTokens: 2050, outputTokens: 420, costUsd: null, knownCostUsd: 0.6, unpricedCalls: 1 });129    expect(r.body.byDay).toHaveLength(1);130    expect(r.body.byDay[0].date).toBe(new Date().toISOString().slice(0, 10));131    expect(r.body.byModel.map((m: any) => [m.model, m.role, m.costUsd])).toEqual([["lead-m", "lead", 0.5], ["worker-m", "worker", 0.1], ["openrouter:x/y", "lead", null]]);132    const bob = await t.api("bob", "GET", "/api/v2/usage");133    expect(bob.body.totals).toMatchObject({ calls: 1, costUsd: 9 });134    expect(bob.body.days).toBe(30);135    expect((await t.api("alice", "GET", "/api/v2/usage?days=0")).status).toBe(400);136    expect((await t.api(null, "GET", "/api/v2/usage")).status).toBe(401);137  });138});139140describe("budget", () => {141  it("reports each limit once, then keeps telling the agents to conclude", () => {142    let spent = 0;143    let clock = 0;144    const hits: unknown[] = [];145    const guard = new usage.BudgetGuard({ maxCostUsd: 1, maxMinutes: 10 }, { startedAt: 0, spentUsd: () => spent, now: () => clock, onExceeded: (h) => hits.push(h) });146    expect(guard.check()).toBeNull();147    spent = 0.99;148    clock = 9.9 * 60_000;149    expect(guard.check()).toBeNull();150    spent = 1.234;151    expect(guard.check()).toMatch(/about \$1\.23 spent for a limit of \$1/);152    expect(hits).toEqual([{ kind: "cost", limit: 1, spent: 1.23 }]);153    spent = 5;154    expect(guard.check()).toMatch(/\$1\.23/); // the hit is reported as it was when the limit was passed155    expect(hits).toHaveLength(1);156    clock = 11 * 60_000;157    expect(guard.check()).toMatch(/11 minutes elapsed for a limit of 10/);158    expect(hits).toEqual([{ kind: "cost", limit: 1, spent: 1.23 }, { kind: "minutes", limit: 10, spent: 11 }]);159  });160161  it("has no limit unless one is given", () => {162    const guard = new usage.BudgetGuard({ maxCostUsd: null, maxMinutes: undefined }, { startedAt: 0, spentUsd: () => 1e9, now: () => 1e12 });163    expect(guard.check()).toBeNull();164    expect(new usage.BudgetGuard({ maxCostUsd: -3, maxMinutes: Number.NaN }, { startedAt: 0, spentUsd: () => 1e9, now: () => 1e12 }).check()).toBeNull();165  });166});167168describe("budget applied to a generation", () => {169  it("takes the request's budget over the preference, and says where the limits come from", () => {170    expect(usage.resolveBudget({ maxCostUsd: 2 }, { maxCostUsd: 10, maxMinutes: 30 })).toEqual({ maxCostUsd: 2, maxMinutes: null, source: "request" });171    expect(usage.resolveBudget({ maxMinutes: 15 }, { maxCostUsd: 10 })).toEqual({ maxCostUsd: null, maxMinutes: 15, source: "request" });172    expect(usage.resolveBudget(undefined, { maxCostUsd: 10, maxMinutes: 30 })).toEqual({ maxCostUsd: 10, maxMinutes: 30, source: "preference" });173    expect(usage.resolveBudget({}, { maxCostUsd: null, maxMinutes: 45 })).toEqual({ maxCostUsd: null, maxMinutes: 45, source: "preference" });174    expect(usage.resolveBudget(undefined, { maxCostUsd: null, maxMinutes: null })).toEqual({ maxCostUsd: null, maxMinutes: null, source: "default" });175    expect(usage.resolveBudget({ maxCostUsd: -1 }, null)).toEqual({ maxCostUsd: null, maxMinutes: null, source: "default" });176  });177178  it("a budget sent with the request is the one the guard enforces", async () => {179    // The chat body as the route parses it, resolved as the route resolves it, held by the guard the route builds.180    const { chatBodySchema } = await import("../routes/validation");181    const body = chatBodySchema.parse({ query: "Étude", mode: "research", budget: { maxCostUsd: 0.5, maxMinutes: 20 } });182    const applied = usage.resolveBudget(body.budget, { maxCostUsd: 50, maxMinutes: 240 });183    expect(applied).toEqual({ maxCostUsd: 0.5, maxMinutes: 20, source: "request" });184    let spent = 0;185    let clock = 0;186    const hits: any[] = [];187    const guard = new usage.BudgetGuard(applied, { startedAt: 0, spentUsd: () => spent, now: () => clock, onExceeded: (h) => hits.push(h) });188    spent = 0.49;189    expect(guard.check()).toBeNull();190    spent = 0.51;191    expect(guard.check()).toMatch(/limit of \$0\.5/);192    expect(hits).toEqual([{ kind: "cost", limit: 0.5, spent: 0.51 }]); // the request's 0.5, not the preference's 50193    // An approved raise lifts the limit and the guard stops asking the agent to conclude.194    guard.raise({ maxCostUsd: 2 });195    expect(guard.check()).toBeNull();196    clock = 21 * 60_000;197    expect(guard.check()).toMatch(/21 minutes elapsed for a limit of 20/);198  });199200  it("is kept in the trace of the generation", async () => {201    const g = new trace.GenerationTrace({ owner: "erin", sessionId: "s-b", generationId: "g-b" });202    g.observe({ type: "budget_applied", maxCostUsd: 0.5, maxMinutes: 20, source: "request" });203    g.finish("done");204    expect((await t.api("erin", "GET", "/api/v2/generations/g-b/trace")).body.budgetApplied).toEqual({ maxCostUsd: 0.5, maxMinutes: 20, source: "request" });205    const none = new trace.GenerationTrace({ owner: "erin", sessionId: "s-b2", generationId: "g-b2" });206    expect((await t.api("erin", "GET", "/api/v2/generations/g-b2/trace")).body.budgetApplied).toBeNull();207    none.finish("done");208    // A trace left running by a server that stopped is marked interrupted at the next start.209    new trace.GenerationTrace({ owner: "erin", sessionId: "s-b3", generationId: "g-b3" });210    expect(trace.interruptStaleTraces()).toBeGreaterThanOrEqual(1);211    expect((await t.api("erin", "GET", "/api/v2/generations/g-b3/trace")).body.status).toBe("interrupted");212    expect(trace.listTraces("erin", "s-b").map((x) => [x.generationId, x.status])).toEqual([["g-b", "done"]]);213  });214});215216describe("generation stream", () => {217  it("stamps every event with the server time, as its last key, without disturbing what reads the events", async () => {218    const { startGeneration } = await import("../routes/generations");219    const before = Date.now();220    const job = startGeneration({ owner: "frank", sessionId: "s-at", query: "q", mode: "research" });221    job.sink.write(`data: ${JSON.stringify({ type: "status", message: "Analyse en cours…" })}\n\n`);222    job.sink.write(`data: ${JSON.stringify({ type: "text", content: "a } b" })}\n\n`);223    job.sink.write(`data: ${JSON.stringify({ type: "tool_start", tool: "get_stock_quote", toolId: "t1", input: {} })}\n\n`);224    job.sink.write(": comment\n\n");225    job.sink.write(`data: ${JSON.stringify({ type: "done", sessionId: "s-at" })}\n\n`);226    job.close();227    const events = job.events.filter((e) => e.startsWith("data: ")).map((e) => JSON.parse(e.slice(6)));228    expect(events.map((e) => e.type)).toEqual(["status", "text", "tool_start", "done"]);229    for (const e of events) {230      expect(e.at).toBeGreaterThanOrEqual(before);231      expect(Object.keys(e).at(-1)).toBe("at");232    }233    expect(events[1].content).toBe("a } b");234    expect(job.events[3]).toBe(": comment\n\n");235    // The list of generations still reads its step, its tool count and its end from the same events.236    expect(job).toMatchObject({ status: "done", tools: 1, step: "Terminée" });237    expect(job.events.filter((e) => e.startsWith('data: {"type":"done"'))).toHaveLength(1);238  });239});240241describe("usage of the small auxiliary calls", () => {242  it("reports the usage block of a summariser or follow-up call, priced from the table, and never throws", async () => {243    const { reportAuxUsage, knownClaudeSpecs } = await import("../services/claude/tokenManagement");244    const seen: any[] = [];245    reportAuxUsage("claude-haiku-5-5", { input_tokens: 1000, cache_read_input_tokens: 200, output_tokens: 300 }, (u) => seen.push(u));246    const spec = knownClaudeSpecs()["claude-haiku-5-5"];247    expect(seen).toEqual([{ model: "claude-haiku-5-5", inputTokens: 1200, outputTokens: 300, costUsd: ((1000 + 200 * 0.1) * spec.input + 300 * spec.output) / 1e6 }]);248    reportAuxUsage("some-unknown-model", { input_tokens: 10, output_tokens: 5 }, (u) => seen.push(u));249    expect(seen[1]).toEqual({ model: "some-unknown-model", inputTokens: 10, outputTokens: 5, costUsd: null });250    reportAuxUsage("claude-haiku-5-5", undefined, (u) => seen.push(u)); // an API answer without usage records nothing251    reportAuxUsage("claude-haiku-5-5", { input_tokens: 1 }, () => { throw new Error("ledger down"); });252    expect(seen).toHaveLength(2);253    const meter = new usage.UsageMeter({ owner: "frank", sessionId: "s-aux", generationId: "g-aux" });254    meter.add({ ...seen[0], provider: "anthropic", role: "utility" });255    expect(t.db.prepare("SELECT role, model FROM vq_usage WHERE generation_id = 'g-aux'").all()).toEqual([{ role: "utility", model: "claude-haiku-5-5" }]);256  });257});258259describe("provenance", () => {260  it("maps tools to the provider that really serves them", () => {261    const p = trace.toolProvider;262    expect(p("get_stock_quote")).toBe("fmp");263    expect(p("search_companies")).toBe("fmp");264    expect(p("extract_sec_filings")).toBe("fmp");265    expect(p("findata_get_bars")).toBe("findata");266    expect(p("get_eodhd_historical")).toBe("eodhd");267    expect(p("eodhd_treasury_rates")).toBe("eodhd");268    expect(p("search_eodhd")).toBe("eodhd");269    expect(p("get_option_chain")).toBe("eodhd");270    expect(p("firecrawl_scrape")).toBe("web");271    expect(p("tavily_search")).toBe("web");272    expect(p("web_search_exa")).toBe("web");273    expect(p("execute_custom_python_analysis")).toBe("python");274    expect(p("calculate_options_price")).toBe("python");275    expect(p("run_quant_engine")).toBe("quant-engine");276    expect(p("some_future_tool")).toBe("other");277    // A result that names its source wins: the FinData fallback of get_historical_price.278    expect(p("get_historical_price", { source: "FMP" })).toBe("fmp");279    expect(p("get_historical_price", { source: "FinData", note: "FMP unavailable" })).toBe("findata");280  });281282  it("gives every data tool of the app a provider, and none to orchestration tools", () => {283    for (const tool of AVAILABLE_TOOLS) expect(trace.toolProvider(tool.name), tool.name).not.toBe("other");284    for (const tool of AVAILABLE_TOOLS) expect(trace.toolProvider(tool.name), tool.name).not.toBeNull();285    for (const tool of AGENT_TOOLS) expect(trace.toolProvider(tool.name), tool.name).toBeNull();286    expect(trace.toolProvider("create_diagram")).toBeNull();287  });288289  it("extracts only symbols that are named as such in the input", () => {290    expect(trace.extractSymbols({ symbol: "aapl" })).toEqual(["AAPL"]);291    expect(trace.extractSymbols({ symbols: ["msft", "AAPL", "MSFT"], pair: "EURUSD" })).toEqual(["AAPL", "EURUSD", "MSFT"]);292    expect(trace.extractSymbols({ symbols: "NVDA, AMD;TSM" })).toEqual(["AMD", "NVDA", "TSM"]);293    expect(trace.extractSymbols({ engine: "risk_lab", params: { symbols: ["SPY", "TLT"], benchmark: "^GSPC" } })).toEqual(["SPY", "TLT", "^GSPC"]);294    expect(trace.extractSymbols({ query: "Apple AAPL earnings", code: "prices('TSLA')" })).toEqual([]);295    expect(trace.extractSymbols({ symbol: "not a ticker!" })).toEqual([]);296    expect(trace.extractSymbols(null)).toEqual([]);297  });298299  it("is built only from the runs it is given: one line per tool and symbol set", () => {300    const sources = trace.buildProvenance([301      { tool: "get_stock_quote", input: { symbol: "AAPL" }, ok: true, at: 100 },302      { tool: "get_stock_quote", input: { symbol: "AAPL" }, ok: false, at: 200 },303      { tool: "get_stock_quote", input: { symbol: "MSFT" }, ok: false, at: 150 },304      { tool: "get_historical_price", input: { symbol: "AAPL" }, ok: true, at: 300, result: { source: "FinData" } },305      { tool: "execute_custom_python_analysis", input: { code: "print(1)" }, ok: true, at: 400 },306      { tool: "run_quant_engine", input: { engine: "backtest", params: { symbol: "SPY" } }, ok: true, at: 500 },307      { tool: "update_plan", input: { steps: [] }, ok: true, at: 50 },308    ]);309    expect(sources).toEqual([310      { tool: "get_stock_quote", provider: "fmp", symbols: ["MSFT"], retrievedAt: 150, ok: false, calls: 1 },311      { tool: "get_stock_quote", provider: "fmp", symbols: ["AAPL"], retrievedAt: 200, ok: true, calls: 2 },312      { tool: "get_historical_price", provider: "findata", symbols: ["AAPL"], retrievedAt: 300, ok: true, calls: 1 },313      { tool: "execute_custom_python_analysis", provider: "python", symbols: [], retrievedAt: 400, ok: true, calls: 1 },314      { tool: "run_quant_engine", provider: "quant-engine", symbols: ["SPY"], retrievedAt: 500, ok: true, calls: 1 },315    ]);316    expect(trace.buildProvenance([])).toEqual([]);317  });318});319320describe("trace", () => {321  it("follows plan, agents and budget events, records tool calls with their generation, and serves it to its owner only", async () => {322    const g = new trace.GenerationTrace({ owner: "carol", sessionId: "s9", generationId: "g9", mode: "deep", model: "lead-m", requestedModel: "auto" });323    expect((await t.api("carol", "GET", "/api/v2/generations/g9/trace")).body).toMatchObject({ status: "running", plan: [], agents: [], toolCalls: [] });324325    g.observe({ type: "plan", steps: [{ title: "Collect", status: "in_progress" }, { title: "Write", status: "pending" }] });326    g.observe({ type: "agent_start", agentId: "t1-0", name: "Valorisation", kind: "analyst", role: "financial_analyst" });327    g.observe({ type: "agent_start", agentId: "t1-1", name: "Risque", kind: "analyst" });328    g.observe({ type: "text", content: "ignored" });329    g.observe({ type: "agent_done", agentId: "t1-0", ok: true, tools: 4, durationMs: 1234, role: "financial_analyst" });330    g.observe({ type: "budget", kind: "cost", limit: 1, spent: 1.2 });331    g.observe({ type: "plan", steps: [{ title: "Collect", status: "done" }, { title: "Write", status: "in_progress" }] });332333    await runtime.runGuarded("get_stock_quote", async () => ({ price: 1 }), { sessionId: "s9", generationId: "g9", owner: "carol", agent: "lead" });334    await expect(runtime.runGuarded("get_company_profile", async () => { throw new Error("symbol not found"); }, { sessionId: "s9", generationId: "g9", owner: "carol", agent: "analyst:Valorisation" })).rejects.toThrow("symbol not found");335    await runtime.runGuarded("get_stock_quote", async () => ({ price: 2 }), { sessionId: "other", generationId: "g-other", owner: "carol", agent: "lead" });336    new usage.UsageMeter({ owner: "carol", sessionId: "s9", generationId: "g9" }).add({ model: "lead-m", provider: "anthropic", role: "lead", inputTokens: 100, outputTokens: 10, costUsd: 0.01 });337338    g.finish("done");339    g.finish("error"); // a finished trace keeps its first final status340341    const r = await t.api("carol", "GET", "/api/v2/generations/g9/trace");342    expect(r.status).toBe(200);343    expect(r.body).toMatchObject({ generationId: "g9", sessionId: "s9", status: "done", mode: "deep", model: "lead-m", requestedModel: "auto" });344    expect(r.body.finishedAt).toBeGreaterThanOrEqual(r.body.startedAt);345    expect(r.body.plan).toEqual([{ title: "Collect", status: "done" }, { title: "Write", status: "in_progress" }]);346    expect(r.body.agents.map((a: any) => [a.id, a.role, a.status, a.durationMs, a.tools])).toEqual([["t1-0", "financial_analyst", "done", 1234, 4], ["t1-1", null, "failed", null, 0]]);347    expect(r.body.budget).toMatchObject([{ kind: "cost", limit: 1, spent: 1.2 }]);348    expect(r.body.toolCalls.map((c: any) => [c.agent, c.tool, c.ok, c.error])).toEqual([["lead", "get_stock_quote", true, null], ["analyst:Valorisation", "get_company_profile", false, "symbol not found"]]);349    expect(r.body.usage).toMatchObject({ inputTokens: 100, outputTokens: 10, costUsd: 0.01 });350351    expect((await t.api("carol", "GET", "/api/v2/generations/latest/trace?sessionId=s9")).body.generationId).toBe("g9");352    expect((await t.api("dave", "GET", "/api/v2/generations/g9/trace")).status).toBe(404);353    expect((await t.api("dave", "GET", "/api/v2/generations/x/trace?sessionId=s9")).status).toBe(404);354    expect((await t.api("carol", "GET", "/api/v2/generations/unknown/trace")).status).toBe(404);355  });356357  it("collects the provenance of the tool runs it is told about", () => {358    const g = new trace.GenerationTrace({ owner: "carol", sessionId: "s10", generationId: "g10" });359    expect(g.provenance()).toEqual([]);360    g.noteTool({ tool: "findata_get_bars", input: { symbol: "SPY" }, ok: true, at: 5 });361    expect(g.provenance()).toEqual([{ tool: "findata_get_bars", provider: "findata", symbols: ["SPY"], retrievedAt: 5, ok: true, calls: 1 }]);362  });363});364365describe("quant result for the model", () => {366  it("keeps findings, diagnostics and provenance, caps tables, and reduces charts to their shape", () => {367    const lab = {368      schema: "lab/1", engine: "volatility_lab", headline: "h", summary: [{ label: "Persistence", value: 0.97 }], diagnostics: [{ name: "LB", pvalue: 0.4 }], warnings: ["w"],369      tables: [{ id: "t", title: "T", rows: Array.from({ length: 100 }, (_, i) => ({ i })) }],370      charts: [{ id: "c", title: "Vol", type: "line", series: [{ name: "s", kind: "calculated", x: [1, 2, 3], y: [4, 5, 6] }] }],371      provenance: { data: [{ symbol: "SPY", observations: 504 }], spec: { p: 1 }, seed: 1, reproduce: "x".repeat(5000), software: { numpy: "2" } },372    };373    const out: any = runtime.quantResultForModel({ jobId: "j1", engine: "volatility_lab", status: "done", result: lab });374    expect(out.jobId).toBe("j1");375    expect(out.result.headline).toBe("h");376    expect(out.result.diagnostics).toEqual(lab.diagnostics);377    expect(out.result.tables[0].rows).toHaveLength(40);378    expect(out.result.tables[0].note).toMatch(/first 40 of 100 rows/);379    expect(out.result.charts).toEqual([{ id: "c", title: "Vol", type: "line", series: [{ name: "s", kind: "calculated", points: 3 }], note: undefined }]);380    expect(out.result.provenance).toEqual({ data: lab.provenance.data, spec: { p: 1 }, seed: 1, computedAt: undefined, durationMs: undefined });381    expect(runtime.resultForModel("run_quant_engine", { jobId: "j1", result: lab }, 24_000)).not.toContain("xxxxxxxx");382    // A legacy tool result passes through untouched.383    const legacy = { jobId: "j2", result: { success: true, var_95: 1234 } };384    expect(runtime.quantResultForModel(legacy)).toBe(legacy);385  });386});387
Files main
Menu

Theme