SPB Git

Repository Public

runner.test.ts 16.6 KB 253 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SP Wallet8 * File             : services/research-runner/test/runner.test.ts9 * Module           : services10 * Repository       : https://git.spboucher.ai/sp-wallet11 * Project Website  : https://wallet.spboucher.ai12 * Created          : 2026-11-1113 * Last Modified    : 2026-11-1714 *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: support@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 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// The runner's state machine with the deterministic fake agent (no model, no network): success, crash, timeout, cancel, every44// budget, malformed submissions, ledger tampering, the cross-process seal of the inner test split. On macOS every job below45// runs under the real sandbox-exec profile.46import { existsSync, readFileSync, readdirSync } from 'node:fs';47import path from 'node:path';48import { describe, expect, it } from 'vitest';49import { RunnerResult, decodeSubmission, parseClaims } from '@spw/core/research-job';50import { configFromEnv } from '../src/config.ts';51import { agentArgv, collectSubmission, describeStreamEvent, jobPaths, runJob, sandboxAvailable } from '../src/job.ts';52import { LedgerTail } from '../src/ledger.ts';53import { processJob } from '../src/runner.ts';54import { hooks, labReady, makeJob, testConfig } from './helpers.ts';55import { appendFileSync, mkdtempSync, writeFileSync } from 'node:fs';56import { tmpdir } from 'node:os';5758const T = 180_000;59const run = async (mode: string, extra: unknown = {}, o: { job?: Parameters<typeof makeJob>[0]; cfg?: Parameters<typeof testConfig>[2] } = {}) => {60  const job = makeJob(o.job), cfg = testConfig(mode, extra, o.cfg), h = hooks();61  const result = RunnerResult.parse(await runJob(job, cfg, h.hooks));   // what the runner returns is exactly what the API accepts62  return { job, cfg, result, log: h.captured.lines.map((l) => `${l.s}: ${l.t}`).join('\n'), captured: h.captured };63};6465describe.skipIf(!labReady())('runner state machine (fake agent)', () => {66  it('success: two trials, one sealed look at the inner test split, a submission with exactly the expected files and the runner\'s ledger', async () => {67    const { result, cfg, job, log, captured } = await run('ok');68    expect(result.outcome, log).toBe('submission');69    if (result.outcome !== 'submission') return;70    expect(captured.running).toBe(1);71    expect(result.usage.sandbox).toBe(process.platform === 'darwin' ? 'sandbox-exec' : 'none');72    expect(result.usage.exitCode).toBe(0);73    expect(result.usage.ledgerTampered).toBe(false);74    const sub = decodeSubmission(result.archive);75    expect(Object.keys(sub.files).sort()).toEqual(['NOTES.md', 'README.md', 'claims.json', 'strategy.py']);76    expect(new TextDecoder().decode(sub.files['strategy.py'])).toContain(`"name": "${job.strategyName}"`);77    // the ledger is the RUNNER's copy: 2 explicit trials, the report's own selection runs, exactly one test evaluation78    const recs = result.archive.ledger.trim().split('\n').map((l) => JSON.parse(l) as { kind: string });79    expect(recs.filter((r) => r.kind === 'test')).toHaveLength(1);80    expect(recs.filter((r) => r.kind === 'trial').length).toBeGreaterThanOrEqual(3);81    expect(result.usage.trials).toBe(recs.length);82    // the claims were written by the laboratory from its own report83    const { claims } = parseClaims(new TextDecoder().decode(sub.files['claims.json']));84    expect(claims?.trials).toBe(recs.length);85    expect(typeof claims?.inner_test?.sharpe === 'number' || claims?.inner_test?.sharpe === null).toBe(true);86    // nothing is left behind: the job directory is gone, the runner's ledger copy stays87    expect(existsSync(jobPaths(cfg, job.id).job)).toBe(false);88    expect(readFileSync(jobPaths(cfg, job.id).ledgerCopy, 'utf8')).toBe(result.archive.ledger);89    expect(log).toMatch(/starting the agent \(command\)/);90  }, T);9192  it('crash: a non-zero exit is a failed job, never a submission', async () => {93    const { result } = await run('crash');94    expect(result.outcome).toBe('failed');95    if (result.outcome === 'failed') { expect(result.reason).toMatch(/exited with code 3/); expect(result.usage.exitCode).toBe(3); }96  }, T);9798  it('exit 0 without files, an empty submission: failed (malformed)', async () => {99    const { result } = await run('nothing');100    expect(result).toMatchObject({ outcome: 'failed' });101    if (result.outcome === 'failed') expect(result.reason).toMatch(/malformed submission: the submission has no strategy.py/);102  }, T);103104  it('timeout: the wall-clock budget kills the agent from outside → over_budget, nothing is submitted', async () => {105    const job = makeJob(); job.budgets = { ...job.budgets, wallSeconds: 2 };106    const cfg = testConfig('hang'), h = hooks(), t0 = Date.now();107    const result = await runJob(job, cfg, h.hooks);108    expect(result.outcome).toBe('over_budget');109    if (result.outcome === 'over_budget') expect(result.reason).toMatch(/wall time over 2 s/);110    expect(Date.now() - t0).toBeLessThan(15_000);111    expect(result.usage.signal).toBe('SIGKILL');112  }, T);113114  it('cancel: the owner\'s cancel request kills the agent → cancelled', async () => {115    const job = makeJob(), cfg = testConfig('hang'), h = hooks();116    setTimeout(() => { h.captured.cancel = true; }, 1500);117    const result = await runJob(job, cfg, h.hooks);118    expect(result).toMatchObject({ outcome: 'cancelled', reason: 'cancelled by the owner' });119  }, T);120121  // v10: through the runner loop, as in production — the cancel is only known from the API's answer to a log push122  it('cancel of a SILENT agent: nothing is printed after the first line, the heartbeat still learns the cancel', async () => {123    const job = makeJob(), cfg = { ...testConfig('hang'), logFlushMs: 150 }, pushes: number[] = []; let cancelAt = 0, wanted = false;124    // V11 final validation: the cancel was armed by a 2.5 s wall-clock timer and the test then counted the empty pushes made before it —125    // on a busy machine the agent's start took most of those 2.5 s and only two had been made (one failure in three full runs).126    // The owner's cancel is now wanted once the agent's line has been pushed AND three heartbeats have followed it: the same127    // situation, whatever the machine's speed. Without a heartbeat the cancel is never wanted and the test times out, as it should.128    const api = { claim: async () => null, result: async () => {}, log: async (_j: unknown, lines: unknown[]) => {129      pushes.push(lines.length);130      const first = pushes.findIndex((n) => n > 0);131      if (!wanted && first >= 0 && pushes.slice(first + 1).filter((n) => n === 0).length >= 3) { wanted = true; cancelAt = Date.now(); }132      return { cancel: wanted }; } };133    const result = await processJob(job, cfg, api as never);134    expect(result).toMatchObject({ outcome: 'cancelled', reason: 'cancelled by the owner' });135    expect(Date.now() - cancelAt).toBeLessThan(5000);                    // not the wall-clock budget (minutes)136    expect(pushes.filter((n) => n === 0).length).toBeGreaterThan(2);     // empty batches were pushed to ask137    expect(pushes.some((n) => n > 0)).toBe(true); expect(cancelAt).toBeGreaterThan(0);   // the agent's line was pushed first; the cancel came from a heartbeat's answer138  }, T);139140  it('trial budget: more ledger lines than allowed → over_budget, and the consumed trials are reported', async () => {141    const { result } = await run('trials', { n: 40, waitMs: 5000 }, { job: { budgets: { maxTrials: 10 } } });142    expect(result.outcome).toBe('over_budget');143    // the runner kills as soon as it sees the overrun: between 11 and 40 lines were written by then, and all of them are reported144    if (result.outcome === 'over_budget') { expect(result.reason).toMatch(/^\d+ trials, budget 10$/); expect(result.usage.trials).toBeGreaterThan(10); expect(result.usage.trials).toBeLessThanOrEqual(40);145      expect(result.ledger.trim().split('\n')).toHaveLength(result.usage.trials); }146  }, T);147148  it('disk budget: the job directory is measured from outside → over_budget', async () => {149    const { result } = await run('disk', { mb: 40, waitMs: 8000 }, { job: { budgets: { maxDiskMb: 16 } } });150    expect(result.outcome).toBe('over_budget');151    if (result.outcome === 'over_budget') expect(result.reason).toMatch(/MB on disk .* budget 16 MB/);152  }, T);153154  it('malformed submissions are refused by the runner: oversized file, unexpected file, symlink, hard link', async () => {155    const reasons: Record<string, RegExp> = { oversized: /NOTES.md is 307200 bytes \(limit 262144\)/, extra: /unexpected file in the submission: "run.sh"/, symlink: /strategy.py cannot be opened as a regular file/, hardlink: /strategy.py has 2 hard links/ };156    for (const [mode, re] of Object.entries(reasons)) {157      const { result, log } = await run(mode);158      expect(result.outcome, `${mode}\n${log}`).toBe('failed');159      if (result.outcome === 'failed') expect(result.reason, mode).toMatch(re);160    }161  }, 4 * T);162163  it('ledger tampering: emptying the agent\'s ledger file does not shrink the runner\'s copy, and is reported', async () => {164    const { result, log } = await run('tamper');165    expect(result.outcome, log).toBe('submission');166    expect(result.usage.ledgerTampered).toBe(true);167    expect(result.usage.trials).toBeGreaterThanOrEqual(4);168    if (result.outcome === 'submission') expect(result.archive.ledger.trim().split('\n').length).toBe(result.usage.trials);169  }, T);170171  it('the inner test split is sealed across processes: a second evaluation with another version is refused by the laboratory', async () => {172    const { result, log } = await run('second-look');173    expect(log).toMatch(/second look: exit 7: spq.job: TestSplitError: the inner test split of this job was already evaluated/);174    expect(result.outcome).toBe('submission');175    if (result.outcome === 'submission') expect(result.archive.ledger.trim().split('\n').map((l) => JSON.parse(l) as { kind: string }).filter((r) => r.kind === 'test')).toHaveLength(1);176  }, T);177178  it('a runner that requires the OS sandbox does not start a job without it', async () => {179    if (sandboxAvailable()) return;                                    // only meaningful where sandbox-exec is missing180    const { result } = await run('ok', {}, { cfg: { sandbox: 'required' } });181    expect(result).toMatchObject({ outcome: 'failed' });182  }, T);183});184185describe('runner units', () => {186  it('LedgerTail copies complete lines only, never shrinks, and flags truncation and in-place rewrites', () => {187    const dir = mkdtempSync(path.join(tmpdir(), 'spw-ledger-')), src = path.join(dir, 'src.jsonl'), copy = path.join(dir, 'copy.jsonl');188    const t = new LedgerTail(src, copy, 10_000);189    expect(t.sync()).toBe(0);190    writeFileSync(src, '{"a":1}\n{"a":2}\n{"a":'); expect(t.sync()).toBe(2);191    appendFileSync(src, '3}\n'); expect(t.sync()).toBe(1);192    expect(readFileSync(copy, 'utf8')).toBe('{"a":1}\n{"a":2}\n{"a":3}\n');193    writeFileSync(src, '');                                             // truncated194    expect(t.sync()).toBe(0); expect(t.tampered).toBe(true); expect(t.lines).toBe(3);195    writeFileSync(src, '{"b":1}\n'); expect(t.sync()).toBe(1); expect(t.lines).toBe(4);196    const t2 = new LedgerTail(path.join(dir, 's2'), path.join(dir, 'c2'), 10_000);197    writeFileSync(path.join(dir, 's2'), '{"x":1}\n{"x":2}\n'); t2.sync();198    writeFileSync(path.join(dir, 's2'), '{"x":9}\n{"x":2}\n{"x":3}\n');  // rewritten in place, longer199    t2.sync(); expect(t2.tampered).toBe(true); expect(t2.lines).toBe(5); // every line of the new file counts again200    const big = new LedgerTail(path.join(dir, 's3'), path.join(dir, 'c3'), 30);201    writeFileSync(path.join(dir, 's3'), `${'{"k":1}\n'.repeat(10)}${'x'.repeat(5000)}\n`); big.sync();202    expect(big.lines).toBe(11); expect(readFileSync(path.join(dir, 'c3'), 'utf8').length).toBeLessThanOrEqual(30); // counted even when the copy is full203  });204205  it('collectSubmission accepts exactly the expected regular files', () => {206    const dir = mkdtempSync(path.join(tmpdir(), 'spw-sub-'));207    expect(() => collectSubmission(path.join(dir, 'none'))).toThrow(/no submission directory/);208    writeFileSync(path.join(dir, 'strategy.py'), 'META = {}\n'); writeFileSync(path.join(dir, 'README.md'), '# x\n');209    expect(collectSubmission(dir).map((f) => f.path)).toEqual(['strategy.py', 'README.md']);210    writeFileSync(path.join(dir, 'claims.json'), ''); expect(() => collectSubmission(dir)).toThrow(/claims.json is empty/);211    writeFileSync(path.join(dir, 'claims.json'), '{}'); writeFileSync(path.join(dir, '.hidden'), 'x'); expect(() => collectSubmission(dir)).toThrow(/unexpected file/);212    expect(readdirSync(dir)).toContain('.hidden');213  });214215  it('the Claude Code invocation: headless, bare (no keychain, no OAuth), listed tools only, nothing that prompts, no web tool, the brief as system prompt', () => {216    const job = makeJob(), cfg = testConfig('ok', {}, { agent: { kind: 'claude', bin: '/opt/homebrew/bin/claude', model: 'sonnet', argv: [] } });217    const argv = agentArgv(cfg, job, jobPaths(cfg, job.id));218    expect(argv[0]).toBe('/opt/homebrew/bin/claude');219    expect(argv.slice(1, 3)[0]).toBe('-p');220    for (const flag of ['--bare', '--verbose', '--strict-mcp-config', '--disable-slash-commands', '--no-session-persistence']) expect(argv).toContain(flag);221    const val = (f: string) => argv[argv.indexOf(f) + 1];222    expect(val('--output-format')).toBe('stream-json');223    expect(val('--tools')).toBe('Read,Write,Edit,Glob,Grep,Bash');224    expect(val('--allowedTools')).toBe(val('--tools'));225    expect(val('--disallowedTools')).toBe('WebFetch,WebSearch');226    expect(val('--permission-mode')).toBe('dontAsk');227    expect(val('--permission-prompts')).toBe('none');228    expect(val('--max-budget-usd')).toBe('10');229    expect(val('--model')).toBe('sonnet');230    expect(val('--append-system-prompt-file')).toMatch(/\/ro\/CLAUDE\.md$/);231    expect(argv.join(' ')).not.toMatch(/dangerously|bypassPermissions/);232  });233234  it('stream-json events become log lines; the cost comes from the result event', () => {235    expect(describeStreamEvent('{"type":"assistant","message":{"content":[{"type":"text","text":"Reading the lab"},{"type":"tool_use","name":"Bash","input":{"command":"python -m spq.job info"}}]}}').text).toBe('agent: Reading the lab\ntool Bash: python -m spq.job info');236    expect(describeStreamEvent('{"type":"result","subtype":"success","num_turns":7,"total_cost_usd":0.4321}')).toEqual({ text: 'agent finished: success, 7 turns, 0.4321 USD reported by the CLI', costUsd: 0.4321 });237    expect(describeStreamEvent('not json')).toEqual({ text: 'not json', costUsd: null });238  });239240  it('configuration: the model credential is taken out of the environment, the runner secret has a minimum length, Claude needs a credential', () => {241    const base = { SPW_RUNNER_API_URL: 'https://wallet.example/', SPW_RUNNER_SECRET: 'r'.repeat(40), SPW_RUNNER_LAB_DIR: '/x/research' };242    const env: NodeJS.ProcessEnv = { ...base, ANTHROPIC_API_KEY: 'sk-test-not-a-real-key' };243    const cfg = configFromEnv(env);244    expect(cfg.model.credential).toEqual(['x-api-key', 'sk-test-not-a-real-key']);245    expect(env.ANTHROPIC_API_KEY).toBeUndefined();246    expect(cfg.apiUrl).toBe('https://wallet.example');247    expect(cfg.sandbox).toBe('required'); expect(cfg.labPin).toBe('commit');248    expect(() => configFromEnv({ ...base })).toThrow(/needs ANTHROPIC_API_KEY/);249    expect(() => configFromEnv({ ...base, SPW_RUNNER_SECRET: 'short' })).toThrow(/at least 32/);250    expect(configFromEnv({ ...base, SPW_RUNNER_AGENT: 'command', SPW_RUNNER_AGENT_CMD: '["/bin/true"]' }).agent).toMatchObject({ kind: 'command', argv: ['/bin/true'] });251  });252});253
Files main
Menu

Theme