okami.mom/strata

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

Niko1221The app's plain Load follows Auto everywhere: it fetches whatever Control's Auto plan says is needed (standard DFlash2 drafter included)93a1e18bc

main
18.5 KiB260 linesraw
1/**
2 * 0.2.13: the app fetches the tuned DFlash2 drafter on every path where Auto resolves to it (a plain load, a restart of the stopped models, a tuning run), like the Models screen
3 * own Load does, with the 12 hour rule (--throttle); a drafter the person named or saved wins; the plan and the Settings hint carry the size of the drafter that is really fetched.
4 * The decision is Control (strata drafting plan / fetch; tests/terminal/test_df2ux_0213.py); this file drives the host with a fake Control.
5 */
6import './helpers/isolate-profile.mjs';   // a test run never writes the owner's real Strata profile
7import test from 'node:test';
8import assert from 'node:assert/strict';
9import { EventEmitter } from 'node:events';
10import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
11import { join, dirname } from 'node:path';
12import { tmpdir } from 'node:os';
13import { createNativeControl } from '../server/native-control.mjs';
14import { createControl } from '../server/control-runtime.mjs';
15import { resolveDrafter as hostResolve } from '../server/native-settings.mjs';
16
17const SPLIT_PLAN = { ok: true, split: true, choice: 'mtp', drafter: 'mtp', needed: false, gb: 0, line: 'Drafting: MTP (the all-cards split engine uses the MTP draft layer, 5.2 GB)', serves: true };
18const DFLASH2_PLAN = { ok: true, split: false, choice: 'dflash2', drafter: 'dflash2', needed: true, gb: 1.2, mtp_needed: false, mtp_gb: 0, line: 'Drafting: DFlash2', serves: true };
19
20/**
21 * A packaged install on two 48 GB cards. `plan(options, state)` answers `drafting plan` (state.installs says how many layer installs ran), `split(options, files)` answers `split-engine apply`
22 * (it may write options.outPath), `installFails` makes the installer's MCP tool fail, `startFails` fails the first N engine starts.
23 */
24function fixture({ fetchResult = { ok: true, event: 'result', pack: 'C:/d/dflash2/x.pack', skipped: false }, plan, split = null, installFails = false, startFails = 0, metrics = {}, config = {} } = {}) {
25  const root = mkdtempSync(join(tmpdir(), 'strata-splitapp-test-'));
26  const install = join(root, 'install'), data = join(root, 'host-data'), home = join(root, 'home'), modelsDir = join(home, 'models');
27  for (const d of [install, data, modelsDir]) mkdirSync(d, { recursive: true });
28  const earlier = process.env.STRATA_INSTALL_DIR;
29  process.env.STRATA_INSTALL_DIR = install;
30  const dataFolder = join(root, 'Strata-data'), modelFolder = join(dataFolder, 'models', 'UD-Q4_K_XL');
31  const gguf = join(modelFolder, 'Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00002.gguf');
32  mkdirSync(modelFolder, { recursive: true });
33  writeFileSync(gguf, 'GGUF'); writeFileSync(gguf.replace('00001', '00002'), 'GGUF');
34  const pack = join(dataFolder, 'packs', 'ud_q4_k_xl'), mtp = join(dataFolder, 'mtp', 'rt');
35  mkdirSync(join(pack, 'tokenizer'), { recursive: true });
36  writeFileSync(join(pack, 'native_experts.txt'), 'x');
37  const configPath = join(install, 'strata-ud_q4_k_xl.json');
38  const args = ['--pack', pack, '--native', gguf, '--ple-gguf', gguf.replace('00001', '00002'), '--mtp', mtp, '--max-context', '131072', '--kv', 'int8'];
39  writeFileSync(configPath, JSON.stringify({ exe: 'component:strata-engine', tokenizer: join(pack, 'tokenizer'), args, model_name: 'qwen3.8-flash-next-ud_q4_k_xl', port: 8080, gpu: [0, 1], ...config }));
40  writeFileSync(process.env.STRATA_SETTINGS_FILE, JSON.stringify({ data_dir: join(root, 'host-owned', 'Strata-data'), data_dir_at: 1700000000 }));
41  const state = { installs: 0, planCalls: [], fetchCalls: [], splitCalls: [], saved: [], starts: 0, rpc: [] };
42  const control = {
43    control: { dir: join(root, 'control'), python: join(root, 'control', 'python', 'python') }, version: '0.2.10',
44    async installedModels() {
45      return { install_dir: install, models: [{ id: 'ud_q4_k_xl', name: 'qwen3.8-flash-next-ud_q4_k_xl', source_config: configPath, context_tokens: 131072, backend: 'cuda', component_status: 'present', missing: [], issue_codes: [] }] };
46    },
47    async engine() { return { usable: true, backend: 'cuda', components_dir: join(root, 'c'), engine: { version: '0.1.56', platform: 'linux-x86_64', backend: 'cuda', exe: join(root, 'engine', 'strata'), root: join(root, 'engine') } }; },
48    async draftingPlan(options) { state.planCalls.push(options); return typeof plan === 'function' ? plan(options, state) : plan; },
49    async draftingFetch(options) { state.fetchCalls.push(options); if (fetchResult instanceof Error) throw fetchResult; return fetchResult; },
50    async splitEngine(options) {
51      state.splitCalls.push({ ...options, input: JSON.parse(readFileSync(options.configPath, 'utf8')) });
52      if (!split) return { ok: true, split: false, line: '', warn: false, reasons: [], written: null };
53      return split(options, state);
54    },
55    async saveProfile(name, path) { state.saved.push(JSON.parse(readFileSync(path, 'utf8'))); return {}; },
56    async start() { state.starts += 1; if (state.starts <= startFails) throw new Error('The engine stopped: out of memory'); return { ok: true, state: 'ready' }; },
57    async stop() { return { ok: true }; },
58  };
59  const catalog = { families: [{ family: 'qwen', title: 'Qwen3.8-Flash-Next', about: 'x', images: false, experimental: false, sizes: [
60    { id: 'ud_q4_k_xl', model: 'UD-Q4_K_XL', download_gb: 22, ram_needed_gb: 60, about: 'x', on_this_pc: 'fits', installed: true, images: false, experimental: false }] }],
61    contexts: [32768, 131072], recommendation: { family: 'qwen', model: 'UD-Q4_K_XL', context: 131072 }, context_note: '' };
62  const hardware = { ram_gb: 256, cpu: { name: 'cpu', cores: 32 }, engine_vendor: 'nvidia', gpus: [0, 1].map(index => ({ index, name: 'NVIDIA RTX A6000', vendor: 'nvidia', vram_gb: 48, arch: 86, usable: true })) };
63  const spawnProcess = (command, argv) => {
64    if (!String(argv[0]).endsWith('strata_mcp.py')) throw new Error('no process but the installer may be started in packaged mode: ' + command + ' ' + argv.join(' '));
65    const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.exitCode = null;
66    child.kill = () => { child.exitCode = 0; queueMicrotask(() => child.emit('exit', 0)); return true; };
67    child.stdin = { write(line) {
68      const message = JSON.parse(line); if (!message.id) return;
69      if (message.method === 'tools/call') state.rpc.push(message.params);
70      let result;
71      if (message.method === 'initialize') result = { protocolVersion: '2024-11-05' };
72      else if (message.method === 'tools/list') result = { tools: ['strata_models', 'strata_status', 'strata_install', 'strata_remove'].map(name => ({ name })) };
73      else if (message.params.name === 'strata_models') result = { structuredContent: catalog };
74      else if (message.params.name === 'strata_status') result = { structuredContent: { hardware, recommendation: catalog.recommendation, install: null, running: [], summary: 'x' } };
75      else if (Object.keys(message.params.arguments ?? {}).length === 0) result = { structuredContent: { summary: 'Install finished', install: { running: false, exit_code: 0 } } };
76      else if (message.params.arguments?.confirm) {
77        if (installFails) result = { isError: true, structuredContent: { error: 'The download did not finish.' } };
78        else { state.installs += 1; mkdirSync(mtp, { recursive: true }); writeFileSync(join(mtp, 'dense.bin'), 'x'); result = { structuredContent: { summary: 'Install started', plan: {}, install: { running: true, step: '1/7' } } }; }
79      } else result = { structuredContent: { summary: 'Plan', plan: { title: 'Qwen3.8-Flash-Next UD-Q4_K_XL', download_gb: 5.2, disk_short: null } } };
80      queueMicrotask(() => child.stdout.emit('data', Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + String.fromCharCode(10))));
81    } };
82    return child;
83  };
84  const fetcher = async url => String(url).endsWith('/metrics') ? Response.json({ engine: metrics }) : Response.json({ status: 'ok' });
85  const native = createNativeControl({ control, directory: data, spawnProcess, fetcher, requests: () => [], modelsDirectory: () => modelsDir, hardwareProbe: () => [0, 1].map(index => ({ index, vram_gb: 48 })) });
86  return { native, state, root, gguf, modelFolder, mtp, configPath, args,
87    cleanup: () => { if (earlier === undefined) delete process.env.STRATA_INSTALL_DIR; else process.env.STRATA_INSTALL_DIR = earlier; rmSync(root, { recursive: true, force: true }); } };
88}
89const finish = async (native, id) => { for (let i = 0; i < 1500; 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'); };
90const load = (f, args = {}) => f.native.operation('load', { model: 'ud_q4_k_xl', ...args });
91
92/** The split engine's answer: the layer config with the split's engine and a lane count (Control's split_config, in miniature), written where the host asked. */
93const splitAnswer = (options) => {
94  const cfg = JSON.parse(readFileSync(options.configPath, 'utf8'));
95  const lanes = Math.min(8, cfg.parallel ?? 6);
96  writeFileSync(options.outPath, JSON.stringify({ ...cfg, exe: '/e/strata-split-2-sm86', args: ['--native', cfg.args[cfg.args.indexOf('--native') + 1], '--batch', String(lanes)], drafting: 'mtp', split_fallback: { exe: cfg.exe, args: cfg.args, parallel: cfg.parallel }, split_engine_note: 'Using the all-cards split engine on 2 cards.' }));
97  return { ok: true, split: true, line: 'Using the all-cards split engine on 2 cards.', warn: false, reasons: [], cards: 2, written: options.outPath };
98};
99/** Before the layer is fetched Control says split + mtp_needed; after it, split with the layer here. */
100const splitPlan = (_options, state) => state.installs === 0 ? { ...SPLIT_PLAN, mtp_needed: true, mtp_gb: 5.2 } : { ...SPLIT_PLAN, mtp_needed: false, mtp_gb: 0 };
101
102
103const TUNED_PLAN = { ok: true, split: false, choice: 'dflash2', drafter: 'dflash2', needed: true, tuned_needed: true, tuned: true, gb: 0.34, drafter_gb: 0.34, mtp_needed: false, mtp_gb: 0, line: 'Drafting: DFlash2', serves: true };
104const READY_PLAN = { ...TUNED_PLAN, needed: false, tuned_needed: false, gb: 0 };
105const planAfterFetch = (_o, state) => (state.fetchCalls.length ? READY_PLAN : TUNED_PLAN);
106
107test('a plain load fetches the tuned drafter with the 12 hour rule, then plans again', async () => {
108  const f = fixture({ plan: planAfterFetch });
109  try {
110    await f.native.refresh(true);
111    const job = await finish(f.native, load(f).id);
112    assert.equal(job.state, 'done', job.error);
113    assert.equal(f.state.fetchCalls.length, 1);
114    assert.equal(f.state.fetchCalls[0].mode, 'auto');
115    assert.equal(f.state.fetchCalls[0].throttle, true, 'nobody asked for it: the Terminal 12 hour rule');
116    assert.ok(f.state.planCalls.length >= 2, 'planned again after the fetch');
117  } finally { await f.native.close(); f.cleanup(); }
118});
119
120/* CLEAN-1A (owner 11-07): the plain Load follows Auto everywhere. Where Auto's drafter is the standard DFlash2 pack (Intel Arc, UD-Q4_K_XL on NVIDIA 72 GB / 12 GB and the Spark), Control says `needed` without `tuned_needed`; the app fetches it just the same, asking Control. */
121const STOCK_PLAN = { ...TUNED_PLAN, tuned_needed: false, tuned: false, gb: 1.2, drafter_gb: 1.2 };
122const stockAfterFetch = (_o, state) => (state.fetchCalls.length ? { ...STOCK_PLAN, needed: false, gb: 0 } : STOCK_PLAN);
123
124test('a plain load fetches the standard DFlash2 drafter too when that is what Auto runs', async () => {
125  const f = fixture({ plan: stockAfterFetch });
126  try {
127    await f.native.refresh(true);
128    const job = await finish(f.native, load(f).id);
129    assert.equal(job.state, 'done', job.error);
130    assert.equal(f.state.fetchCalls.length, 1);
131    assert.equal(f.state.fetchCalls[0].mode, 'auto');
132    assert.equal(f.state.fetchCalls[0].throttle, true);
133  } finally { await f.native.close(); f.cleanup(); }
134});
135
136test('a plain load fetches nothing when Auto needs no download', async () => {
137  const f = fixture({ plan: () => ({ ...STOCK_PLAN, needed: false, gb: 0 }) });
138  try {
139    await f.native.refresh(true);
140    const job = await finish(f.native, load(f).id);
141    assert.equal(job.state, 'done', job.error);
142    assert.equal(f.state.fetchCalls.length, 0);
143  } finally { await f.native.close(); f.cleanup(); }
144});
145
146test('the Models screen own Load keeps its un-throttled fetch and does not fetch twice', async () => {
147  const f = fixture({ plan: planAfterFetch });
148  try {
149    await f.native.refresh(true);
150    const job = await finish(f.native, load(f, { values: { drafting: 'auto' } }).id);
151    assert.equal(job.state, 'done', job.error);
152    assert.equal(f.state.fetchCalls.length, 1);
153    assert.ok(f.state.fetchCalls[0].throttle !== true);
154  } finally { await f.native.close(); f.cleanup(); }
155});
156
157test('a drafter the person saved wins: MTP, off and DFlash2 are never fetched by a plain load', async () => {
158  for (const drafting of ['mtp', 'off', 'dflash2']) {
159    const f = fixture({ plan: TUNED_PLAN, config: { drafting } });
160    try {
161      await f.native.refresh(true);
162      const job = await finish(f.native, load(f).id);
163      assert.equal(job.state, 'done', job.error);
164      assert.equal(f.state.fetchCalls.length, 0, drafting);
165    } finally { await f.native.close(); f.cleanup(); }
166  }
167});
168
169test('nothing needed (the tuned drafter is here, or Control says MTP): a plain load fetches nothing', async () => {
170  const f = fixture({ plan: READY_PLAN });
171  try {
172    await f.native.refresh(true);
173    const job = await finish(f.native, load(f).id);
174    assert.equal(job.state, 'done', job.error);
175    assert.equal(f.state.fetchCalls.length, 0);
176  } finally { await f.native.close(); f.cleanup(); }
177});
178
179test('the feed has nothing (skipped): the load goes on exactly as before, no note', async () => {
180  const f = fixture({ plan: TUNED_PLAN, fetchResult: { ok: true, event: 'result', pack: null, skipped: true } });
181  try {
182    await f.native.refresh(true);
183    const job = await finish(f.native, load(f).id);
184    assert.equal(job.state, 'done', job.error);
185    assert.equal(f.state.fetchCalls.length, 1);
186    assert.ok(!job.drafterNote);
187  } finally { await f.native.close(); f.cleanup(); }
188});
189
190test('a fetch that fails for a real reason never stops the load and the job says why', async () => {
191  const f = fixture({ plan: TUNED_PLAN, fetchResult: new Error('The tuned DFlash2 drafter did not pass the safety check, so it was deleted.') });
192  try {
193    await f.native.refresh(true);
194    const job = await finish(f.native, load(f).id);
195    assert.equal(job.state, 'done', job.error);
196    assert.match(job.drafterNote ?? '', /safety check/);
197  } finally { await f.native.close(); f.cleanup(); }
198});
199
200test('a tuning run fetches it first, and not for a saved MTP', async () => {
201  for (const [drafting, calls] of [[undefined, 1], ['mtp', 0]]) {
202    const f = fixture({ plan: TUNED_PLAN, config: drafting ? { drafting } : {} });
203    try {
204      await f.native.refresh(true);
205      const id = f.native.operation('autotune', { model: 'ud_q4_k_xl' }).id;
206      await finish(f.native, id);
207      assert.equal(f.state.fetchCalls.length, calls, String(drafting));
208      if (calls) assert.equal(f.state.fetchCalls[0].throttle, true);
209    } finally { await f.native.close(); f.cleanup(); }
210  }
211});
212
213test('the install plan asks Control about this model and lists the tuned size, and says nothing for MTP', async () => {
214  const f = fixture({ plan: (o) => (o.mode === 'mtp' ? { ...READY_PLAN, choice: 'mtp', drafter: 'mtp' } : TUNED_PLAN) });
215  try {
216    await f.native.refresh(true);
217    const got = await f.native.plan({ family: 'qwen', model: 'UD-Q4_K_XL', drafting: 'auto' });
218    assert.equal(f.state.planCalls.find(c => c.model)?.model, 'UD-Q4_K_XL');
219    assert.equal(got.drafting.gb, 0.34);
220    assert.equal(got.drafting.tuned, true);
221    const none = await f.native.plan({ family: 'qwen', model: 'UD-Q4_K_XL', drafting: 'mtp' });
222    assert.equal(none.drafting, undefined, 'MTP chosen: no drafter is listed');
223  } finally { await f.native.close(); f.cleanup(); }
224});
225
226test('the Settings hint keeps its wording and changes only the number', async () => {
227  const { draftingHint, NATIVE_FIELDS } = await import('../server/native-settings.mjs');
228  assert.equal(NATIVE_FIELDS.find(x => x.id === 'drafting').hint, draftingHint(1.2));
229  assert.equal(draftingHint(0.34), draftingHint(1.2).replace('1.2 GB', '0.34 GB'));
230  assert.match(draftingHint(0.52), /DFlash2 downloads a 0\.52 GB drafter once, the MTP its draft layer once\./);
231  assert.equal(draftingHint(0), draftingHint(1.2), 'no number from Control: the generic hint');
232  const f = fixture({ plan: TUNED_PLAN });
233  try {
234    await f.native.refresh(true);
235    assert.deepEqual(await f.native.settingsHints('ud_q4_k_xl'), { drafting: draftingHint(0.34) });
236    assert.equal(f.state.planCalls.at(-1).mode, 'dflash2');
237  } finally { await f.native.close(); f.cleanup(); }
238});
239
240test('control passes the model, the family and --throttle to Control and not --model beside a run config', async () => {
241  const calls = [];
242  const control = createControl({ control: { dir: 'C:/c', python: 'py', cli: 'strata.py' }, run: async (args) => { calls.push(args); return { code: 0, json: { ok: true }, text: '', stderr: '' }; } });
243  await control.draftingPlan({ mode: 'auto', family: 'unsloth', model: 'UD-Q4_K_XL', dataDir: 'C:/d' });
244  assert.deepEqual(calls[0], ['drafting', 'plan', '--mode', 'auto', '--family', 'unsloth', '--model', 'UD-Q4_K_XL', '--data-dir', 'C:/d', '--output', 'json']);
245  await control.draftingPlan({ configPath: 'C:/w/c.json', model: 'UD-Q4_K_XL' });
246  assert.ok(!calls[1].includes('--model'));
247  await control.draftingFetch({ configPath: 'C:/w/c.json', mode: 'auto', throttle: true });
248  assert.deepEqual(calls[2], ['drafting', 'fetch', '--config', 'C:/w/c.json', '--mode', 'auto', '--if-needed', '--throttle', '--output', 'jsonl']);
249});
250
251test('a restart of the stopped models fetches it before the start, and so does every path through the one helper', async () => {
252  const { readFileSync: read } = await import('node:fs');
253  const source = read(new URL('../server/native-control.mjs', import.meta.url), 'utf8');
254  const restart = source.slice(source.indexOf('async function restartStopped'), source.indexOf('function dismissRestart'));
255  assert.match(restart, /await autoDrafterFor\(job,instance\.model,[^)]*\);[\s\S]*await control\.start\(instance\.profile/, 'before the engine starts again');
256  const tune = source.slice(source.indexOf('async function autotune'), source.indexOf('function operation'));
257  assert.match(tune, /await autoDrafterFor\(job,args\.model,/);
258  assert.match(source, /if\(args\.values\?\.drafting===undefined&&drafts\?\.needed===true\)\{const got=await fetchAutoDrafter\(/, 'a plain load');
259  assert.match(source, /!autoChoice\(readJson\(configFile\)\.drafting\)\)return false/, 'a saved choice wins');
260});