okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221merge f-split-agent3 c99896ae6 (status, goal and time-skip events and backend, time-skip keepalive and stop, atomic.py) into f-split-intf9bfe8bc1

main
8.2 KiB200 linesraw
1import { fileURLToPath } from 'node:url';
2/**
3 * The tuning and Time-skip client routes.
4 *
5 * These are contract tests for the bridge between the App Host and Strata Control. They are
6 * deliberately about the *shapes and the refusals*, not about measurement numbers: the numbers come
7 * from the job, and the job has its own tests. What matters here is that the Host does not become a
8 * second source of truth.
9 *
10 * Two properties are load-bearing and are asserted directly:
11 *
12 *   1. The tuning plan is computed from the **engine binary's own flags**, so a dimension the binary
13 *      cannot accept is excluded with a reason. A plan that offered one would let a sweep "measure"
14 *      a configuration the engine would refuse to start.
15 *   2. A concurrent user edit is a **409 conflict**, not a silent overwrite and not a 500.
16 */
17import test from 'node:test';
18import assert from 'node:assert/strict';
19import { spawn } from 'node:child_process';
20import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
21import { tmpdir } from 'node:os';
22import { join } from 'node:path';
23
24const HOST = fileURLToPath(new URL('../server/index.mjs',import.meta.url));
25const REPO = fileURLToPath(new URL('../../..',import.meta.url));
26
27const wait = (ms) => new Promise((r) => setTimeout(r, ms));
28
29async function listenFree() {
30  const net = await import('node:net');
31  const srv = net.createServer();
32  await new Promise((r) => srv.listen(0, '127.0.0.1', r));
33  const { port } = srv.address();
34  await new Promise((r) => srv.close(r));
35  return port;
36}
37
38/** Start the host against a disposable home, and wait for health. */
39async function startHost({ python } = {}) {
40  const home = await mkdtemp(join(tmpdir(), 'strata-tune-routes-'));
41  await mkdir(join(home, 'data'), { recursive: true });
42  const port = await listenFree();
43  const child = spawn(process.execPath, [HOST, '--dist', join(REPO, 'apps/host/dist')], {
44    cwd: join(REPO, 'apps/host'),
45    env: {
46      ...process.env,
47      STRATA_HOME: home,
48      // the Time-skip runs of whoever uses this PC live in their own state folder; a test must not read (or write) them
49      STRATA_TIMESKIP_DIR: join(home, 'time-skip'),
50      STRATA_PORT: String(port),
51      STRATA_REAL_ENGINE: '0',
52      ...(python ? { STRATA_PYTHON: python } : {}),
53    },
54    stdio: 'ignore',
55  });
56  const base = `http://127.0.0.1:${port}`;
57  for (let i = 0; i < 100; i++) {
58    try {
59      const res = await fetch(`${base}/api/health`);
60      if (res.ok) return { child, base, home };
61    } catch { /* not up yet */ }
62    await wait(100);
63  }
64  child.kill('SIGKILL');
65  throw new Error('the host did not become healthy');
66}
67
68test('an unconfigured engine is reported as unavailable rather than guessed at', { timeout: 30000 }, async () => {
69  const { child, base } = await startHost();
70  try {
71    const r = await fetch(`${base}/api/tune/engine`);
72    assert.equal(r.status, 200);
73    const body = await r.json();
74    // The panel uses `available` to decide whether to offer a plan at all. A guessed path would
75    // produce a plan about the wrong engine, which is worse than no plan.
76    assert.equal(typeof body.available, 'boolean');
77    assert.ok('path' in body);
78    if (!body.available) assert.equal(body.path, null);
79  } finally {
80    child.kill('SIGKILL');
81  }
82});
83
84test('the tuning plan comes from the engine binary and excludes what it cannot accept', { timeout: 60000 }, async () => {
85  // A stub engine that accepts exactly two of the flags the static table knows about. The plan must
86  // offer only those two, and must name each exclusion.
87  const dir = await mkdtemp(join(tmpdir(), 'strata-tune-stub-'));
88  // A Python stub, run by Strata Control as [python, stub.py] on every OS (a #! script is WinError 193 on Windows).
89  const engine = join(dir, 'strata-stub.py');
90  await writeFile(engine, 'import sys\nfor line in ("usage:", "  --kv KV", "  --ple-io MODE"):\n    print(line, file=sys.stderr)\n');
91
92  const { child, base } = await startHost();
93  try {
94    const r = await fetch(`${base}/api/tune/plan`, {
95      method: 'POST',
96      headers: { 'content-type': 'application/json' },
97      body: JSON.stringify({ engine, backend: 'metal', model: 'fixture', objective: 'generation' }),
98    });
99    // Read the body once: consuming it in an assertion message leaves nothing for `.json()`.
100    const raw = await r.text();
101    assert.equal(r.status, 200, raw);
102    const { plan } = JSON.parse(raw);
103    assert.equal(plan.engine_flags_known, true, 'the stub engine read cleanly');
104
105    const offered = plan.dimensions.map((d) => d.id);
106    assert.deepEqual(offered.sort(), ['kv', 'ple_io'],
107      'only the dimensions whose flags this binary accepts may be searched');
108
109    const excluded = Object.fromEntries(plan.excluded.map((e) => [e.id, e.reason]));
110    for (const id of ['vram_reserve', 'pcie_frac']) {
111      assert.ok(excluded[id], `${id} must be excluded and explained`);
112      assert.match(excluded[id], /does not accept|NVIDIA\/AMD/);
113    }
114    // The bound is displayed before a sweep starts, and the repeat floor is the specification's.
115    assert.equal(plan.repeats, 3);
116    assert.ok(plan.max_trials > 0);
117  } finally {
118    child.kill('SIGKILL');
119    await rm(dir, { recursive: true, force: true });
120  }
121});
122
123test('a plan request without an engine or backend is refused with a typed error', { timeout: 30000 }, async () => {
124  const { child, base } = await startHost();
125  try {
126    const r = await fetch(`${base}/api/tune/plan`, {
127      method: 'POST',
128      headers: { 'content-type': 'application/json' },
129      body: JSON.stringify({}),
130    });
131    assert.equal(r.status, 400);
132    const body = await r.json();
133    assert.ok(body.error, 'a refusal must carry a reason');
134  } finally {
135    child.kill('SIGKILL');
136  }
137});
138
139test('an unknown tuning job is a 404, and a malformed id cannot escape the store', { timeout: 30000 }, async () => {
140  const { child, base } = await startHost();
141  try {
142    for (const id of ['deadbeefdeadbeef', '../../etc/passwd', 'not-hex']) {
143      const r = await fetch(`${base}/api/tune/job?id=${encodeURIComponent(id)}`);
144      // `deadbeef…` is well-formed but absent; the other two must be rejected by shape. Either way
145      // the answer is 404 — never a path outside the store.
146      assert.equal(r.status, 404, `id ${id} must not resolve`);
147    }
148  } finally {
149    child.kill('SIGKILL');
150  }
151});
152
153test('the Time-skip run list is empty and honest when nothing has run', { timeout: 30000 }, async () => {
154  const { child, base } = await startHost();
155  try {
156    const r = await fetch(`${base}/api/timeskip`);
157    assert.equal(r.status, 200);
158    const body = await r.json();
159    assert.deepEqual(body.runs, []);
160    assert.ok(body.stateDir, 'the store location is reported so a developer can inspect it');
161  } finally {
162    child.kill('SIGKILL');
163  }
164});
165
166test('applying an unknown Time-skip run is refused, not silently accepted', { timeout: 30000 }, async () => {
167  const { child, base } = await startHost();
168  try {
169    const r = await fetch(`${base}/api/timeskip/apply`, {
170      method: 'POST',
171      headers: { 'content-type': 'application/json' },
172      body: JSON.stringify({ id: 'a'.repeat(32) }),
173    });
174    assert.ok(r.status >= 400, 'an unknown run must not report success');
175    const body = await r.json();
176    assert.ok(body.error !== undefined);
177  } finally {
178    child.kill('SIGKILL');
179  }
180});
181
182test('an HTTP caller cannot supply an arbitrary revision command', { timeout: 30000 }, async () => {
183  // `reviseCommand` is configured, never requested: accepting one would hand a remote caller
184  // command execution on the user's machine. The route must ignore the field.
185  const { child, base } = await startHost();
186  try {
187    const r = await fetch(`${base}/api/timeskip/start`, {
188      method: 'POST',
189      headers: { 'content-type': 'application/json' },
190      body: JSON.stringify({ workspace: '/nonexistent-workspace', prompt: 'x',
191                             reviseCommand: 'touch /tmp/strata-should-not-exist' }),
192    });
193    // The run fails because the workspace does not exist -- the point is that it fails for *that*
194    // reason, and the injected command is never run.
195    assert.ok(r.status >= 400, 'a nonexistent workspace must not start a run');
196  } finally {
197    child.kill('SIGKILL');
198    await rm('/tmp/strata-should-not-exist', { force: true });
199  }
200});