From af9b832fd39e6a5c93c44fb5fe5f98e97817fc29 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 9 Nov 2026 22:49:42 +0100 Subject: [PATCH] App: the setup prepares the drafter Control's Auto picks for this card; the first load after it fetches a missing MTP layer The install used the host's own rule (DFlash2 wherever it is served), so on a card where Auto means the MTP (a 12 GB CUDA card streaming IQ3_S, gfx1201) setup skipped the MTP layer and the first load ran undrafted (QAGUI 0213). One decider now: Control's drafting plan, at the install and the load; the load right after a setup fetches a still-missing layer. Tests pin that the setup, the first load and the start agree on 12 GB (MTP) and 24 GB (DFlash2). --- apps/host/server/native-control.mjs | 18 ++- apps/host/tests/applin-0214-drafter.test.mjs | 139 ++++++++++++++++++ .../test_app_first_load_drafter_0214.py | 48 ++++++ 3 files changed, 202 insertions(+), 3 deletions(-) create mode 100644 apps/host/tests/applin-0214-drafter.test.mjs create mode 100644 tests/terminal/test_app_first_load_drafter_0214.py diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 4c5b544dd3..5a161e1d77 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -171,10 +171,21 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp async function settingsHints(model){try{if(!packaged||typeof control.draftingPlan!=='function')return {};const {path}=recordFile(model),d=await control.draftingPlan({configPath:path,mode:'dflash2'});return Number(d?.drafter_gb)>0?{drafting:draftingHint(d.drafter_gb)}:{};}catch{return {};}} function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};if(patch.ds_experts!=null&&!dsExpertsSupported(config))throw new Error('The Speed choice needs the newer DeepSeek engine. Update the engine in Settings, then choose it.');for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if('vram_reserve_mib' in patch){const base=captureUserArgs(next);const mine=setUserFlag(base,'--vram-reserve-mib',patch.vram_reserve_mib);if(mine.length)next[USER_KEY]=mine;else delete next[USER_KEY];next.args=mine.length&&patch.vram_reserve_mib!==null?mergeUserArgs(next.args??[],mine):setUserFlag(next.args??[],'--vram-reserve-mib',null);delete next.ui_reserve_applied;if(Array.isArray(next.args_written))next.args_written=[...next.args];}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);} function previousEngine(){if(packaged)return !!snapshot.engine?.previous;try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}} - async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);const result=await tool('strata_install',installArgs(args,false)); + async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);args=await controlDrafter(args);const result=await tool('strata_install',installArgs(args,false)); /* A chosen drafter that is not on this computer yet is part of the download: its size is listed beside the model's (Control decides; nothing is fetched here). */ const choice=args.drafting??(dflash2Served===true?'auto':undefined);if(packaged&&typeof choice==='string'&&typeof control.draftingPlan==='function'){try{const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model),here=snapshot.installed?.models?.find(m=>m.model===size?.id);const d=await control.draftingPlan({mode:choice,family:args.family??null,model:args.model??null,dataDir:here?.runDataFolder??snapshot.installed?.data_folder??null,...(unloadsRunning(args)?{unloading:true}:{})});if(d.needed||d.mtp_needed)return {...result,drafting:{needed:true,drafter:d.needed?'dflash2':'mtp',gb:d.needed?d.gb:d.mtp_gb,line:d.line,...(d.needed&&d.tuned===true?{tuned:true}:{})}};}catch{/* the model plan still stands */}} return result;} + /* Which drafter the install prepares: Control's plan decides, as at the load (strata_control/drafting.py, the per-card Auto). The host's own rule said DFlash2 wherever it is + served, so a card where Auto means the MTP (a 12 GB CUDA card streaming IQ3_S, an RX 9070) was set up without the MTP layer and its first load ran undrafted (QAGUI 0213). + No plan (an older Control, an error): the old rule (installArgs). A drafter named by the caller (the MTP layer fetch) is kept. */ + async function controlDrafter(args){ + if(!packaged||args.drafter!==undefined||typeof control.draftingPlan!=='function')return args; + const choice=args.drafting??(dflash2Served===true?'auto':undefined);if(typeof choice!=='string')return args; + try{const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model),here=snapshot.installed?.models?.find(m=>m.model===size?.id); + const d=await control.draftingPlan({mode:choice,family:args.family??null,model:args.model??null,dataDir:here?.runDataFolder??snapshot.installed?.data_folder??null}); + if(d?.choice==='mtp'||d?.choice==='dflash2')return {...args,drafter:d.choice};}catch{/* the old rule below */} + return args; + } /* The folder the person picked in the first-run chooser can be the one that holds their GGUF files (or a folder inside it). It is theirs, not a Strata data folder: packs are never made in it, and a Strata folder around it (/models/) is used instead (#3507, #3424). */ function ownFilesDataFolder(candidate,args){if(!candidate||args.data_dir!==undefined||!args.gguf_dir)return candidate;const same=(a,b)=>{const x=resolve(a),y=resolve(b);return process.platform==='win32'?x.toLowerCase()===y.toLowerCase():x===y;};const inside=(a,b)=>{const rel=relative(resolve(b),resolve(a));return rel===''||(!!rel&&!rel.startsWith('..')&&!isAbsolute(rel));};if(!same(candidate,args.gguf_dir)&&!inside(candidate,args.gguf_dir))return candidate;const models=dirname(resolve(args.gguf_dir)),top=dirname(models);return basename(models).toLowerCase()==='models'&&/strata/i.test(basename(top))?top:undefined;} function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port','gguf_dir','drafter'];/* One drafter per run: when the choice means DFlash2 the installer does not fetch the MTP layer's ~5 GB (the drafter is fetched by the load); choosing the MTP later fetches the layer once. */if(args.drafter===undefined&&args.drafting!==undefined||args.drafter===undefined&&dflash2Served===true){const d=resolveDrafter(args.drafting,args.family,dflash2Served,dflash2Split);if(d==='dflash2')args={...args,drafter:'dflash2'};}const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);/* A model adopted from the person's own GGUF folder reports that folder's parent as its data folder: it is theirs, not Strata's, so a second preparation never uses it for the packs. */if(args.gguf_dir===undefined&&existing?.ownGgufDir)args={...args,gguf_dir:existing.ownGgufDir};/* A model that is installed keeps working in the data folder its own run config names (where its pack and draft layer are), whether its files are under it or in the person's own folder: that is never changed or written to the settings from here. Only a folder taken from the app's models folder is the person's choice, and the one the installer is told about. */const own=args.data_dir===undefined?existing?.runDataFolder:undefined;const data=own??nativeDataDirectory(ownFilesDataFolder(args.data_dir??(args.gguf_dir?undefined:existing?.dataFolder)??preferences.downloadDirectory??modelsDirectory?.(),args));if(data&&packaged&&!args.data_dir&&!own)rememberDataFolder(controlSettingsFile(),data);return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),/* One card is "gpu", never "gpus" (the installer wants two or more there: "Gpus='0' is not valid", #3203). */...(/^\d{1,2}$/.test(String(args.gpus??''))?{gpu:Number(args.gpus),gpus:undefined}:{}),/* Picture reading is only downloaded when it was asked for (Read pictures); the default stays the smaller download. */...(packaged&&args.vision===undefined&&args.family!=='deepseek41'?{vision:'no'}:{}),confirm};} @@ -189,6 +200,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel requests before preparing model files.'); for(const id of [...instances.keys()])await unload(id); if(job.state!=='running')return; + args=await controlDrafter(args);if(job.state!=='running')return; let result=await tool('strata_install',installArgs(args,true)); /* The engine comes with the model: the same job makes sure this PC has a usable engine (none installed, or a newer compatible one in the signed feed) through Control's component updater, and shows it in the job's own progress (install.engine, install.parts, @@ -213,7 +225,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp if(note)return {...finalResult,summary:note}; /* A context the person picked is kept with a marker (ui_context_chosen), so only an old saved 32K, which has no marker, is read as the old default. */ if(args.contextChosen===true){try{const id=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;rememberSetting(record(id).path,'ui_context_chosen',true);}catch{/* the install itself is done */}} - if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision,...(args.visionUnavailable===true?{visionUnavailable:true}:{}),...(typeof args.drafting==='string'?{values:{drafting:args.drafting}}:{})});} + if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,firstLoad:true,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision,...(args.visionUnavailable===true?{visionUnavailable:true}:{}),...(typeof args.drafting==='string'?{values:{drafting:args.drafting}}:{})});} return finalResult; } } @@ -455,7 +467,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} let picturesNote=null;{const got=await ensurePictures(job,args,configFile,config,{missing:entry.picturesMissing===true});if(job.state!=='running')return;config=got.config;args=got.args;picturesNote=got.note;} /* One drafter per run (strata_control/drafting.py): switching to the MTP on a model set up for DFlash2 fetches the layer once, here; DFlash2 is fetched below. */ let drafts=await draftPlan(args,configFile),noSplit=false; - if(drafts?.mtp_needed===true&&(args.values?.drafting!==undefined||drafts.split===true&&(config.drafting==null||String(config.drafting).toLowerCase()==='auto'))){/* the Models screen's own Load carries the choice; a plain Auto load fetches the layer too when Control says the all-cards split engine will take the start (it runs the MTP and nothing else): the same as the Terminal */await installMtpLayer(job,args,config);if(job.state!=='running')return;await refresh(true);config=checkedSettingsConfig(readFileSync(recordFile(args.model).path,'utf8'));drafts=await draftPlan(args,configFile); + if(drafts?.mtp_needed===true&&(args.values?.drafting!==undefined||(drafts.split===true||args.firstLoad===true)&&(config.drafting==null||String(config.drafting).toLowerCase()==='auto'))){/* firstLoad: the load right after a setup (Prepare and load), whose plan listed the layer: Auto meaning the MTP on this card fetches it, as the Models screen does (QAGUI 0213) *//* the Models screen's own Load carries the choice; a plain Auto load fetches the layer too when Control says the all-cards split engine will take the start (it runs the MTP and nothing else): the same as the Terminal */await installMtpLayer(job,args,config);if(job.state!=='running')return;await refresh(true);config=checkedSettingsConfig(readFileSync(recordFile(args.model).path,'utf8'));drafts=await draftPlan(args,configFile); /* The draft layer for the split could not be had (no internet, disk): the load goes on as the 0.2.10 app did, the normal layer split with the plan DFlash2's again (the Models screen's own Load fetches that drafter below). One plain line says so. */ if(drafts?.split===true&&drafts.mtp_needed===true){noSplit=true;job.drafterNote=job.drafterNote??'The MTP drafter could not be downloaded.';job.summary='Loading the model…';emit();drafts=await draftPlan(args,configFile,{noSplit:true});}} /* A plain load (the Models screen's own Load carries its choice and fetches below): Auto on a set that has the tuned drafter fetches it now, so the start uses it. Not on this computer and not reachable: the MTP or the stock drafter runs as before. */ diff --git a/apps/host/tests/applin-0214-drafter.test.mjs b/apps/host/tests/applin-0214-drafter.test.mjs new file mode 100644 index 0000000000..1bbc9de6bd --- /dev/null +++ b/apps/host/tests/applin-0214-drafter.test.mjs @@ -0,0 +1,139 @@ +/** + * Lane APP-LIN (0.2.14) item 7: on a card where Control's Auto means the MTP (here a 12 GB CUDA card, CLASS_DEFAULTS "streaming"), the app's setup prepares the MTP + * layer and the first load after it drafts. One decider: the install asks Control's `drafting plan` (strata_control/drafting.py), not the host's own rule. + * The fixture is split-app.test.mjs's (fake Control, fake installer over MCP) with one 12 GB card. Generated by the lane's script; edit freely. + */ +import './helpers/isolate-profile.mjs'; // a test run never writes the owner's real Strata profile +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join, dirname } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createNativeControl } from '../server/native-control.mjs'; + +function fixture({ plan, split = null, installFails = false, startFails = 0, metrics = {}, config = {} } = {}) { + const root = mkdtempSync(join(tmpdir(), 'strata-applin-drafter-')); + const install = join(root, 'install'), data = join(root, 'host-data'), home = join(root, 'home'), modelsDir = join(home, 'models'); + for (const d of [install, data, modelsDir]) mkdirSync(d, { recursive: true }); + const earlier = process.env.STRATA_INSTALL_DIR; + process.env.STRATA_INSTALL_DIR = install; + const dataFolder = join(root, 'Strata-data'), modelFolder = join(dataFolder, 'models', 'UD-Q4_K_XL'); + const gguf = join(modelFolder, 'Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00002.gguf'); + mkdirSync(modelFolder, { recursive: true }); + writeFileSync(gguf, 'GGUF'); writeFileSync(gguf.replace('00001', '00002'), 'GGUF'); + const pack = join(dataFolder, 'packs', 'ud_q4_k_xl'), mtp = join(dataFolder, 'mtp', 'rt'); + mkdirSync(join(pack, 'tokenizer'), { recursive: true }); + writeFileSync(join(pack, 'native_experts.txt'), 'x'); + const configPath = join(install, 'strata-ud_q4_k_xl.json'); + const args = ['--pack', pack, '--native', gguf, '--ple-gguf', gguf.replace('00001', '00002'), '--mtp', mtp, '--max-context', '131072', '--kv', 'int8']; + 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, ...config })); + writeFileSync(process.env.STRATA_SETTINGS_FILE, JSON.stringify({ data_dir: join(root, 'host-owned', 'Strata-data'), data_dir_at: 1700000000 })); + const state = { installs: 0, planCalls: [], fetchCalls: [], splitCalls: [], saved: [], starts: 0, rpc: [] }; + const control = { + control: { dir: join(root, 'control'), python: join(root, 'control', 'python', 'python') }, version: '0.2.10', + async installedModels() { + 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: [] }] }; + }, + 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') } }; }, + async draftingPlan(options) { state.planCalls.push(options); return typeof plan === 'function' ? plan(options, state) : plan; }, + async draftingFetch(options) { state.fetchCalls.push(options); return { ok: true, event: 'result', pack: null, skipped: false }; }, + async splitEngine(options) { + state.splitCalls.push({ ...options, input: JSON.parse(readFileSync(options.configPath, 'utf8')) }); + if (!split) return { ok: true, split: false, line: '', warn: false, reasons: [], written: null }; + return split(options, state); + }, + async saveProfile(name, path) { state.saved.push(JSON.parse(readFileSync(path, 'utf8'))); return {}; }, + async start() { state.starts += 1; if (state.starts <= startFails) throw new Error('The engine stopped: out of memory'); return { ok: true, state: 'ready' }; }, + async stop() { return { ok: true }; }, + }; + const catalog = { families: [{ family: 'qwen', title: 'Qwen3.8-Flash-Next', about: 'x', images: false, experimental: false, sizes: [ + { 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 }] }], + contexts: [32768, 131072], recommendation: { family: 'qwen', model: 'UD-Q4_K_XL', context: 131072 }, context_note: '' }; + const hardware = { ram_gb: 256, cpu: { name: 'cpu', cores: 32 }, engine_vendor: 'nvidia', gpus: [{ index: 0, name: 'NVIDIA GeForce RTX 3060', vendor: 'nvidia', vram_gb: 12, arch: 86, usable: true }] }; + const spawnProcess = (command, argv) => { + 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(' ')); + const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.exitCode = null; + child.kill = () => { child.exitCode = 0; queueMicrotask(() => child.emit('exit', 0)); return true; }; + child.stdin = { write(line) { + const message = JSON.parse(line); if (!message.id) return; + if (message.method === 'tools/call') state.rpc.push(message.params); + let result; + if (message.method === 'initialize') result = { protocolVersion: '2024-11-05' }; + else if (message.method === 'tools/list') result = { tools: ['strata_models', 'strata_status', 'strata_install', 'strata_remove'].map(name => ({ name })) }; + else if (message.params.name === 'strata_models') result = { structuredContent: catalog }; + else if (message.params.name === 'strata_status') result = { structuredContent: { hardware, recommendation: catalog.recommendation, install: null, running: [], summary: 'x' } }; + else if (Object.keys(message.params.arguments ?? {}).length === 0) result = { structuredContent: { summary: 'Install finished', install: { running: false, exit_code: 0 } } }; + else if (message.params.arguments?.confirm) { + if (installFails) result = { isError: true, structuredContent: { error: 'The download did not finish.' } }; + 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' } } }; } + } else result = { structuredContent: { summary: 'Plan', plan: { title: 'Qwen3.8-Flash-Next UD-Q4_K_XL', download_gb: 5.2, disk_short: null } } }; + queueMicrotask(() => child.stdout.emit('data', Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + String.fromCharCode(10)))); + } }; + return child; + }; + const fetcher = async url => String(url).endsWith('/metrics') ? Response.json({ engine: metrics }) : Response.json({ status: 'ok' }); + const native = createNativeControl({ control, directory: data, spawnProcess, fetcher, requests: () => [], modelsDirectory: () => modelsDir, hardwareProbe: () => [{ index: 0, vram_gb: 12 }] }); + return { native, state, root, gguf, modelFolder, mtp, configPath, args, + cleanup: () => { if (earlier === undefined) delete process.env.STRATA_INSTALL_DIR; else process.env.STRATA_INSTALL_DIR = earlier; rmSync(root, { recursive: true, force: true }); } }; +} +const 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'); }; +const load = (f, args = {}) => f.native.operation('load', { model: 'ud_q4_k_xl', ...args }); + +/** Control's plan: at the install (no run config yet) `atInstall`; at the load the MTP layer is missing until `layerAfter` installs ran. `serves`: DFlash2 is served here. */ +const planner = ({ atInstall, layerAfter = 1 }) => (options, state) => { + if (!options.configPath && options.family === undefined) return { ok: true, serves: true, choice: 'dflash2', split: false }; // the start-up probe (mode auto) + if (!options.configPath) { if (atInstall instanceof Error) throw atInstall; return { ok: true, serves: true, split: false, needed: false, mtp_needed: false, gb: 0, ...atInstall }; } + const missing = state.installs < layerAfter; + return { ok: true, serves: true, split: false, choice: 'mtp', drafter: missing ? 'off' : 'mtp', needed: false, gb: 0, mtp_needed: missing, mtp_gb: missing ? 5.2 : 0, line: 'Drafting: MTP' }; +}; +const installs = f => f.state.rpc.filter(p => p.name === 'strata_install' && p.arguments?.confirm === true); +const prepareAndLoad = f => f.native.operation('install', { family: 'qwen', model: 'UD_Q4_K_XL', gguf_dir: f.modelFolder, loadAfter: true }); + +test('the install takes the drafter Control\'s Auto picks for this card: the MTP on a 12 GB streaming card, so the layer comes with the model', async () => { + const f = fixture({ plan: planner({ atInstall: { choice: 'mtp', drafter: 'mtp' } }) }); + try { + await f.native.refresh(true); + const job = await finish(f.native, prepareAndLoad(f).id); + assert.equal(job.state, 'done', job.error); + assert.equal(installs(f).length, 1, 'one install: the layer came with it, the load fetched nothing more'); + assert.equal(installs(f)[0].arguments.drafter, 'mtp', 'not the host\'s DFlash2 guess'); + const asked = f.state.planCalls.find(c => !c.configPath && c.family === 'qwen'); + assert.equal(asked.mode, 'auto'); + assert.equal(asked.model, 'UD_Q4_K_XL'); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('where Control\'s Auto means DFlash2, the install skips the MTP layer as before', async () => { + const f = fixture({ plan: planner({ atInstall: { choice: 'dflash2', drafter: 'dflash2' }, layerAfter: 0 }) }); + try { + await f.native.refresh(true); + const job = await finish(f.native, prepareAndLoad(f).id); + assert.equal(job.state, 'done', job.error); + assert.equal(installs(f)[0].arguments.drafter, 'dflash2'); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('the first load after a setup fetches a missing MTP layer (an older Control without the plan at install time), so it does not run undrafted', async () => { + const f = fixture({ plan: planner({ atInstall: new Error('no plan'), layerAfter: 2 }) }); + try { + await f.native.refresh(true); + const job = await finish(f.native, prepareAndLoad(f).id); + assert.equal(job.state, 'done', job.error); + const all = installs(f); + assert.equal(all.length, 2, 'the setup, then the layer'); + assert.equal(all[0].arguments.drafter, 'dflash2', 'no plan: the old host rule'); + assert.equal(all[1].arguments.drafter, 'mtp'); + assert.equal(all[1].arguments.gguf_dir, dirname(f.gguf)); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('a plain load that is not the first after a setup still downloads nothing', async () => { + const f = fixture({ plan: planner({ atInstall: { choice: 'mtp' }, layerAfter: 5 }) }); + try { + await f.native.refresh(true); + const job = await finish(f.native, load(f).id); + assert.equal(job.state, 'done', job.error); + assert.equal(installs(f).length, 0); + } finally { await f.native.close(); f.cleanup(); } +}); diff --git a/tests/terminal/test_app_first_load_drafter_0214.py b/tests/terminal/test_app_first_load_drafter_0214.py new file mode 100644 index 0000000000..ac5f41f230 --- /dev/null +++ b/tests/terminal/test_app_first_load_drafter_0214.py @@ -0,0 +1,48 @@ +"""The app's setup, the app's first load and the Terminal's start pick the same drafter for Auto (lane APP-LIN 0.2.14 item 7). + +Before: the app prepared every DFlash2-capable model for DFlash2 (the host's own rule), so on a card where Control's Auto means the MTP the setup skipped the MTP layer and the +first load ran undrafted. Now the app asks `strata drafting plan` at the install (no run config yet: --family/--model) and at the load (--config). This pins that both answers +equal the start's own decision (drafting.apply, what serve/server.py runs) on the card classes where they differ: a 12 GB CUDA card streaming IQ3_S (MTP) and a 24 GB one (DFlash2). +""" +import argparse +import json +from pathlib import Path + +import pytest + +from strata_cli import drafting_cmd +from strata_control import drafting + + +def _plan(capsys, **kw) -> dict: + a = argparse.Namespace(drafting_command="plan", data_dir=None, config=None, family=None, model=None, mode=None, no_split=False, + engines_unloading=False, output="json") + for k, v in kw.items(): + setattr(a, k, v) + assert drafting_cmd.run(a) == 0 + return json.loads(capsys.readouterr().out.strip().splitlines()[-1]) + + +@pytest.mark.parametrize("vram_mib,expected", [(12288, "mtp"), (24576, "dflash2")]) +def test_setup_first_load_and_start_agree(tmp_path, monkeypatch, capsys, vram_mib, expected): + monkeypatch.setattr(drafting_cmd, "_hardware", lambda: ("cuda", ["sm_86"])) + monkeypatch.setattr(drafting, "card_vram_mib", lambda *a, **k: float(vram_mib)) + monkeypatch.setattr(drafting_cmd, "_split_expected", lambda *a, **k: False) + monkeypatch.setattr(drafting_cmd, "_installed_dflash2_configs", lambda a: []) + data = tmp_path / "data" + (data / "mtp" / "rt").mkdir(parents=True) + # 1. the app's setup: no run config yet + at_install = _plan(capsys, family="qwen", model="IQ3_S", mode="auto", data_dir=str(data)) + assert at_install["choice"] == expected + # 2. the app's first load: the run config setup wrote (Auto: no "drafting" key) + mtp = data / "mtp" / "rt" + (mtp / "experts.bin").write_bytes(b"x" * 2048) + cfg = {"model_name": "qwen3.8-flash-next-iq3_s", "backend": "cuda", + "args": ["--pack", str(data / "packs" / "iq3_s"), "--native", "/m/IQ3_S-00001-of-00002.gguf", "--mtp", str(mtp), "--max-context", "131072"]} + path = tmp_path / "strata-iq3_s.json" + path.write_text(json.dumps(cfg), encoding="utf-8") + at_load = _plan(capsys, config=str(path)) + assert at_load["choice"] == expected + # 3. the start (serve/server.py runs drafting.apply on the same config): the same choice + want = drafting.choice_of("auto", model_name=cfg["model_name"], backend="cuda", archs=["sm_86"], args=cfg["args"], vram_mib=float(vram_mib)) + assert want == expected