okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
93a1e18bc
main
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= {} } = {}) { 25const root = mkdtempSync ( join ( tmpdir (), 'strata-splitapp-test-' )); 26const install = join ( root , 'install' ), data = join ( root , 'host-data' ), home = join ( root , 'home' ), modelsDir = join ( home , 'models' ); 27for ( const d of [ install , data , modelsDir ]) mkdirSync ( d , { recursive :true }); 28const earlier = process . env . STRATA_INSTALL_DIR ; 29process . env . STRATA_INSTALL_DIR = install ; 30const dataFolder = join ( root , 'Strata-data' ), modelFolder = join ( dataFolder , 'models' , 'UD-Q4_K_XL' ); 31const gguf = join ( modelFolder , 'Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00002.gguf' ); 32mkdirSync ( modelFolder , { recursive :true }); 33writeFileSync ( gguf , 'GGUF' ); writeFileSync ( gguf . replace ( '00001' , '00002' ), 'GGUF' ); 34const pack = join ( dataFolder , 'packs' , 'ud_q4_k_xl' ), mtp = join ( dataFolder , 'mtp' , 'rt' ); 35mkdirSync ( join ( pack , 'tokenizer' ), { recursive :true }); 36writeFileSync ( join ( pack , 'native_experts.txt' ), 'x' ); 37const configPath = join ( install , 'strata-ud_q4_k_xl.json' ); 38const args = [ '--pack' , pack , '--native' , gguf , '--ple-gguf' , gguf . replace ( '00001' , '00002' ), '--mtp' , mtp , '--max-context' , '131072' , '--kv' , 'int8' ]; 39writeFileSync ( 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 })); 40writeFileSync ( process . env . STRATA_SETTINGS_FILE , JSON . stringify ({ data_dir :join ( root , 'host-owned' , 'Strata-data' ), data_dir_at :1700000000 })); 41const state = { installs :0 , planCalls :[], fetchCalls :[], splitCalls :[], saved :[], starts :0 , rpc :[] }; 42const control = { 43control :{ dir :join ( root , 'control' ), python :join ( root , 'control' , 'python' , 'python' ) }, version :'0.2.10' , 44async installedModels () { 45return { 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}, 47async 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' ) } }; }, 48async draftingPlan ( options ) { state . planCalls . push ( options ); return typeof plan === 'function' ?plan ( options , state ) :plan ; }, 49async draftingFetch ( options ) { state . fetchCalls . push ( options ); if ( fetchResult instanceof Error ) throw fetchResult ; return fetchResult ; }, 50async splitEngine ( options ) { 51state . splitCalls . push ({ ...options , input :JSON . parse ( readFileSync ( options . configPath , 'utf8' )) }); 52if ( ! split ) return { ok :true , split :false , line :'' , warn :false , reasons :[], written :null }; 53return split ( options , state ); 54}, 55async saveProfile ( name , path ) { state . saved . push ( JSON . parse ( readFileSync ( path , 'utf8' ))); return {}; }, 56async start () { state . starts += 1 ; if ( state . starts <= startFails ) throw new Error ( 'The engine stopped: out of memory' ); return { ok :true , state :'ready' }; }, 57async stop () { return { ok :true }; }, 58}; 59const 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 }] }], 61contexts :[ 32768 , 131072 ], recommendation :{ family :'qwen' , model :'UD-Q4_K_XL' , context :131072 }, context_note :'' }; 62const 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 })) }; 63const spawnProcess = ( command , argv ) => { 64if ( ! String ( argv [ 0 ]). endsWith ( 'strata_mcp.py' )) throw new Error ( 'no process but the installer may be started in packaged mode: ' + command + ' ' + argv . join ( ' ' )); 65const child = new EventEmitter (); child . stdout = new EventEmitter (); child . stderr = new EventEmitter (); child . exitCode = null ; 66child . kill = () => { child . exitCode = 0 ; queueMicrotask (() => child . emit ( 'exit' , 0 )); return true ; }; 67child . stdin = { write ( line ) { 68const message = JSON . parse ( line ); if ( ! message . id ) return ; 69if ( message . method === 'tools/call' ) state . rpc . push ( message . params ); 70let result ; 71if ( message . method === 'initialize' ) result = { protocolVersion :'2024-11-05' }; 72else if ( message . method === 'tools/list' ) result = { tools :[ 'strata_models' , 'strata_status' , 'strata_install' , 'strata_remove' ]. map ( name => ({ name})) }; 73else if ( message . params . name === 'strata_models' ) result = { structuredContent :catalog }; 74else if ( message . params . name === 'strata_status' ) result = { structuredContent :{ hardware, recommendation :catalog . recommendation , install :null , running :[], summary :'x' } }; 75else if ( Object . keys ( message . params . arguments ?? {}). length === 0 ) result = { structuredContent :{ summary :'Install finished' , install :{ running :false , exit_code :0 } } }; 76else if ( message . params . arguments ?. confirm ) { 77if ( installFails ) result = { isError :true , structuredContent :{ error :'The download did not finish.' } }; 78else { 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 } } }; 80queueMicrotask (() => child . stdout . emit ( 'data' , Buffer . from ( JSON . stringify ({ jsonrpc :'2.0' , id :message . id , result}) + String . fromCharCode ( 10 )))); 81} }; 82return child ; 83}; 84const fetcher = async url => String ( url ). endsWith ( '/metrics' ) ?Response . json ({ engine :metrics }) :Response . json ({ status :'ok' }); 85const native = createNativeControl ({ control, directory :data , spawnProcess, fetcher, requests :() => [], modelsDirectory :() => modelsDir , hardwareProbe :() => [ 0 , 1 ]. map ( index => ({ index, vram_gb :48 })) }); 86return { native, state, root, gguf, modelFolder, mtp, configPath, args, 87cleanup :() => { 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 ) => { 94const cfg = JSON . parse ( readFileSync ( options . configPath , 'utf8' )); 95const lanes = Math . min ( 8 , cfg . parallel ?? 6 ); 96writeFileSync ( 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.' })); 97return { 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 () => { 108const f = fixture ({ plan :planAfterFetch }); 109try { 110await f . native . refresh ( true ); 111const job = await finish ( f . native , load ( f ). id ); 112assert . equal ( job . state , 'done' , job . error ); 113assert . equal ( f . state . fetchCalls . length , 1 ); 114assert . equal ( f . state . fetchCalls [ 0 ]. mode , 'auto' ); 115assert . equal ( f . state . fetchCalls [ 0 ]. throttle , true , 'nobody asked for it: the Terminal 12 hour rule' ); 116assert . 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 () => { 125const f = fixture ({ plan :stockAfterFetch }); 126try { 127await f . native . refresh ( true ); 128const job = await finish ( f . native , load ( f ). id ); 129assert . equal ( job . state , 'done' , job . error ); 130assert . equal ( f . state . fetchCalls . length , 1 ); 131assert . equal ( f . state . fetchCalls [ 0 ]. mode , 'auto' ); 132assert . 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 () => { 137const f = fixture ({ plan :() => ({ ...STOCK_PLAN , needed :false , gb :0 }) }); 138try { 139await f . native . refresh ( true ); 140const job = await finish ( f . native , load ( f ). id ); 141assert . equal ( job . state , 'done' , job . error ); 142assert . 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 () => { 147const f = fixture ({ plan :planAfterFetch }); 148try { 149await f . native . refresh ( true ); 150const job = await finish ( f . native , load ( f , { values :{ drafting :'auto' } }). id ); 151assert . equal ( job . state , 'done' , job . error ); 152assert . equal ( f . state . fetchCalls . length , 1 ); 153assert . 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 () => { 158for ( const drafting of [ 'mtp' , 'off' , 'dflash2' ]) { 159const f = fixture ({ plan :TUNED_PLAN , config :{ drafting} }); 160try { 161await f . native . refresh ( true ); 162const job = await finish ( f . native , load ( f ). id ); 163assert . equal ( job . state , 'done' , job . error ); 164assert . 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 () => { 170const f = fixture ({ plan :READY_PLAN }); 171try { 172await f . native . refresh ( true ); 173const job = await finish ( f . native , load ( f ). id ); 174assert . equal ( job . state , 'done' , job . error ); 175assert . 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 () => { 180const f = fixture ({ plan :TUNED_PLAN , fetchResult :{ ok :true , event :'result' , pack :null , skipped :true } }); 181try { 182await f . native . refresh ( true ); 183const job = await finish ( f . native , load ( f ). id ); 184assert . equal ( job . state , 'done' , job . error ); 185assert . equal ( f . state . fetchCalls . length , 1 ); 186assert . 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 () => { 191const f = fixture ({ plan :TUNED_PLAN , fetchResult :new Error ( 'The tuned DFlash2 drafter did not pass the safety check, so it was deleted.' ) }); 192try { 193await f . native . refresh ( true ); 194const job = await finish ( f . native , load ( f ). id ); 195assert . equal ( job . state , 'done' , job . error ); 196assert . 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 () => { 201for ( const [ drafting , calls ] of [[ undefined , 1 ], [ 'mtp' , 0 ]]) { 202const f = fixture ({ plan :TUNED_PLAN , config :drafting ?{ drafting} :{} }); 203try { 204await f . native . refresh ( true ); 205const id = f . native . operation ( 'autotune' , { model :'ud_q4_k_xl' }). id ; 206await finish ( f . native , id ); 207assert . equal ( f . state . fetchCalls . length , calls , String ( drafting )); 208if ( 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 () => { 214const f = fixture ({ plan :( o ) => ( o . mode === 'mtp' ?{ ...READY_PLAN , choice :'mtp' , drafter :'mtp' } :TUNED_PLAN ) }); 215try { 216await f . native . refresh ( true ); 217const got = await f . native . plan ({ family :'qwen' , model :'UD-Q4_K_XL' , drafting :'auto' }); 218assert . equal ( f . state . planCalls . find ( c => c . model )?. model , 'UD-Q4_K_XL' ); 219assert . equal ( got . drafting . gb , 0.34 ); 220assert . equal ( got . drafting . tuned , true ); 221const none = await f . native . plan ({ family :'qwen' , model :'UD-Q4_K_XL' , drafting :'mtp' }); 222assert . 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 () => { 227const { draftingHint, NATIVE_FIELDS } = await import ( '../server/native-settings.mjs' ); 228assert . equal ( NATIVE_FIELDS . find ( x => x . id === 'drafting' ). hint , draftingHint ( 1.2 )); 229assert . equal ( draftingHint ( 0.34 ), draftingHint ( 1.2 ). replace ( '1.2 GB' , '0.34 GB' )); 230assert . match ( draftingHint ( 0.52 ), / DFlash2 downloads a 0\.52 GB drafter once, the MTP its draft layer once\. / ); 231assert . equal ( draftingHint ( 0 ), draftingHint ( 1.2 ), 'no number from Control: the generic hint' ); 232const f = fixture ({ plan :TUNED_PLAN }); 233try { 234await f . native . refresh ( true ); 235assert . deepEqual ( await f . native . settingsHints ( 'ud_q4_k_xl' ), { drafting :draftingHint ( 0.34 ) }); 236assert . 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 () => { 241const calls = []; 242const 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 :'' }; } }); 243await control . draftingPlan ({ mode :'auto' , family :'unsloth' , model :'UD-Q4_K_XL' , dataDir :'C:/d' }); 244assert . deepEqual ( calls [ 0 ], [ 'drafting' , 'plan' , '--mode' , 'auto' , '--family' , 'unsloth' , '--model' , 'UD-Q4_K_XL' , '--data-dir' , 'C:/d' , '--output' , 'json' ]); 245await control . draftingPlan ({ configPath :'C:/w/c.json' , model :'UD-Q4_K_XL' }); 246assert . ok ( ! calls [ 1 ]. includes ( '--model' )); 247await control . draftingFetch ({ configPath :'C:/w/c.json' , mode :'auto' , throttle :true }); 248assert . 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 () => { 252const { readFileSync :read } = await import ( 'node:fs' ); 253const source = read ( new URL ( '../server/native-control.mjs' , import . meta. url ), 'utf8' ); 254const restart = source . slice ( source . indexOf ( 'async function restartStopped' ), source . indexOf ( 'function dismissRestart' )); 255assert . match ( restart , / await autoDrafterFor\(job,instance\.model, [ ^ ) ] * \); [ \s\S ] * await control\.start\(instance\.profile / , 'before the engine starts again' ); 256const tune = source . slice ( source . indexOf ( 'async function autotune' ), source . indexOf ( 'function operation' )); 257assert . match ( tune , / await autoDrafterFor\(job,args\.model, / ); 258assert . match ( source , / if\(args\.values\?\.drafting===undefined&&drafts\?\.needed===true\)\{const got=await fetchAutoDrafter\( / , 'a plain load' ); 259assert . match ( source , / !autoChoice\(readJson\(configFile\)\.drafting\)\)return false / , 'a saved choice wins' ); 260});