stock-bot/test/unit/data-pipeline-rust-evaluation-doc.test.ts
2026-11-29 23:54:53 -05:00

192 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
// Guards the T-124 decision brief (design/data-pipeline/rust-migration-evaluation.md) against
// silent drift: it must stay linked, keep its seven required sections, keep internally consistent
// totals and derived figures, and every quoted benchmark figure must still appear verbatim in the
// README it cites. Live file counts are deliberately not pinned here (they change with every
// data-pipeline task); the document's own reproducible commands cover that at its commit.
const repoRoot = join(import.meta.dir, '..', '..');
const evalRel = 'design/data-pipeline/rust-migration-evaluation.md';
const evalPath = join(repoRoot, evalRel);
const designReadmePath = join(repoRoot, 'design/README.md');
const curateReadme = readFileSync(join(repoRoot, 'tools/curate-etl/README.md'), 'utf8');
const pipelineReadme = readFileSync(join(repoRoot, 'apps/stock/data-pipeline/README.md'), 'utf8');
const doc = readFileSync(evalPath, 'utf8');
function num(text: string): number {
return Number(text.replace(/[`,*]/g, '').trim());
}
function section(title: RegExp): string {
const lines = doc.split('\n');
const start = lines.findIndex(line => /^## /.test(line) && title.test(line));
expect(start).toBeGreaterThan(-1);
const rest = lines.slice(start + 1);
const end = rest.findIndex(line => /^## /.test(line));
return rest.slice(0, end === -1 ? undefined : end).join('\n');
}
function tableRows(body: string, firstCell: RegExp): string[][] {
return body
.split('\n')
.filter(line => line.startsWith('|'))
.map(line => line.split('|').slice(1, -1).map(cell => cell.trim()))
.filter(cells => firstCell.test(cells[0] ?? ''));
}
describe('data-pipeline Rust migration evaluation document', () => {
test('design/README.md links to the evaluation and the link resolves', () => {
const readme = readFileSync(designReadmePath, 'utf8');
expect(readme).toContain('](data-pipeline/rust-migration-evaluation.md)');
expect(existsSync(evalPath)).toBe(true);
});
test('contains all seven required sections in order', () => {
const headings = doc.split('\n').filter(line => /^## \d\./.test(line));
expect(headings.map(h => h.match(/^## (\d)\./)![1])).toEqual(['1', '2', '3', '4', '5', '6', '7']);
expect(headings[0]).toMatch(/Inventory/);
expect(headings[1]).toMatch(/Rust/);
expect(headings[2]).toMatch(/Workload Classification/);
expect(headings[3]).toMatch(/Options Comparison/);
expect(headings[4]).toMatch(/Compliance/);
expect(headings[5]).toMatch(/Recommendation/);
expect(headings[6]).toMatch(/Not Verified/);
});
test('inventory covers the T-89/T-105 CLI, T-116 TSV exporter, T-117 raw-BSON exporter and web-api coupling', () => {
const inventory = section(/^## 1\./);
for (const needle of ['T-89', 'T-105', 'T-116', 'T-117', 'run-security-master.ts', 'export-curate-inputs.ts', 'export-raw-bson.ts', '{data-pipeline_exchanges}', '{data-pipeline_symbols}', 'getFullQueueName', '@stock-bot/types', 'mongoReadOnly: true', 'assertEnvironmentSafety()']) {
expect(inventory).toContain(needle);
}
// The commands that make the counts reproducible are printed verbatim.
expect(inventory).toContain("find \"apps/stock/data-pipeline/src/$area\" -type f -name '*.ts'");
});
test('every path referenced by the inventory commands exists', () => {
const inventory = section(/^## 1\./);
const block = inventory.match(/```bash\n([\s\S]*?)```/)![1]!;
for (const area of ['security-master', 'normalization', 'handlers', 'repositories', 'routes', 'types']) {
expect(existsSync(join(repoRoot, 'apps/stock/data-pipeline/src', area))).toBe(true);
}
const paths = new Set(block.match(/(?:apps|test|tools)\/[\w./-]+/g) ?? []);
expect(paths.size).toBeGreaterThan(0);
for (const path of paths) {
expect({ path, exists: existsSync(join(repoRoot, path)) }).toEqual({ path, exists: true });
}
});
test('per-area inventory rows sum to the stated src/ total', () => {
const rows = tableRows(section(/^## 1\./), /^`(security-master|normalization|handlers|repositories|routes|types)\/`$|^`index\.ts`$|Total/);
const areas = rows.filter(r => !/Total/.test(r[0]!));
const total = rows.find(r => /Total/.test(r[0]!))!;
expect(areas).toHaveLength(7);
const sum = (col: number) => areas.reduce((acc, r) => acc + (Number.isNaN(num(r[col]!)) ? 0 : num(r[col]!)), 0);
expect(sum(1)).toBe(num(total[1]!));
expect(sum(2)).toBe(num(total[2]!));
// pipeline-safety.test.ts is attributed to handlers/ and shared with repositories/ (counted once).
expect(sum(3)).toBe(num(total[3]!));
expect(sum(4)).toBe(num(total[4]!));
});
test('curate-etl module groups sum to the stated Rust total and the non-test/test split', () => {
const rows = tableRows(section(/^## 2\./), /./).filter(r => /^\d/.test(r[1]?.replace(/\*/g, '') ?? ''));
const total = rows.find(r => /Total/.test(r[0]!))!;
const groups = rows.filter(r => r !== total);
const tests = groups.find(r => /test modules/.test(r[0]!))!;
const files = groups.reduce((acc, r) => acc + num(r[1]!), 0);
const loc = groups.reduce((acc, r) => acc + num(r[2]!), 0);
expect(files).toBe(num(total[1]!));
expect(loc).toBe(num(total[2]!));
expect(total[3]).toContain(`${files - num(tests[1]!)} non-test files (${(loc - num(tests[2]!)).toLocaleString('en-US')} LOC)`);
expect(total[3]).toContain(`${num(tests[1]!)} test files (${num(tests[2]!).toLocaleString('en-US')} LOC)`);
});
test('derived figures in the brief are arithmetically consistent', () => {
// 88.1% of src/ LOC is security-master/.
expect(doc).toContain('88.1%');
expect(((17_924 / 20_349) * 100).toFixed(1)).toBe('88.1');
// rayon write speedup from the dated local re-run.
expect(doc).toContain('4.72x');
expect((445.79 / 94.42).toFixed(2)).toBe('4.72');
// Scratch estimates are binary GiB: docs x bytes/doc / 2^30, total I/O = 2x peak.
const gib = (docs: number, bytes: number) => Math.round((docs * bytes) / 2 ** 30);
expect([gib(845.7e6, 161.7), gib(845.7e6, 285.6)]).toEqual([127, 225]);
expect([gib(3.40e9 + 173.3e6, 150), gib(3.40e9 + 173.3e6, 250)]).toEqual([499, 832]);
expect(doc).toContain('~127–225 GiB');
expect(doc).toContain('~255–450 GiB');
expect(doc).toContain('~499–832 GiB');
expect(doc).toContain('~998–1,664 GiB');
expect(doc).not.toMatch(/\d\s?GB peak/);
});
test('every README-sourced benchmark row quotes figures present in the cited README', () => {
const rows = tableRows(section(/^## 2\./), /./).filter(r => /README\.md/.test(r[1] ?? ''));
expect(rows.length).toBeGreaterThanOrEqual(15);
for (const [name, source, command, result] of rows) {
const readme = source!.includes('tools/curate-etl/README.md') ? curateReadme : pipelineReadme;
// Each row states a date or explicitly says the README omits one.
expect({ name, dated: /\d{4}-\d{2}-\d{2}|date omitted/.test(source!) }).toEqual({ name, dated: true });
// The command is copied in full (no ellipsis abbreviations) and appears in the README.
const cmd = command!.replace(/`/g, '');
expect({ name, abbreviated: cmd.includes('...') || cmd.includes('…') }).toEqual({ name, abbreviated: false });
const bin = cmd.match(/-- (\S+)/)?.[1] ?? cmd.match(/(\S+\.(?:test\.)?ts)/)?.[1];
expect({ name, bin, inReadme: readme.includes(bin!) }).toEqual({ name, bin, inReadme: true });
// Every millisecond figure in the bolded result appears verbatim in the README.
const bold = (result!.match(/\*\*([^*]+)\*\*/g) ?? []).join(' ');
for (const ms of bold.match(/[\d,]+\.\d+(?= ms)/g) ?? []) {
expect({ name, ms, inReadme: readme.includes(ms) || readme.includes(ms.replace(/,/g, '')) }).toEqual({ name, ms, inReadme: true });
}
}
});
test('the only non-README benchmark is a labelled local synthetic re-run, never quant or live Mongo', () => {
const rows = tableRows(section(/^## 2\./), /^`/).filter(r => r.length === 4 && !/README\.md/.test(r[1]!));
expect(rows).toHaveLength(1);
const [, source, command] = rows[0]!;
expect(source).toMatch(/Local sandbox re-run/);
expect(source).toMatch(/2026-11-29/);
expect(source).toMatch(/synthetic/);
expect(command).toContain('--offline');
expect(section(/^## 2\./)).toContain('Zero Live QA MongoDB or `quant` Runs');
});
test('options table compares at least three options across the required dimensions', () => {
const body = section(/^## 4\./);
const header = body.split('\n').find(line => line.startsWith('| Dimension'))!;
expect(header.match(/Option [A-Z]/g)!.length).toBeGreaterThanOrEqual(3);
for (const dim of ['Estimated Effort', 'New Rust Crates Required', 'Expected Runtime', 'Key Risks', 'Impact on M2']) {
expect(body).toContain(dim);
}
expect(body).toMatch(/End-to-end wall-time speedup is unmeasured/);
});
test('compliance matrix covers D1–D12 and QA safety rules for every option', () => {
const body = section(/^## 5\./);
for (let d = 1; d <= 12; d++) {
const row = tableRows(body, new RegExp(`^\\*\\*D${d}\\*\\*`));
expect({ d, rows: row.length, cells: row[0]?.length }).toEqual({ d, rows: 1, cells: 4 });
}
expect(body).toMatch(/Reopens §4 layer table/);
for (const needle of ['studio_stock_bot_read', 'trading_admin', 'stock_bot_safety*']) {
expect(body).toContain(needle);
}
});
test('gives exactly one recommendation, director-gated follow-ups and a non-port list', () => {
const body = section(/^## 6\./);
expect(body.match(/\*\*Select Option [A-C]\.\*\*/g)).toEqual(['**Select Option B.**']);
expect(body).toMatch(/Director-Gated — Not Yet Queued or Enacted/);
expect(body.match(/^\d+\. \*\*/gm)!.length).toBeGreaterThanOrEqual(3);
expect(body).toContain('### What Should NOT Be Ported to Rust');
});
test('every relative Markdown link in the brief resolves', () => {
const links = [...doc.matchAll(/\]\(([^)#\s]+)(?:#[^)]*)?\)/g)].map(m => m[1]!).filter(l => !/^[a-z]+:/i.test(l));
for (const link of links) {
const target = resolve(dirname(evalPath), link);
expect({ link, exists: existsSync(target) }).toEqual({ link, exists: true });
}
});
});