Repository Public MIT
1// @vitest-environment node2/**3 * =============================================================================4 * SP BOUCHER | SOFTWARE & RESEARCH5 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project : VQuant9 * File : server/next/labRunner.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, beforeAll, describe, expect, it } from "vitest";47import fs from "node:fs";48import os from "node:os";49import path from "node:path";50import { executeLabEngine, labCatalogue, redactSecrets, resetLabCatalogue, runPython } from "../services/python/lab";5152// These tests start real Python processes (tiny scripts written to a temporary directory).53let dir: string;54const script = (name: string, body: string): string => {55 const file = path.join(dir, name);56 fs.writeFileSync(file, body);57 return file;58};5960beforeAll(() => {61 dir = fs.mkdtempSync(path.join(os.tmpdir(), "vq-lab-test-"));62});63afterAll(() => {64 fs.rmSync(dir, { recursive: true, force: true });65});6667describe("redactSecrets", () => {68 it("masks credential values of the environment and key-like query parameters", () => {69 process.env.VQ_TEST_API_KEY = "s3cr3t-value-123456";70 const out = redactSecrets("GET https://x.example/a?apikey=abcdef123456&symbol=AAPL failed with s3cr3t-value-123456 (Bearer abcdefghijklmnop)");71 expect(out).not.toContain("s3cr3t-value-123456");72 expect(out).not.toContain("abcdef123456");73 expect(out).not.toContain("abcdefghijklmnop");74 expect(out).toContain("symbol=AAPL");75 delete process.env.VQ_TEST_API_KEY;76 });77});7879describe("runPython", () => {80 it("passes stdin, captures stdout and parses progress lines, even split across chunks", async () => {81 const file = script(82 "progress.py",83 [84 "import sys, json, time",85 "req = json.loads(sys.stdin.read())",86 "sys.stderr.write('@@progress 0.25\\n'); sys.stderr.flush()",87 "sys.stderr.write('a log line\\n@@prog'); sys.stderr.flush(); time.sleep(0.05)",88 "sys.stderr.write('ress 0.5\\n'); sys.stderr.flush()",89 "sys.stderr.write('@@progress 7\\n@@progress nan\\n@@progress 1.000\\n'); sys.stderr.flush()",90 "sys.stdout.write(json.dumps({'echo': req['x']}))",91 ].join("\n"),92 );93 const seen: number[] = [];94 const r = await runPython(file, [], { stdin: JSON.stringify({ x: 42 }), onProgress: (f) => seen.push(f) });95 expect(r.outcome).toBe("ok");96 expect(r.exitCode).toBe(0);97 expect(JSON.parse(r.stdout)).toEqual({ echo: 42 });98 expect(seen).toEqual([0.25, 0.5, 1, 1]); // 7 is clamped to 1, "nan" is not a progress value99 expect(r.stderr).toContain("a log line");100 expect(r.stderr).not.toContain("@@progress 0.25");101 });102103 it("enforces the wall-clock timeout, escalating to SIGKILL for a process that ignores SIGTERM", async () => {104 const file = script("stubborn.py", ["import signal, time, sys", "signal.signal(signal.SIGTERM, signal.SIG_IGN)", "sys.stderr.write('started\\n'); sys.stderr.flush()", "time.sleep(60)"].join("\n"));105 const t = Date.now();106 const r = await runPython(file, [], { timeoutMs: 400, killGraceMs: 300 });107 expect(r.outcome).toBe("timeout");108 expect(r.signal).toBe("SIGKILL");109 expect(Date.now() - t).toBeLessThan(5_000);110 });111112 it("stops on abort with SIGTERM", async () => {113 const file = script("sleeper.py", "import time\ntime.sleep(60)\n");114 const controller = new AbortController();115 setTimeout(() => controller.abort(), 200);116 const r = await runPython(file, [], { signal: controller.signal });117 expect(r.outcome).toBe("aborted");118 expect(r.signal).toBe("SIGTERM");119 const already = new AbortController();120 already.abort();121 expect((await runPython(file, [], { signal: already.signal })).outcome).toBe("aborted");122 });123124 it("caps captured output", async () => {125 const file = script("flood.py", "import sys\nwhile True:\n sys.stdout.write('x' * 65536)\n");126 const r = await runPython(file, [], { maxStdoutBytes: 200_000, timeoutMs: 10_000 });127 expect(r.outcome).toBe("output_too_large");128 expect(r.stdout).toBe("");129 const noisy = script("noisy.py", "import sys\nfor i in range(4000):\n sys.stderr.write('line %d ' % i + 'y' * 100 + '\\n')\nsys.stdout.write('{}')\n");130 const n = await runPython(noisy, []);131 expect(n.outcome).toBe("ok");132 expect(n.stderr.length).toBeLessThanOrEqual(64 * 1024);133 expect(n.stderr).toContain("line 3999"); // the tail is what is kept134 });135136 it("reports a script that crashes", async () => {137 const r = await runPython(script("crash.py", "raise SystemExit(3)\n"), []);138 expect(r).toMatchObject({ outcome: "ok", exitCode: 3, stdout: "" });139 });140});141142describe("executeLabEngine / labCatalogue (real dispatcher)", () => {143 it("lists engines without throwing, whatever is installed", async () => {144 resetLabCatalogue();145 const [a, b] = await Promise.all([labCatalogue(), labCatalogue()]);146 expect(a).toBe(b); // one Python start for concurrent callers147 expect(Array.isArray(a.engines)).toBe(true);148 for (const e of a.engines) {149 expect(e.id).toMatch(/^[a-z][a-z0-9_]+$/);150 expect(Array.isArray(e.params)).toBe(true);151 }152 expect(await labCatalogue()).toBe(a); // cached153 }, 120_000);154155 it("returns the dispatcher's failure document for an unknown engine, and refuses a malformed id", async () => {156 const r = await executeLabEngine("no_such_engine", {});157 expect(r.success).toBe(false);158 expect(r.error).toMatch(/Unknown engine/);159 expect(r.result).toMatchObject({ success: false, schema: "lab/1" });160 expect(await executeLabEngine("../etc/passwd", {})).toEqual({ success: false, error: "Unknown engine." });161 }, 120_000);162163 it("reports a cancellation", async () => {164 const controller = new AbortController();165 controller.abort();166 expect(await executeLabEngine("volatility_lab", { symbol: "SPY" }, { signal: controller.signal })).toMatchObject({ success: false, cancelled: true });167 });168});169