Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : client/src/lib/research/lib.test.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445import { describe, expect, it } from "vitest";46import fs from "node:fs";47import path from "node:path";48import { replay } from "./reducer";49import { stateFromSnapshot } from "./snapshot";50import { DEFAULT_LEDGER_FILTER, filterLedger, formatMetric, ledgerCounts, ledgerRows, outcomeOf, shapeMetrics } from "./ledger";51import { APPROVAL_TTL_MS, approvalDetails, countdown, isAnswerable } from "./approval";52import { extensionOf, formatBytes, uploadErrorMessage, validateDataset } from "./upload";53import { buildTree, fileKind, isTextual, parseDelimited } from "./files";54import { tokenizePython } from "./highlight";55import { setNumberLocale } from "@/lib/format";56import type { SessionDetail, StoredMessage, StreamEvent } from "./types";5758const fixture = <T,>(name: string): T => JSON.parse(fs.readFileSync(path.join(__dirname, "__fixtures__", name), "utf8")) as T;59const stream = fixture<StreamEvent[]>("stream-study.json");60const detail = fixture<SessionDetail>("workspace-detail.json");61const conversation = fixture<{ messages: StoredMessage[] }>("conversation.json");62setNumberLocale("fr-CA", false);6364describe("experiment ledger", () => {65 const rows = ledgerRows(stateFromSnapshot(detail, conversation.messages));6667 it("shapes declared experiments, cells and runs into one table", () => {68 const c = ledgerCounts(rows);69 expect(c.experiment).toBe(10);70 expect(c.execution).toBe(detail.executions.length);71 expect(c.all).toBe(10 + detail.executions.length);72 expect(rows.filter((r) => r.kind === "run")).toHaveLength(11);73 });7475 it("gives failed and abandoned entries their reason", () => {76 const failed = rows.find((r) => r.kind === "experiment" && r.status === "failed")!;77 expect(failed.outcome).toBe("problem");78 expect(failed.reason).toContain("SSL certificate");79 const abandoned = rows.find((r) => r.status === "abandoned")!;80 expect(abandoned.outcome).toBe("open");81 expect(abandoned.reason).toContain("BIC decreased monotonically");82 const cell = rows.find((r) => r.kind === "cell" && r.status === "failed")!;83 // the exception, not the output that preceded it84 expect(cell.reason).toMatch(/Error/);85 expect(cell.codePath).toMatch(/^logs\/cells\/[0-9a-f]{16}\.py$/);86 expect(rows.filter((r) => r.outcome === "ok").every((r) => r.reason === null)).toBe(true);87 });8889 it("keeps the key metrics, the environment hash and the links", () => {90 const first = rows.find((r) => r.kind === "experiment")!;91 expect(first.metrics).toHaveLength(4);92 expect(first.metricCount).toBe(6);93 expect(first.metrics[0]).toEqual({ name: "infl ADF p full", value: "0,0270", numeric: true });94 expect(first.envHash).toBe("af5ef3d79d245a52");95 expect(first.artifacts).toEqual(["artifacts/stationarity.csv"]);96 const run = rows.find((r) => r.kind === "run")!;97 expect(run.codePath).toMatch(/^code\/.+\.py$/);98 expect(run.durationMs).toBeGreaterThan(0);99 });100101 it("filters by kind, outcome and text", () => {102 expect(filterLedger(rows, DEFAULT_LEDGER_FILTER)).toHaveLength(10);103 expect(filterLedger(rows, { kind: "experiment", outcome: "problem", query: "" })).toHaveLength(1);104 expect(filterLedger(rows, { kind: "experiment", outcome: "open", query: "" })).toHaveLength(1);105 expect(filterLedger(rows, { kind: "execution", outcome: "problem", query: "" })).toHaveLength(5);106 expect(filterLedger(rows, { kind: "all", outcome: "all", query: "giacomini" }).length).toBeGreaterThan(0);107 expect(filterLedger(rows, { kind: "all", outcome: "all", query: "zzz-rien" })).toHaveLength(0);108 });109110 it("builds the same rows from the live stream", () => {111 const live = ledgerRows(replay(stream));112 expect(ledgerCounts(live)).toMatchObject({ experiment: 9, execution: 56, problem: 5, open: 1 });113 });114115 it("formats metric values without inventing precision", () => {116 expect(formatMetric(0.027).value).toBe("0,0270");117 expect(formatMetric(44.4).value).toBe("44,400");118 expect(formatMetric(116)).toEqual({ value: "116", numeric: true });119 expect(formatMetric("1973Q1, 1981Q4")).toEqual({ value: "1973Q1, 1981Q4", numeric: false });120 expect(formatMetric(null).value).toBe("—");121 expect(formatMetric(true).value).toBe("oui");122 expect(shapeMetrics(null)).toEqual({ shown: [], total: 0 });123 expect(outcomeOf("timeout")).toBe("problem");124 expect(outcomeOf("inconclusive")).toBe("open");125 expect(outcomeOf("running")).toBe("running");126 });127});128129describe("approval countdown", () => {130 const a = { createdAt: 1_000_000, status: "pending" as const };131132 it("counts down fifteen minutes from the request", () => {133 expect(countdown(a, 1_000_000)).toMatchObject({ remainingMs: APPROVAL_TTL_MS, label: "15:00", expired: false, urgent: false, elapsedShare: 0 });134 expect(countdown(a, 1_000_000 + 61_500).label).toBe("13:59");135 const late = countdown(a, 1_000_000 + 13.5 * 60_000);136 expect(late).toMatchObject({ label: "01:30", urgent: true, expired: false });137 expect(late.elapsedShare).toBeCloseTo(0.9, 5);138 });139140 it("treats silence after fifteen minutes as a refusal", () => {141 expect(countdown(a, 1_000_000 + APPROVAL_TTL_MS)).toMatchObject({ remainingMs: 0, label: "00:00", expired: true, urgent: false });142 expect(isAnswerable(a, 1_000_000 + APPROVAL_TTL_MS - 1)).toBe(true);143 expect(isAnswerable(a, 1_000_000 + APPROVAL_TTL_MS)).toBe(false);144 expect(isAnswerable({ createdAt: 1_000_000, status: "approved" }, 1_000_001)).toBe(false);145 expect(countdown({ createdAt: 1_000_000, status: "expired" }, 1_000_001).expired).toBe(true);146 });147148 it("never invents a deadline for a request without a time, nor goes negative on a skewed clock", () => {149 expect(countdown({ createdAt: null, status: "pending" }, 5)).toMatchObject({ remainingMs: null, label: "—", expired: false });150 expect(isAnswerable({ createdAt: null, status: "pending" }, 5)).toBe(true);151 expect(countdown(a, 999_000).elapsedShare).toBe(0);152 });153154 it("spells out what is asked", () => {155 expect(approvalDetails({ action: "raise_budget", detail: { maxCostUsd: 8, maxMinutes: 60 } })).toEqual([{ label: "Nouveau plafond de coût", value: expect.stringContaining("8") }, { label: "Nouvelle durée maximale", value: "60 min" }]);156 expect(approvalDetails({ action: "open_network", detail: { host: "fred.stlouisfed.org", empty: "" } })).toEqual([{ label: "Destination", value: "fred.stlouisfed.org" }]);157 expect(approvalDetails({ action: "other", detail: null })).toEqual([]);158 });159});160161describe("dataset upload checks", () => {162 it("accepts the formats of the contract, whatever the case", () => {163 for (const name of ["a.csv", "b.TSV", "c.parquet", "d.xlsx", "e.xls", "f.feather", "g.json", "h.jsonl", "i.txt"]) expect(validateDataset({ name, size: 10 }).ok).toBe(true);164 expect(extensionOf("Rendements.Mensuels.CSV")).toBe(".csv");165 });166167 it("refuses other types, empty files and files above the limit, and says why", () => {168 const zip = validateDataset({ name: "data.zip", size: 10 });169 expect(zip.ok).toBe(false);170 expect(!zip.ok && zip.error).toContain(".zip");171 expect(validateDataset({ name: "sans-extension", size: 10 }).ok).toBe(false);172 expect(validateDataset({ name: ".csv", size: 10 }).ok).toBe(false);173 expect(validateDataset({ name: "vide.csv", size: 0 })).toEqual({ ok: false, error: "Ce fichier est vide." });174 const big = validateDataset({ name: "gros.parquet", size: 300 * 1024 * 1024 });175 expect(!big.ok && big.error).toContain("200,0 Mo");176 expect(validateDataset({ name: "ok.csv", size: 2048 }, 1024).ok).toBe(false);177 expect(validateDataset({ name: "ok.csv", size: 1024 }, 1024).ok).toBe(true);178 });179180 it("formats sizes and server refusals", () => {181 expect(formatBytes(17424)).toBe("17 ko");182 expect(formatBytes(900)).toBe("900 o");183 expect(formatBytes(5 * 1024 * 1024)).toBe("5,0 Mo");184 expect(formatBytes(null)).toBe("—");185 expect(uploadErrorMessage(415)).toContain("extension");186 expect(uploadErrorMessage(413)).toContain("taille");187 expect(uploadErrorMessage(500, "disk full")).toContain("disk full");188 });189});190191describe("workspace files", () => {192 it("builds the tree with sizes and counts", () => {193 const tree = buildTree(detail.files);194 expect(tree.map((n) => n.name)).toEqual(["artifacts", "code", "data", "logs", "runs", "environment.lock.txt"]);195 const code = tree.find((n) => n.name === "code")!;196 expect(code.fileCount).toBe(9);197 expect(code.bytes).toBe(code.children.reduce((s, c) => s + c.bytes, 0));198 const total = tree.reduce((s, n) => s + n.fileCount, 0);199 expect(total).toBe(detail.files.filter((f) => f.type === "file").length);200 });201202 it("knows how each file is previewed", () => {203 expect(fileKind("code/common.py")).toBe("code");204 expect(fileKind("artifacts/stationarity.csv")).toBe("table");205 expect(fileKind("artifacts/figures/a.PNG")).toBe("image");206 expect(fileKind("artifacts/figures/a.pdf")).toBe("pdf");207 expect(fileKind("data/x.parquet")).toBe("data");208 expect(isTextual("environment.lock.txt")).toBe(true);209 expect(isTextual("runs/x/stdout.log")).toBe(true);210 expect(isTextual("data/x.parquet")).toBe(false);211 });212213 it("reads delimited text with quotes, semicolons and tabs", () => {214 expect(parseDelimited('a,b\n1,"x, y"\n2,"he said ""hi"""\n')).toMatchObject({ header: ["a", "b"], rows: [["1", "x, y"], ["2", 'he said "hi"']], delimiter: ",", truncated: false });215 expect(parseDelimited("a;b\r\n1,5;2\r\n").rows).toEqual([["1,5", "2"]]);216 expect(parseDelimited("a\tb\n1\t2").rows).toEqual([["1", "2"]]);217 const many = parseDelimited(`h\n${Array.from({ length: 500 }, (_, i) => i).join("\n")}`, 50);218 expect(many.rows).toHaveLength(50);219 expect(many.truncated).toBe(true);220 });221});222223describe("python tokenizer", () => {224 const kinds = (code: string) => tokenizePython(code).filter((t) => t.kind !== "plain").map((t) => `${t.kind}:${t.text}`);225226 it("marks keywords, definitions, strings, numbers and comments", () => {227 expect(kinds("def load(path): # read\n return pd.read_csv(path, sep=';')")).toEqual(["keyword:def", "def:load", "comment:# read", "keyword:return", "string:';'"]);228 expect(kinds("x = 1_000 + 2.5e-3")).toEqual(["number:1_000", "number:2.5e-3"]);229 expect(kinds("print(len(a))")).toEqual(["builtin:print", "builtin:len"]);230 });231232 it("keeps a triple-quoted block and a raw string whole and never loses a character", () => {233 const code = 's = r\'\'\'\nimport sys # not a comment\n\'\'\'\nf"{a}" # c\n@decorator\nclass A: pass';234 const tokens = tokenizePython(code);235 expect(tokens.map((t) => t.text).join("")).toBe(code);236 expect(tokens.find((t) => t.kind === "string")!.text).toContain("# not a comment");237 expect(kinds(code)).toEqual(expect.arrayContaining(["comment:# c", "decorator:@decorator", "keyword:class", "def:A", "keyword:pass"]));238 });239240 it("survives an unterminated string", () => {241 const code = "x = 'abc\ny = 2";242 expect(tokenizePython(code).map((t) => t.text).join("")).toBe(code);243 });244});245