okami.mom/strata

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

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
16.2 KiB233 linesraw
1import './helpers/isolate-profile.mjs';   // a test run never writes the owner's real Strata profile
2import test from 'node:test';
3import assert from 'node:assert/strict';
4import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'node:fs';
5import { join } from 'node:path';
6import { tmpdir } from 'node:os';
7import { createControl, ControlError } from '../server/control-runtime.mjs';
8import { plainUpdateError, plainEngineError, UPDATE_WAITING_FOR_LOCK } from '../server/update-messages.mjs';
9import { createNativeControl } from '../server/native-control.mjs';
10import { checkComponentUpdates, engineFailedBeforeText, engineFirstRun } from '../server/updates.mjs';
11
12// Lane APP-LIN (0.2.14): the update and first-run fixes of the 0.2.13 GUI tests.
13
14const LOCK = 'another update is already running for this component folder';
15
16function fixture({ update, cfgExtra = {}, reload } = {}) {
17  const root = mkdtempSync(join(tmpdir(), 'strata-applin-'));
18  const install = join(root, 'install'), data = join(root, 'data');
19  mkdirSync(install, { recursive: true });
20  process.env.STRATA_INSTALL_DIR = install;
21  const config = join(install, 'strata-iq2_xs.json');
22  mkdirSync(join(root, 'control', 'data'), { recursive: true });
23  writeFileSync(join(root, 'control', 'data', 'expert-profile.bin'), 'x');
24  writeFileSync(config, JSON.stringify({ exe: 'component:strata-engine', args: ['--max-context', '32768'], model_name: 'Qwen', port: 8080, ...cfgExtra }));
25  const calls = [];
26  const control = {
27    control: { dir: join(root, 'control') }, version: '0.1.60',
28    async installedModels() { return { install_dir: install, models: [{ id: 'iq2_xs', name: 'Qwen', source_config: config, component_status: 'present', context_tokens: 32768, backend: 'cuda' }] }; },
29    async engine() { return { usable: true, backend: 'cuda', components_dir: '/c', engine: { version: '0.1.60', platform: 'linux-x86_64', backend: 'cuda', exe: 'e', root: 'r' } }; },
30    async saveProfile() { return {}; }, async start() { return { ok: true, state: 'ready' }; }, async stop() { return { ok: true }; },
31    ...(reload ? { reload() { calls.push(['reload']); return reload(this); } } : {}),
32    async update(options) {
33      calls.push(['update', options.engine, options.control, options.force === true]);
34      await update?.(options, calls.length);
35      return { ok: true, results: [{ component: 'engine', status: 'updated', installed_after: { version: '0.1.61' } }] };
36    },
37  };
38  const native = createNativeControl({ control, directory: data, lockWaitMs: 300, lockPollMs: 20, spawnProcess: () => { throw new Error('no process'); }, fetcher: async () => Response.json({}), requests: () => [] });
39  return { native, calls, root, config, cleanup: () => rmSync(root, { recursive: true, force: true }) };
40}
41const finish = async (native, id) => { for (let i = 0; i < 400; i++) { const job = native.state().jobs.find(j => j.id === id); if (job.state !== 'running') return job; await new Promise(r => setTimeout(r, 10)); } throw new Error('job did not finish'); };
42
43// ------------------------------------------------------------------ item 4: exit 7 is two things
44
45test('exit 7 from the update lock is "an update is already running", not "a model is running"', () => {
46  for (const error of [Object.assign(new Error(LOCK), { exitCode: 7 }), Object.assign(new Error(LOCK), { exitCode: 7, code: 'engine_serving' }), new ControlError(LOCK, { exitCode: 7, code: 'update_busy' })]) {
47    const plain = plainUpdateError(error, 'engine', 'Continue');
48    assert.match(plain.message, /An update is already running/);
49    assert.doesNotMatch(plain.message, /model is running/);
50  }
51  // a real serving refusal keeps its words
52  const serving = plainUpdateError(Object.assign(new Error('app-1 is serving.'), { exitCode: 7, code: 'engine_serving' }));
53  assert.match(serving.message, /A model is running/);
54  assert.match(plainEngineError(Object.assign(new Error(LOCK), { exitCode: 7 })).message, /An update is running/);
55  assert.match(plainEngineError(Object.assign(new Error('x is serving'), { exitCode: 7 })).message, /A model is running/);
56});
57
58test('createControl tells the lock from a serving engine by the text, for both failure shapes', async () => {
59  const lockedStep = createControl({ control: { dir: '/c', python: 'p', cli: 'c' }, run: async () => ({ code: 7, json: { ok: false, results: [{ component: 'engine', status: 'failed', error: LOCK, exit_code: 7 }] }, stderr: '' }) });
60  await assert.rejects(lockedStep.update({}), e => e.code === 'update_busy' && e.exitCode === 7);
61  const lockedWhole = createControl({ control: { dir: '/c', python: 'p', cli: 'c' }, run: async () => ({ code: 7, json: { ok: false, error: { message: LOCK } }, stderr: '' }) });
62  await assert.rejects(lockedWhole.update({}), e => e.code === 'update_busy');
63  await assert.rejects(lockedWhole.updateCheck({}), e => e.code === 'update_busy');
64  const serving = createControl({ control: { dir: '/c', python: 'p', cli: 'c' }, run: async () => ({ code: 7, json: { ok: false, results: [{ component: 'engine', status: 'failed', error: 'app-1 is serving.', exit_code: 7 }] }, stderr: '' }) });
65  await assert.rejects(serving.update({}), e => e.code === 'engine_serving');
66});
67
68test('the first-run Download waits for the lock the start-up check holds, then installs', async () => {
69  const f = fixture({ update: async (_o, n) => { if (n < 3) throw new ControlError(LOCK, { exitCode: 7, code: 'update_busy' }); } });
70  try {
71    const started = f.native.operation('update-engine', { firstRun: true });
72    let sawWaiting = false;
73    for (let i = 0; i < 50 && !sawWaiting; i++) { sawWaiting = f.native.state().jobs.find(j => j.id === started.id)?.summary === UPDATE_WAITING_FOR_LOCK; await new Promise(r => setTimeout(r, 5)); }
74    const job = await finish(f.native, started.id);
75    assert.equal(job.state, 'done', job.error);
76    assert.equal(f.calls.length, 3, 'tried again while the lock was held');
77    assert.ok(sawWaiting, 'the job said it was waiting');
78  } finally { await f.native.close(); f.cleanup(); }
79});
80
81test('a lock that stays held ends with the lock words, after the wait', async () => {
82  const f = fixture({ update: async () => { throw new ControlError(LOCK, { exitCode: 7, code: 'update_busy' }); } });
83  try {
84    const job = await finish(f.native, f.native.operation('update-engine', { firstRun: true }).id);
85    assert.equal(job.state, 'error');
86    assert.match(job.error, /An update is already running/);
87    assert.doesNotMatch(job.error, /model is running/);
88    assert.ok(f.calls.length >= 2);
89  } finally { await f.native.close(); f.cleanup(); }
90});
91
92test('a serving refusal is not retried', async () => {
93  const f = fixture({ update: async () => { throw new ControlError('app-1 is serving.', { exitCode: 7, code: 'engine_serving' }); } });
94  try {
95    const job = await finish(f.native, f.native.operation('update-engine', {}).id);
96    assert.equal(job.state, 'error');
97    assert.equal(f.calls.length, 1);
98    assert.match(job.error, /A model is running/);
99  } finally { await f.native.close(); f.cleanup(); }
100});
101
102// ------------------------------------------------------------------ item 3: a failed engine update is not "up to date"
103
104test('an engine version that failed its test start here is offered again with the owner-approved words', async () => {
105  const note = '0.1.59 failed its test start on 2026-11-09 (read_expert_profile: cannot open ...); run `strata update --force` to try it again';
106  const control = { version: '0.1.59', async updateCheck() { return { ok: true, feed: { sequence: 123 }, engine: { installed: { version: '0.1.58' }, offered: { version: '0.1.59' }, status: 'failed-before', note, download_bytes: 723e6 }, control: { installed: '0.1.59', offered: '0.1.59', status: 'current' }, app: { status: 'not-in-feed' } }; } };
107  const result = await checkComponentUpdates({ control, appVersion: '0.2.13' });
108  assert.equal(result.engine.status, 'available');
109  assert.equal(result.engine.canInstall, true);
110  assert.equal(result.engine.retry, true);
111  assert.equal(result.engine.message, "Engine 0.1.59 didn't start correctly on this computer, so Strata kept engine 0.1.58. Press Update engine to try again.");
112  assert.equal(result.engine.message, engineFailedBeforeText('0.1.59', '0.1.58'));
113  assert.equal(result.engine.details, note, 'the reason stays behind Details');
114  assert.doesNotMatch(result.engine.message, /up to date/);
115  // a version the person switched away from (skipped) still reads as current
116  const skipped = await checkComponentUpdates({ control: { ...control, async updateCheck() { return { ok: true, feed: {}, engine: { installed: { version: '0.1.58' }, offered: { version: '0.1.59' }, status: 'skipped' }, control: {}, app: {} }; } }, appVersion: '0.2.13' });
117  assert.equal(skipped.engine.status, 'current');
118});
119
120test('the app\'s Update engine asks Control to try a held-back version again (--force)', async () => {
121  const f = fixture();
122  try {
123    const job = await finish(f.native, f.native.operation('update-engine', {}).id);
124    assert.equal(job.state, 'done', job.error);
125    assert.deepEqual(f.calls[0], ['update', true, false, true]);
126  } finally { await f.native.close(); f.cleanup(); }
127});
128
129// ------------------------------------------------------------------ item 2: a stale /tmp/.mount_* path
130
131test('the engine update repairs run-config paths of a gone AppImage mount before Control test-starts with it', async () => {
132  const gone = '/tmp/.mount_StratappjGco/usr/lib/Strata/control';
133  let seen = null;
134  const f = fixture({ cfgExtra: { cwd: gone, args: ['--expert-profile', gone + '/data/expert-profile.bin', '--max-context', '32768'] },
135    update: async () => { seen = JSON.parse(readFileSync(f.config, 'utf8')); } });
136  try {
137    const job = await finish(f.native, f.native.operation('update-engine', {}).id);
138    assert.equal(job.state, 'done', job.error);
139    assert.ok(seen, 'Control was called');
140    assert.equal(seen.cwd, join(f.root, 'control'));
141    assert.equal(seen.args[1], join(f.root, 'control', 'data', 'expert-profile.bin'));
142  } finally { await f.native.close(); f.cleanup(); }
143});
144
145// ------------------------------------------------------------------ item 1: the app update's job across the restart
146
147test('an app update job the old host closed as "cancelled" is read as finished by the new version; this host keeps it running when it closes', async () => {
148  const before = process.env.STRATA_APP_VERSION;
149  const root = mkdtempSync(join(tmpdir(), 'strata-applin-jobs-'));
150  try {
151    const job = { id: 'j1', kind: 'update-strata', state: 'cancelled', startedAt: new Date().toISOString(), summary: 'Downloading the app update: 100%', appUpdateFrom: '0.2.13', appUpdateTo: '0.2.14' };
152    writeFileSync(join(root, 'native-jobs.json'), JSON.stringify([job, { ...job, id: 'j2', appUpdateFrom: undefined }]));
153    process.env.STRATA_APP_VERSION = '0.2.14';
154    const mk = () => createNativeControl({ control: { control: { dir: '/c' }, version: '0.1.60' }, directory: root, spawnProcess: () => { throw new Error('no process'); }, fetcher: async () => Response.json({}), requests: () => [] });
155    const next = mk();
156    const jobs = next.state().jobs;
157    assert.equal(jobs.find(j => j.id === 'j1').state, 'done');
158    assert.match(jobs.find(j => j.id === 'j1').summary, /updated to 0\.2\.14/);
159    assert.equal(jobs.find(j => j.id === 'j2').state, 'cancelled', 'a cancelled job that was not an app update stays cancelled');
160    await next.close();
161    // the same version came back: the update did not finish, and it says so
162    writeFileSync(join(root, 'native-jobs.json'), JSON.stringify([{ ...job, appUpdateFrom: '0.2.14' }]));
163    const same = mk();
164    assert.equal(same.state().jobs[0].state, 'error');
165    await same.close();
166  } finally { if (before === undefined) delete process.env.STRATA_APP_VERSION; else process.env.STRATA_APP_VERSION = before; rmSync(root, { recursive: true, force: true }); }
167});
168
169test('closing the host during an app update leaves its job running (the next start settles it)', async () => {
170  const before = process.env.STRATA_APP_VERSION;
171  process.env.STRATA_APP_VERSION = '0.2.14';
172  const root = mkdtempSync(join(tmpdir(), 'strata-applin-close-'));
173  const control = { control: { dir: '/c' }, version: '0.1.60', async update() { return { ok: true, results: [] }; } };
174  const appUpdater = { check: async () => ({ available: true, version: '0.2.15' }), install: () => new Promise(() => {}) };
175  const native = createNativeControl({ control, appUpdater, directory: root, spawnProcess: () => { throw new Error('no process'); }, fetcher: async () => Response.json({}), requests: () => [] });
176  try {
177    const started = native.operation('update-strata', {});
178    for (let i = 0; i < 100 && !native.state().jobs.find(j => j.id === started.id)?.appUpdateFrom; i++) await new Promise(r => setTimeout(r, 10));
179    await native.close();
180    assert.equal(native.state().jobs.find(j => j.id === started.id).state, 'running');
181  } finally { if (before === undefined) delete process.env.STRATA_APP_VERSION; else process.env.STRATA_APP_VERSION = before; rmSync(root, { recursive: true, force: true }); }
182});
183
184// ------------------------------------------------------------------ item 5: the first-run card offers the Control update
185
186const feedReport = control => ({ ok: true, feed: {}, hardware: { backend: 'sycl' }, engine: { status: 'install', installed: null, offered: { version: '0.1.60', variant: '', backend: 'sycl' }, download_bytes: 300e6 }, control, app: {} });
187
188test('the first-run card names a newer Control in the feed, and nothing when there is none', async () => {
189  const withControl = await engineFirstRun({ control: { updateCheck: async () => feedReport({ installed: '0.1.60', offered: '0.1.60.1', status: 'available', download_bytes: 120e6 }) } });
190  assert.equal(withControl.status, 'offer');
191  assert.deepEqual(withControl.control, { version: '0.1.60.1', bytes: 120e6 });
192  const current = await engineFirstRun({ control: { updateCheck: async () => feedReport({ installed: '0.1.60', offered: '0.1.60', status: 'current' }) } });
193  assert.equal(current.control, null);
194});
195
196test('the first-run Download with the Control: engine first, then Control, then the app switches to it while nothing runs', async () => {
197  const f = fixture({ reload: self => { self.control = { dir: '/new/control' }; self.version = '0.1.60.1'; return true; } });
198  try {
199    const job = await finish(f.native, f.native.operation('update-engine', { firstRun: true, withControl: true }).id);
200    assert.equal(job.state, 'done', job.error);
201    assert.deepEqual(f.calls.map(c => c.slice(0, 3)), [['update', true, false], ['update', false, true], ['reload']]);
202  } finally { await f.native.close(); f.cleanup(); }
203});
204
205test('a Control update that fails on first run keeps the engine and the job; no switch', async () => {
206  const f = fixture({ update: async options => { if (options.control) throw new Error('the package failed its check'); }, reload: () => true });
207  try {
208    const job = await finish(f.native, f.native.operation('update-engine', { firstRun: true, withControl: true }).id);
209    assert.equal(job.state, 'done', job.error);
210    assert.ok(!f.calls.some(c => c[0] === 'reload'));
211  } finally { await f.native.close(); f.cleanup(); }
212});
213
214test('without withControl (or from Settings) the engine update never touches Control', async () => {
215  const f = fixture({ reload: () => true });
216  try {
217    await finish(f.native, f.native.operation('update-engine', { firstRun: true }).id);
218    await finish(f.native, f.native.operation('update-engine', {}).id);
219    assert.deepEqual(f.calls.map(c => c.slice(0, 3)), [['update', true, false], ['update', true, false]]);
220  } finally { await f.native.close(); f.cleanup(); }
221});
222
223test('createControl.reload switches to a newer Control and the next call runs from it; the same folder is no switch', async () => {
224  const seen = [];
225  const first = { dir: '/a/control', python: '/a/py', cli: '/a/strata.py', bundle: { version: '0.1.60' } };
226  const ctl = createControl({ control: first, run: async (args) => { seen.push(args[0]); return { code: 0, json: { ok: true } }; } });
227  assert.equal(ctl.reload({ find: () => ({ ...first }) }), false);
228  assert.equal(ctl.reload({ find: () => null }), false);
229  const next = { dir: '/b/control', python: '/b/py', cli: '/b/strata.py', bundle: { version: '0.1.60.1' } };
230  assert.equal(ctl.reload({ find: () => next }), true);
231  assert.equal(ctl.control.dir, '/b/control');
232  assert.equal(ctl.version, '0.1.60.1');
233});