Repository Public MIT
1// @vitest-environment node2/**3 * =============================================================================4 * SP BOUCHER | SOFTWARE & RESEARCH5 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project : VQuant9 * File : server/next/quantJobs.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 */4546import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";47import fs from "node:fs";48import os from "node:os";49import path from "node:path";5051// A private SQLite file for this suite, chosen before server/db.ts is loaded.52const tmp = vi.hoisted(() => {53 const dir = `${process.env.TMPDIR ?? "/tmp"}/vq-quant-test-${process.pid}-${Date.now()}`;54 process.env.DATABASE_URL = `sqlite://${dir}.db`;55 return { file: `${dir}.db` };56});5758// The lab runner is replaced: these tests are about validation and job bookkeeping, not about Python.59const lab = vi.hoisted(() => ({60 runs: [] as { engine: string; params: Record<string, unknown>; opts: { signal?: AbortSignal; onProgress?: (f: number) => void }; resolve: (r: unknown) => void }[],61 specs: [] as Record<string, unknown>[],62 errors: {} as Record<string, string>,63}));64vi.mock("../services/python/lab", () => ({65 labCatalogue: async () => ({ engines: lab.specs, errors: lab.errors, loadedAt: 1 }),66 executeLabEngine: (engine: string, params: Record<string, unknown>, opts: { signal?: AbortSignal; onProgress?: (f: number) => void } = {}) =>67 new Promise((resolve) => {68 lab.runs.push({ engine, params, opts, resolve });69 opts.signal?.addEventListener("abort", () => resolve({ success: false, cancelled: true, error: "The computation was cancelled." }));70 }),71 redactSecrets: (s: string) => s,72}));73const legacy = vi.hoisted(() => ({ garch: [] as { input: Record<string, unknown>; resolve: (r: unknown) => void }[] }));74vi.mock("../services/python", () => ({75 executeGarchModel: (input: Record<string, unknown>) => new Promise((resolve) => legacy.garch.push({ input, resolve })),76 executeMonteCarloSimulation: async () => ({ success: true, result: { success: true }, code: "mc" }),77 executeOptionsPricing: async () => ({ success: true, result: { success: true }, code: "opt" }),78 executeVarCalculation: async () => ({ success: true, result: { success: true }, code: "var" }),79}));80vi.mock("../services/python/var", () => ({81 executePortfolioOptimization: async () => ({ success: true, result: { success: true }, code: "po" }),82 executeRiskMetricsAnalysis: async () => ({ success: true, result: { success: true }, code: "rm" }),83}));8485import { ParamError, __test, allTools, buildInput, labTool, legacyNativeClient, normalizeLabParam, runQuantJob, type ParamSpec } from "../routes/quant";8687const SPEC = {88 id: "test_engine",89 title: "Test engine",90 summary: "For tests.",91 category: "econometrics",92 version: "1.2.3",93 params: [94 { name: "symbol", type: "symbol", label: "Symbol", required: true, group: "Data", help: "The asset." },95 { name: "start", type: "date", label: "Start", min: "2000-01-01", max: "2030-12-31" },96 { name: "formula", type: "text", label: "Formula", default: "y ~ x", maxLength: 40 },97 { name: "legs", type: "json", label: "Legs", schemaHint: '[{"strike": 100}]', maxBytes: 300 },98 { name: "weights", type: "numbers", label: "Weights", min: -10, max: 10 },99 { name: "peers", type: "symbols", label: "Peers", min: 0, max: 3 },100 { name: "window", type: "int", label: "Window", default: 60, min: 5, max: 500 },101 { name: "model", type: "choice", label: "Model", default: "garch", choices: ["garch", "egarch"] },102 { name: "robust", type: "bool", label: "Robust", default: true },103 ],104};105106const tick = () => new Promise((r) => setTimeout(r, 5));107const db = () => __test.db();108const jobRow = (id: string) => db().prepare("SELECT * FROM vq_quant_jobs WHERE id = ?").get(id) as Record<string, unknown>;109110beforeEach(() => {111 lab.specs = [SPEC];112 lab.errors = { backtest: "ModuleNotFoundError: No module named 'vqlab.backtest'" };113 lab.runs.length = 0;114 legacy.garch.length = 0;115 db().exec("DELETE FROM vq_quant_jobs");116 __test.running.clear();117});118afterAll(() => {119 for (const f of [tmp.file, `${tmp.file}-wal`, `${tmp.file}-shm`]) fs.rmSync(f, { force: true });120 void os;121 void path;122});123124describe("buildInput — legacy tools are validated exactly as before", () => {125 const tool = (id: string) => __test.LEGACY_TOOLS.find((t) => t.id === id)!;126 it("writes defaults out and drops unknown keys", () => {127 expect(buildInput(tool("garch"), { symbol: " aapl ", extra: 1 })).toEqual({ symbol: "AAPL", p: 1, q: 1, forecast_horizon: 30, data_period: 504 });128 expect(buildInput(tool("var"), { symbol: "SPY", confidence_levels: "0.9, 0.99", data_period: "2520" })).toMatchObject({ confidence_levels: [0.9, 0.99], data_period: 2520, num_simulations: 10000 });129 expect(buildInput(tool("portfolio_optimization"), { symbols: "aapl msft;AAPL" })).toMatchObject({ symbols: ["AAPL", "MSFT"], generate_frontier: true });130 });131 it.each([132 ["garch", {}, /Symbol is required/],133 ["garch", { symbol: "AAPL", p: 6 }, /between 1 and 5/],134 ["garch", { symbol: "AAPL", p: 1.5 }, /an integer is expected/],135 ["garch", { symbol: "AAPL", data_period: 2521 }, /between 30 and 2520/],136 ["garch", { symbol: "AA PL" }, /not a ticker symbol/],137 ["var", { symbol: "AAPL", confidence_levels: Array(11).fill(0.9) }, /1 to 10 values/],138 ["var", { symbol: "AAPL", confidence_levels: [1.2] }, /between 0.5 and 0.9999/],139 ["options", { symbol: "AAPL", strike_price: 100, time_to_maturity: 1, option_type: "straddle" }, /one of call, put/],140 ["portfolio_optimization", { symbols: ["AAPL"] }, /between 2 and 30 distinct symbols/],141 ["portfolio_optimization", { symbols: ["AAPL", "MSFT"], min_weight: 0.8, max_weight: 0.2 }, /Minimum weight is above maximum weight/],142 ])("%s %j is refused", (id, raw, message) => {143 expect(() => buildInput(tool(id), raw as Record<string, unknown>)).toThrow(ParamError);144 expect(() => buildInput(tool(id), raw as Record<string, unknown>)).toThrow(message);145 });146 it("keeps the six legacy tools and their parameter names", () => {147 expect(__test.LEGACY_TOOLS.map((t) => [t.id, t.resultSchema, t.category])).toEqual([148 ["garch", "legacy", "volatility"],149 ["var", "legacy", "risk"],150 ["monte_carlo", "legacy", "simulation"],151 ["options", "legacy", "options"],152 ["portfolio_optimization", "legacy", "portfolio"],153 ["risk_metrics", "legacy", "risk"],154 ]);155 expect(tool("var").params.map((p) => p.name)).toEqual(["symbol", "portfolio_value", "confidence_levels", "time_horizon", "num_simulations", "data_period"]);156 });157});158159describe("lab parameter types", () => {160 const tool = labTool(SPEC);161 it("normalises a Python spec, passing group and help through", () => {162 expect(tool).toMatchObject({ id: "test_engine", category: "econometrics", version: "1.2.3", resultSchema: "lab/1" });163 expect(tool.params[0]).toEqual({ name: "symbol", type: "symbol", label: "Symbol", required: true, group: "Data", help: "The asset." });164 // Bounds of a date are served as minDate/maxDate: min/max stay numeric for the 1.0.x native decoders.165 expect(tool.params[1]).toEqual({ name: "start", type: "date", label: "Start", minDate: "2000-01-01", maxDate: "2030-12-31" });166 for (const p of tool.params) for (const k of ["min", "max"] as const) if (k in p) expect(typeof (p as unknown as Record<string, unknown>)[k]).toBe("number");167 expect(tool.params.find((p) => p.name === "legs")).toMatchObject({ type: "json", schemaHint: '[{"strike": 100}]', maxBytes: 300 });168 });169 it("accepts valid values and writes defaults", () => {170 const input = buildInput(tool, { symbol: "spy", start: "2020-02-29", formula: " ret ~ mkt + smb ", legs: '[{"strike": 100, "type": "call"}]', weights: "0.5, -0.5", peers: [], robust: "true" });171 expect(input).toEqual({ symbol: "SPY", start: "2020-02-29", formula: "ret ~ mkt + smb", legs: [{ strike: 100, type: "call" }], weights: [0.5, -0.5], peers: [], window: 60, model: "garch", robust: true });172 expect(buildInput(tool, { symbol: "SPY", legs: { a: 1 } }).legs).toEqual({ a: 1 });173 expect(buildInput(tool, { symbol: "SPY", formula: " " }).formula).toBe("y ~ x"); // blank text falls back to the default174 });175 it.each([176 [{ start: "2020-02-30" }, /a date YYYY-MM-DD is expected/],177 [{ start: "02/03/2020" }, /a date YYYY-MM-DD is expected/],178 [{ start: 20200101 }, /a date YYYY-MM-DD is expected/],179 [{ start: "1999-12-31" }, /not before 2000-01-01/],180 [{ start: "2031-01-01" }, /not after 2030-12-31/],181 [{ formula: "x".repeat(41) }, /at most 40 characters/],182 [{ formula: { a: 1 } }, /text is expected/],183 [{ legs: "{not json" }, /not valid JSON/],184 [{ legs: "42" }, /a JSON object or array is expected/],185 [{ legs: Array(100).fill({ strike: 100 }) }, /too large/],186 [{ legs: "[" + "1,".repeat(400) + "1]" }, /too large/],187 [{ legs: JSON.parse("[".repeat(14) + "]".repeat(14)) }, /nested too deeply/],188 [{ weights: Array(101).fill(1) }, /1 to 100 values/],189 [{ weights: [11] }, /between -10 and 10/],190 [{ peers: ["A", "B", "C", "D"] }, /between 0 and 3 distinct symbols/],191 [{ model: "tgarch" }, /one of garch, egarch/],192 [{ window: 4 }, /between 5 and 500/],193 ])("refuses %j", (raw, message) => {194 expect(() => buildInput(tool, { symbol: "SPY", ...(raw as Record<string, unknown>) })).toThrow(ParamError);195 expect(() => buildInput(tool, { symbol: "SPY", ...(raw as Record<string, unknown>) })).toThrow(message);196 });197 it("strips control characters from text", () => {198 expect(buildInput(tool, { symbol: "SPY", formula: "a\u0000b\u0007c" }).formula).toBe("abc");199 });200 it("passes requiredWhen / visibleWhen through and enforces requiredWhen on the validated input", () => {201 const t = labTool({ id: "cond_engine", title: "T", summary: "S", category: "options", version: "1.0.0", params: [202 { name: "mode", type: "choice", label: "Analysis", choices: ["price", "implied", "strategy"], default: "price" },203 { name: "template", type: "choice", label: "Template", choices: ["straddle", "custom"], default: "straddle", visibleWhen: { mode: "strategy" } },204 { name: "market_price", type: "number", label: "Market price", min: 0, requiredWhen: { mode: "implied" }, visibleWhen: { mode: ["implied"] } },205 { name: "legs", type: "json", label: "Legs", requiredWhen: { mode: "strategy", template: "custom" } },206 { name: "deep", type: "bool", label: "Deep", default: false },207 { name: "depth", type: "int", label: "Depth", min: 1, max: 9, requiredWhen: { deep: true } },208 ] } as never);209 const byName = Object.fromEntries(t.params.map((p) => [p.name, p]));210 expect(byName.market_price).toMatchObject({ requiredWhen: { mode: "implied" }, visibleWhen: { mode: ["implied"] } });211 expect(byName.template.visibleWhen).toEqual({ mode: "strategy" });212 expect(byName.mode).not.toHaveProperty("requiredWhen");213 expect(buildInput(t, {})).toEqual({ mode: "price", template: "straddle", deep: false }); // the default mode asks for nothing more214 expect(() => buildInput(t, { mode: "implied" })).toThrow("Market price is required when Analysis is implied.");215 expect(buildInput(t, { mode: "implied", market_price: 0 }).market_price).toBe(0); // zero is a value, not a missing one216 expect(buildInput(t, { mode: "strategy" }).template).toBe("straddle"); // both conditions must hold217 expect(() => buildInput(t, { mode: "strategy", template: "custom" })).toThrow("Legs is required when Analysis is strategy and Template is custom.");218 expect(buildInput(t, { mode: "strategy", template: "custom", legs: [{ type: "call" }] }).legs).toEqual([{ type: "call" }]);219 expect(() => buildInput(t, { deep: "true" })).toThrow("Depth is required when Deep is true.");220 expect(() => normalizeLabParam({ name: "x", type: "int", requiredWhen: "mode" })).toThrow(/requiredWhen must be an object/);221 expect(() => normalizeLabParam({ name: "x", type: "int", visibleWhen: { mode: { a: 1 } } })).toThrow(/must be a value or a list of values/);222 expect(() => normalizeLabParam({ name: "x", type: "int", requiredWhen: { "bad name": 1 } })).toThrow(/invalid parameter/);223 });224 it("refuses a spec it could not validate inputs for", () => {225 expect(() => normalizeLabParam({ name: "x", type: "matrix", label: "X" })).toThrow(/unknown parameter type/);226 expect(() => normalizeLabParam({ name: "bad name", type: "int" })).toThrow(/invalid parameter name/);227 expect(() => normalizeLabParam({ name: "c", type: "choice", choices: [] })).toThrow(/needs choices/);228 expect(() => normalizeLabParam({ name: "n", type: "int", min: 5, max: 1 })).toThrow(/min is above max/);229 const p = normalizeLabParam({ name: "n", type: "number" }) as Extract<ParamSpec, { type: "number" }>;230 expect([p.min, p.max, p.label]).toEqual([-1e15, 1e15, "n"]);231 });232});233234describe("catalogue merge", () => {235 it("offers the legacy tools then the lab engines, and says which engines are unavailable", async () => {236 lab.specs = [SPEC, { ...SPEC, id: "garch", title: "Impostor" }, { ...SPEC, id: "broken", params: [{ name: "x", type: "matrix" }] }];237 const { tools, unavailable } = await allTools();238 expect(tools.map((t) => t.id)).toEqual(["garch", "var", "monte_carlo", "options", "portfolio_optimization", "risk_metrics", "test_engine"]);239 expect(tools[0].title).toBe("GARCH volatility"); // a lab engine never shadows a legacy id240 expect(unavailable.backtest).toMatch(/ModuleNotFoundError/);241 expect(unavailable.broken).toMatch(/Invalid engine spec/);242 });243 it("recognises the 1.0.x native apps", () => {244 const h = (v?: string) => ({ headers: v ? { "x-vq-client": v } : {} });245 expect(legacyNativeClient(h("vquant-macos/1.0.1"))).toBe(true);246 expect(legacyNativeClient(h("vquant-ios/1.0.0 (iPhone)"))).toBe(true);247 expect(legacyNativeClient(h("vquant-macos/2.0.0"))).toBe(false);248 expect(legacyNativeClient(h())).toBe(false); // the web app249 });250});251252describe("jobs", () => {253 it("records a lab job with progress, engine version, project and session, then its result", async () => {254 const pending = runQuantJob("simon", "test_engine", { symbol: "spy" }, { projectId: "proj_1", sessionId: "sess-9" });255 await tick();256 expect(lab.runs).toHaveLength(1);257 expect(lab.runs[0].params).toMatchObject({ symbol: "SPY", window: 60 });258 const id = String((db().prepare("SELECT id FROM vq_quant_jobs").get() as { id: string }).id);259 expect(jobRow(id)).toMatchObject({ owner: "simon", tool: "test_engine", status: "running", progress: 0, engine_version: "1.2.3", project_id: "proj_1", session_id: "sess-9" });260 expect(__test.summary(jobRow(id) as never)).toMatchObject({ status: "running", cancellable: true, durationMs: null, progress: 0, engineVersion: "1.2.3", projectId: "proj_1", sessionId: "sess-9" });261262 lab.runs[0].opts.onProgress!(0.4);263 expect(jobRow(id).progress).toBe(0.4);264 lab.runs[0].opts.onProgress!(0.2); // never backwards265 expect(jobRow(id).progress).toBe(0.4);266267 const result = { success: true, schema: "lab/1", engine: "test_engine", engineVersion: "1.2.4", headline: "ok" };268 lab.runs[0].resolve({ success: true, result, code: "print('reproduce')" });269 const out = await pending;270 expect(out).toEqual({ jobId: id, status: "done", result });271 const row = jobRow(id);272 expect(row).toMatchObject({ status: "done", progress: 1, engine_version: "1.2.4", code: "print('reproduce')", error: null });273 expect(JSON.parse(String(row.result))).toEqual(result);274 const s = __test.summary(row as never);275 expect(s.durationMs).toBe(Number(row.finished_at) - Number(row.started_at));276 expect(s.cancellable).toBe(false);277 });278279 it("records an engine failure as an error with its message", async () => {280 const pending = runQuantJob("simon", "test_engine", { symbol: "SPY" });281 await tick();282 lab.runs[0].resolve({ success: false, result: { success: false, error: "Not enough observations." }, error: "Not enough observations." });283 const out = await pending;284 expect(out).toMatchObject({ status: "error", error: "Not enough observations." });285 expect(jobRow(out.jobId)).toMatchObject({ status: "error", result: null });286 });287288 it("rejects invalid requests without recording anything", async () => {289 expect(await runQuantJob("simon", "nope", {})).toEqual({ jobId: "", status: "rejected", error: "Unknown tool." });290 expect(await runQuantJob("simon", "test_engine", {})).toMatchObject({ status: "rejected", error: "Symbol is required." });291 expect(await runQuantJob("simon", "test_engine", { symbol: "SPY" }, { projectId: "../x" })).toMatchObject({ status: "rejected", error: expect.stringMatching(/projectId/) });292 expect((db().prepare("SELECT count(*) AS n FROM vq_quant_jobs").get() as { n: number }).n).toBe(0);293 });294295 it("applies the per-person limit of running computations", async () => {296 const started = [runQuantJob("simon", "test_engine", { symbol: "A" }), runQuantJob("simon", "test_engine", { symbol: "B" }), runQuantJob("simon", "test_engine", { symbol: "C" })];297 await tick();298 expect(await runQuantJob("simon", "test_engine", { symbol: "D" })).toMatchObject({ status: "rejected", error: expect.stringMatching(/3 computations are already running/) });299 const other = runQuantJob("richard", "test_engine", { symbol: "D" }); // another person is not affected300 await tick();301 for (const r of lab.runs) r.resolve({ success: true, result: { success: true } });302 expect((await Promise.all([...started, other])).every((o) => o.status === "done")).toBe(true);303 });304305 it("cancels a running lab job; a late result does not resurrect it", async () => {306 const pending = runQuantJob("simon", "test_engine", { symbol: "SPY" });307 await tick();308 const id = String((db().prepare("SELECT id FROM vq_quant_jobs").get() as { id: string }).id);309 expect(__test.cancelJob("richard", id).http).toBe(404); // someone else's job310 const r = __test.cancelJob("simon", id);311 expect(r.http).toBe(200);312 expect(r.body.job).toMatchObject({ id, status: "cancelled", cancellable: false });313 expect(lab.runs[0].opts.signal!.aborted).toBe(true);314 expect(await pending).toMatchObject({ jobId: id, status: "cancelled" });315 expect(jobRow(id)).toMatchObject({ status: "cancelled", result: null, error: "Cancelled." });316 expect(__test.cancelJob("simon", id)).toMatchObject({ http: 409, body: { error: "not_running", status: "cancelled" } });317 // 1.0.x native apps know four statuses: they are shown "interrupted".318 expect(__test.summary(jobRow(id) as never, true).status).toBe("interrupted");319 expect(__test.summary(jobRow(id) as never, false).status).toBe("cancelled");320 });321322 it("keeps a cancellation even when the engine answers at the same moment", async () => {323 const pending = runQuantJob("simon", "test_engine", { symbol: "SPY" });324 await tick();325 const id = String((db().prepare("SELECT id FROM vq_quant_jobs").get() as { id: string }).id);326 db().prepare("UPDATE vq_quant_jobs SET status = 'cancelled', finished_at = 1, error = 'Cancelled.' WHERE id = ?").run(id);327 lab.runs[0].resolve({ success: true, result: { success: true, headline: "too late" } });328 expect(await pending).toMatchObject({ jobId: id, status: "cancelled" });329 expect(jobRow(id)).toMatchObject({ status: "cancelled", result: null });330 });331332 it("runs a legacy tool untouched and refuses to cancel it", async () => {333 const pending = runQuantJob("simon", "garch", { symbol: "aapl", data_period: 2520 });334 await tick();335 expect(legacy.garch[0].input).toEqual({ symbol: "AAPL", p: 1, q: 1, forecast_horizon: 30, data_period: 2520 });336 const id = String((db().prepare("SELECT id FROM vq_quant_jobs").get() as { id: string }).id);337 expect(jobRow(id)).toMatchObject({ status: "running", progress: null, engine_version: "1.0.0" });338 expect(__test.summary(jobRow(id) as never).cancellable).toBe(false);339 expect(__test.cancelJob("simon", id)).toEqual({ http: 409, body: { error: "not_cancellable" } });340 const result = { success: true, symbol: "AAPL", parameters: { persistence: 0.97 } };341 legacy.garch[0].resolve({ success: true, result, code: "import arch" });342 expect(await pending).toEqual({ jobId: id, status: "done", result });343 expect(JSON.parse(String(jobRow(id).result))).toEqual(result); // the legacy result shape is stored as produced344 });345});346