Merge branch 'f-022-int' into f-022-intfix
This commit is contained in:
commit
67bb56bd1d
17 files changed
+510
-37
No files matched your search
@@ -10,7 +10,8 @@
|
||||
* made (exFAT, FAT, a network share) the models simply go in `<data>/models`.
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join, parse, resolve } from 'node:path';
|
||||
|
||||
export const isDriveRoot = path => { const p = resolve(path); return p === parse(p).root; };
|
||||
@@ -48,18 +49,64 @@ export function alignModels(data, library, { link = symlinkSync } = {}) {
|
||||
return { data, linked: false };
|
||||
}
|
||||
|
||||
/** Write the person's data folder into the Control settings file (merged, atomically); returns whether it changed. Never throws: the folder
|
||||
* still works for the app, only the Terminal and the installer's own check lose the shared setting. */
|
||||
export function rememberDataFolder(file, folder) {
|
||||
|
||||
function readSettings(file) {
|
||||
try { const parsed = JSON.parse(readFileSync(file, 'utf8').replace(/^/, '')); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; } catch { return {}; }
|
||||
}
|
||||
|
||||
/** The data folder a settings file names and when it was last changed (`data_dir_at`, seconds; the file's own time for a file that has none). */
|
||||
export function readDataFolder(file) {
|
||||
if (!file) return null;
|
||||
const current = readSettings(file);
|
||||
if (typeof current.data_dir !== 'string' || !current.data_dir) return null;
|
||||
let at = Number(current.data_dir_at);
|
||||
if (!Number.isFinite(at) || at <= 0) { try { at = statSync(file).mtimeMs / 1000; } catch { at = 0; } }
|
||||
return { folder: current.data_dir, at };
|
||||
}
|
||||
|
||||
/** The settings file the Terminal (command-line Strata) keeps: the same place setup.py and strata_control/discovery.py use. */
|
||||
export function terminalSettingsFile(env = process.env, platform = process.platform) {
|
||||
if (env.STRATA_TERMINAL_SETTINGS_FILE) return env.STRATA_TERMINAL_SETTINGS_FILE;
|
||||
if (platform === 'win32') return join(env.APPDATA || join(homedir(), 'AppData', 'Roaming'), 'Strata', 'settings.json');
|
||||
return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'strata', 'settings.json');
|
||||
}
|
||||
|
||||
/** Write the person's data folder into a settings file (merged, atomically) with the time of the change; returns whether it changed. Never
|
||||
* throws: the folder still works for the app, only the Terminal and the installer's own check lose the shared setting. */
|
||||
export function rememberDataFolder(file, folder, at = Date.now() / 1000, touch = false) {
|
||||
if (!file || !folder) return false;
|
||||
try {
|
||||
let current = {};
|
||||
try { const parsed = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) current = parsed; } catch { /* a new file */ }
|
||||
if (current.data_dir === folder) return false;
|
||||
const current = readSettings(file);
|
||||
if (current.data_dir === folder && !touch) return false;
|
||||
mkdirSync(dirname(file), { recursive: true });
|
||||
const temp = `${file}.${process.pid}.tmp`;
|
||||
writeFileSync(temp, JSON.stringify({ ...current, data_dir: folder }, null, 1) + '\n', { mode: 0o600 });
|
||||
writeFileSync(temp, JSON.stringify({ ...current, data_dir: folder, data_dir_at: at }, null, 1) + '\n', { mode: 0o600 });
|
||||
renameSync(temp, file);
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
const same = (a, b) => resolve(a).toLowerCase() === resolve(b).toLowerCase();
|
||||
|
||||
/**
|
||||
* One models folder for the app and the Terminal. The app keeps its choice in its own settings file (`appFile`), the Terminal in `terminalFile`;
|
||||
* whichever was changed last wins and the other file is brought up to date. Nothing is moved. A folder that is gone (a disk that is not
|
||||
* connected) is never adopted. `app` is the app's own answer when its file names none (`{ folder, at }`).
|
||||
* Returns `{ folder, from }`: the shared folder (null when neither names one) and `from` = 'terminal' when the app has to take over the
|
||||
* Terminal's folder, 'app' when the Terminal's file was updated, null when nothing changed.
|
||||
*/
|
||||
export function syncDataFolder({ appFile, terminalFile, app = null, exists = path => existsSync(path) }) {
|
||||
const mine = readDataFolder(appFile) ?? app;
|
||||
const theirs = readDataFolder(terminalFile);
|
||||
const theirsUsable = theirs && exists(theirs.folder);
|
||||
if (!theirsUsable) {
|
||||
if (mine && theirs && !same(mine.folder, theirs.folder)) { rememberDataFolder(terminalFile, mine.folder, mine.at); return { folder: mine.folder, from: 'app' }; }
|
||||
return { folder: mine?.folder ?? null, from: null };
|
||||
}
|
||||
if (!mine || (!same(mine.folder, theirs.folder) && theirs.at > mine.at)) {
|
||||
rememberDataFolder(appFile, theirs.folder, theirs.at);
|
||||
return { folder: theirs.folder, from: 'terminal' };
|
||||
}
|
||||
if (!same(mine.folder, theirs.folder)) { rememberDataFolder(terminalFile, mine.folder, mine.at); return { folder: mine.folder, from: 'app' }; }
|
||||
return { folder: mine.folder, from: null };
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import os from 'node:os';
|
||||
import { runtimeVision } from './native-vision.mjs';
|
||||
import { componentsDirectory, installerEnvironment, controlEnvironment } from './control-runtime.mjs';
|
||||
import { createEngineStep } from './engine-step.mjs';
|
||||
import { dataFolderFromPick, isDriveRoot, makeFolder, rememberDataFolder } from './model-folder.mjs';
|
||||
import { dataFolderFromPick, isDriveRoot, makeFolder, rememberDataFolder, syncDataFolder, terminalSettingsFile } from './model-folder.mjs';
|
||||
import { createAutoTune, writeTuneConfig } from './native-autotune.mjs';
|
||||
import { plainError, PHASE_TEXT } from './update-messages.mjs';
|
||||
import { checkRunConfig, describeIssues } from './run-config-check.mjs';
|
||||
@@ -75,6 +75,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
function installRoot(){const found=[preferences.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());}
|
||||
/* The settings file Strata Control and the installer read (control-runtime.mjs sets STRATA_SETTINGS_FILE to it): the app's data folder is written there. */
|
||||
function controlSettingsFile(){return process.env.STRATA_SETTINGS_FILE||join(dirname(componentsDirectory()),'app-settings.json');}
|
||||
/* One models folder for the app and the Terminal: the one changed last wins and the other settings file is updated (nothing is moved). */
|
||||
function shareDataFolder(){if(!packaged)return;try{let at=0;if(preferences.downloadDirectory)try{at=statSync(settingsPath).mtimeMs/1000;}catch{/* no file yet */}const found=syncDataFolder({appFile:controlSettingsFile(),terminalFile:terminalSettingsFile(),app:preferences.downloadDirectory?{folder:preferences.downloadDirectory,at}:null});if(found.from==='terminal'&&found.folder&&found.folder!==preferences.downloadDirectory){preferences={...preferences,downloadDirectory:found.folder};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});}}catch{/* the shared setting is a convenience: never stop the app */}}
|
||||
function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;}
|
||||
function python(){return resolvePython({repo:preferences.repo});}
|
||||
function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});}
|
||||
@@ -124,7 +126,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);let visionReader=false;if(packaged){try{const e=await control.engine();const root=e?.engine?.root??(e?.engine?.exe?dirname(e.engine.exe):'');visionReader=!!root&&['strata-vision','strata-vision.exe'].some(n=>existsSync(join(root,n)));}catch{visionReader=false;}}const markImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,imagesCapable:!!f.images,images:!!f.images&&visionReader,sizes:(f.sizes??[]).map(s=>({...s,imagesCapable:!!s.images,images:!!s.images&&visionReader}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:markEngine(packaged?markImages(catalog):catalog,status.engine),engineInfo:{version:status.engine?.version??null,source:status.engine?.source??null},visionReader:packaged?visionReader:true,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});const run=refreshing;if(!force&&snapshot.available){run.catch(()=>{});return state();}return run;
|
||||
}
|
||||
function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}
|
||||
function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();}
|
||||
function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path,Date.now()/1000,true);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});shareDataFolder();emit();return state();}
|
||||
function recordFile(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path};}
|
||||
function record(model){const {entry,path}=recordFile(model);return {entry,path,config:readJson(path)};}
|
||||
/* The text file a power user edits by hand: where it is and what is wrong in it (run-config-check.mjs). */
|
||||
|
||||
@@ -5,7 +5,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, parse } from 'node:path';
|
||||
import { alignModels, dataFolderFromPick, isDriveRoot, libraryFolderFromPick, makeFolder, rememberDataFolder } from '../server/model-folder.mjs';
|
||||
import { alignModels, dataFolderFromPick, isDriveRoot, libraryFolderFromPick, makeFolder, rememberDataFolder, syncDataFolder, readDataFolder, terminalSettingsFile } from '../server/model-folder.mjs';
|
||||
import { nativeFixture } from './helpers/native-fixture.mjs';
|
||||
|
||||
const scratch = t => { const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-folder-'))); t.after(() => rmSync(dir, { recursive: true, force: true })); return dir; };
|
||||
@@ -46,10 +46,10 @@ test('models and Models are one folder; a disk that cannot hold the link gets a
|
||||
test('the data folder is written into the Control settings file, merged and only when it changes', t => {
|
||||
const dir = scratch(t), file = join(dir, 'config', 'app-settings.json');
|
||||
assert.equal(rememberDataFolder(file, 'D:\\Strata'), true);
|
||||
assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), { data_dir: 'D:\\Strata' });
|
||||
assert.equal(JSON.parse(readFileSync(file, 'utf8')).data_dir, 'D:\\Strata');
|
||||
writeFileSync(file, JSON.stringify({ installs: ['C:\\x'], data_dir: 'C:\\old' }));
|
||||
assert.equal(rememberDataFolder(file, 'D:\\Strata'), true);
|
||||
assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), { installs: ['C:\\x'], data_dir: 'D:\\Strata' });
|
||||
assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')).installs, ['C:\\x']);
|
||||
assert.equal(rememberDataFolder(file, 'D:\\Strata'), false);
|
||||
writeFileSync(file, '\uFEFF{"data_dir":"E:\\\\Strata","installs":[]}');
|
||||
assert.equal(rememberDataFolder(file, 'E:\\Strata'), false);
|
||||
@@ -97,3 +97,39 @@ test('Windows: the model library on a whole drive goes to X:\\Strata\\Models', {
|
||||
assert.equal(run.stdout.trim().toLowerCase(), `${drive}Strata\\Models`.toLowerCase());
|
||||
assert.equal(existsSync(join(dir, 'Strata', 'Models')), true);
|
||||
});
|
||||
|
||||
test('the app and the Terminal share one models folder: the one changed last wins, the other file follows, nothing moves', t => {
|
||||
const dir = scratch(t), appFile = join(dir, 'app-settings.json'), terminalFile = join(dir, 'roaming', 'settings.json');
|
||||
const c = join(dir, 'on-c'), d = join(dir, 'on-d');
|
||||
mkdirSync(c); mkdirSync(d);
|
||||
const seed = (file, folder, at) => { mkdirSync(join(file, '..'), { recursive: true }); writeFileSync(file, JSON.stringify({ data_dir: folder, data_dir_at: at, installs: ['keep'] })); };
|
||||
// the Terminal chose D: after the app chose C:
|
||||
seed(appFile, c, 1000); seed(terminalFile, d, 2000);
|
||||
assert.deepEqual(syncDataFolder({ appFile, terminalFile }), { folder: d, from: 'terminal' });
|
||||
assert.deepEqual(readDataFolder(appFile), { folder: d, at: 2000 });
|
||||
assert.deepEqual(JSON.parse(readFileSync(appFile, 'utf8')).installs, ['keep']);
|
||||
assert.deepEqual(syncDataFolder({ appFile, terminalFile }), { folder: d, from: null });
|
||||
// the app chose C: later
|
||||
seed(appFile, c, 3000);
|
||||
assert.deepEqual(syncDataFolder({ appFile, terminalFile }), { folder: c, from: 'app' });
|
||||
assert.deepEqual(readDataFolder(terminalFile), { folder: c, at: 3000 });
|
||||
// the Terminal has none: nothing is written there; the app has none: it takes the Terminal's
|
||||
const lone = join(dir, 'lone.json');
|
||||
assert.deepEqual(syncDataFolder({ appFile: join(dir, 'none.json'), terminalFile: lone }), { folder: null, from: null });
|
||||
assert.equal(existsSync(lone), false);
|
||||
seed(lone, d, 10);
|
||||
assert.deepEqual(syncDataFolder({ appFile: join(dir, 'none.json'), terminalFile: lone }), { folder: d, from: 'terminal' });
|
||||
// the app's preference (native-host.json) counts when its file names none
|
||||
assert.deepEqual(syncDataFolder({ appFile: join(dir, 'none2.json'), terminalFile: lone, app: { folder: c, at: 99 } }), { folder: c, from: 'app' });
|
||||
// a Terminal folder on a disk that is not there is never adopted
|
||||
seed(terminalFile, join(dir, 'unplugged'), 9999); seed(appFile, c, 5);
|
||||
assert.deepEqual(syncDataFolder({ appFile, terminalFile }), { folder: c, from: 'app' });
|
||||
assert.equal(readdirSyncSafe(c), 0);
|
||||
});
|
||||
const readdirSyncSafe = folder => execFileSync(process.execPath, ['-e', `console.log(require('fs').readdirSync(${JSON.stringify(folder)}).length)`]).toString().trim() * 1;
|
||||
|
||||
test('the Terminal settings file is where setup.py and Control keep it', () => {
|
||||
assert.equal(terminalSettingsFile({ APPDATA: 'C:\R' }, 'win32'), join('C:\R', 'Strata', 'settings.json'));
|
||||
assert.equal(terminalSettingsFile({ XDG_CONFIG_HOME: '/x' }, 'linux'), join('/x', 'strata', 'settings.json'));
|
||||
assert.equal(terminalSettingsFile({ STRATA_TERMINAL_SETTINGS_FILE: '/t.json' }, 'linux'), '/t.json');
|
||||
});
|
||||
+73
-4
@@ -69,6 +69,57 @@ for legacy in HOST LOW_RAM REINSTALL RESIDENT_BUDGET_GIB KV_STREAMING LAYER_SPLI
|
||||
[ -n "$v" ] && warn "$legacy is from the older image and is ignored here. See docs/DOCKER.md (\"From the older image\")."
|
||||
done
|
||||
|
||||
# ---- a volume from the older (0.1.x) image: its models, packs and draft layer are in /data/models, /data/packs and /data/mtp.
|
||||
# This image keeps them in /data/Strata-data. Move them over (a rename inside one volume: instant, no copy, no download).
|
||||
# A folder that is its own mount (a bind mount of yours) is never touched.
|
||||
legacy_moved=""
|
||||
for d in models packs mtp; do
|
||||
[ -d "/data/$d" ] || continue
|
||||
grep -q " /data/$d " /proc/self/mountinfo 2>/dev/null && continue
|
||||
[ -n "$(ls -A "/data/$d" 2>/dev/null)" ] || continue
|
||||
mkdir -p "/data/Strata-data/$d" 2>/dev/null || continue
|
||||
for item in "/data/$d"/* "/data/$d"/.[!.]*; do
|
||||
[ -e "$item" ] || continue
|
||||
name=${item##*/}
|
||||
[ -e "/data/Strata-data/$d/$name" ] && continue
|
||||
if mv "$item" "/data/Strata-data/$d/$name" 2>/dev/null; then legacy_moved="$legacy_moved $d/$name"
|
||||
else warn "Could not move $item into /data/Strata-data/$d (the model is downloaded again unless you set MODEL_PATH=/data/$d/...)."; fi
|
||||
done
|
||||
rmdir "/data/$d" 2>/dev/null || true
|
||||
done
|
||||
[ -n "$legacy_moved" ] && say "Found model files from the older image in the volume and moved them into /data/Strata-data (no copy, nothing is downloaded again):$legacy_moved"
|
||||
|
||||
# ---- run settings made by an image for another card or another engine version name that image's engine folder
|
||||
# (/opt/strata/components/engine/<package>/...): in this image that folder is not there, so the server would stop at the start. Drop
|
||||
# them; the next step writes them again from the model files, which are kept.
|
||||
for c in /data/install/strata-*.json; do
|
||||
[ -f "$c" ] || continue
|
||||
gone=$("$PYBIN" -c '
|
||||
import json, os, sys
|
||||
def walk(v):
|
||||
if isinstance(v, str):
|
||||
yield v
|
||||
elif isinstance(v, dict):
|
||||
for x in v.values():
|
||||
yield from walk(x)
|
||||
elif isinstance(v, list):
|
||||
for x in v:
|
||||
yield from walk(x)
|
||||
try:
|
||||
cfg = json.load(open(sys.argv[1], encoding="utf-8-sig"))
|
||||
except (OSError, ValueError):
|
||||
sys.exit(0)
|
||||
for s in walk(cfg):
|
||||
if s.startswith("/opt/strata/components/") and not os.path.exists(s):
|
||||
print(s)
|
||||
break
|
||||
' "$c" 2>/dev/null)
|
||||
if [ -n "$gone" ]; then
|
||||
say "The saved run settings $(basename "$c") name $gone, which this image does not have (made by an image for another card or engine version): making them again. The model files are kept."
|
||||
rm -f "$c"
|
||||
fi
|
||||
done
|
||||
|
||||
# ---- is there an engine for this card?
|
||||
phase checking
|
||||
engine_json=$("$STRATA" components engine --output json 2>/dev/null || true)
|
||||
@@ -86,10 +137,13 @@ MSG
|
||||
fi
|
||||
|
||||
# the card is found through sysfs even when no device file was passed in: say so now instead of failing when the engine starts
|
||||
# (before the model is prepared; /dev/dxg is the GPU of Docker Desktop on WSL2)
|
||||
backend=$(printf '%s' "$engine_json" | sed -n 's/.*"backend": *"\([a-z0-9]*\)".*/\1/p' | head -1)
|
||||
dev="${STRATA_DEV_DIR:-/dev}"
|
||||
case "$backend" in
|
||||
hip) [ -e /dev/kfd ] || { echo "[X] This is an AMD card, but /dev/kfd is not in the container. Add: --device /dev/kfd --device /dev/dri --group-add video --group-add <render group number> (docs/DOCKER.md)" >&2; exit 3; } ;;
|
||||
sycl) ls /dev/dri/renderD* >/dev/null 2>&1 || { echo "[X] This is an Intel card, but /dev/dri is not in the container. Add: --device /dev/dri --group-add <render group number> (docs/DOCKER.md)" >&2; exit 3; } ;;
|
||||
cuda) ls "$dev"/nvidia[0-9]* >/dev/null 2>&1 || [ -e "$dev/dxg" ] || { echo "[X] This computer has an NVIDIA card, but the container cannot use it, so nothing would run (and the model would be prepared for nothing). Start the container with: --gpus all (needs the NVIDIA Container Toolkit on the host; docs/DOCKER.md, Troubleshooting)." >&2; exit 3; } ;;
|
||||
hip) [ -e "$dev/kfd" ] || { echo "[X] This is an AMD card, but /dev/kfd is not in the container. Add: --device /dev/kfd --device /dev/dri --group-add video --group-add <render group number> (docs/DOCKER.md)" >&2; exit 3; } ;;
|
||||
sycl) ls "$dev"/dri/renderD* >/dev/null 2>&1 || { echo "[X] This is an Intel card, but /dev/dri is not in the container. Add: --device /dev/dri --group-add <render group number> (docs/DOCKER.md)" >&2; exit 3; } ;;
|
||||
esac
|
||||
|
||||
# ---- the API key
|
||||
@@ -107,6 +161,18 @@ preset_exists=""
|
||||
if "$STRATA" launch --list-presets --output json 2>/dev/null | grep -q "\"name\": *\"$PRESET\""; then preset_exists=1; fi
|
||||
|
||||
model_path="${MODEL_PATH:-${GGUF_DIR:-}}"
|
||||
if [ -n "$model_path" ]; then
|
||||
# a folder that is not mounted (or a typo) must not end as "missing /xxx.gguf" after a minute of setup, and must never turn into a download
|
||||
if [ ! -e "$model_path" ]; then
|
||||
die "MODEL_PATH=$model_path is not in the container, so no model file can be found there. Mount your folder at that place, for example: -v /srv/gguf/IQ3_XXS:$model_path:ro (docs/DOCKER.md, \"Files you already have\"). Nothing was downloaded." 2
|
||||
elif [ -d "$model_path" ] && ! ls "$model_path"/*.gguf >/dev/null 2>&1; then
|
||||
sub=$(find "$model_path" -maxdepth 2 -name '*.gguf' 2>/dev/null | head -1)
|
||||
if [ -n "$sub" ]; then
|
||||
die "MODEL_PATH=$model_path has no .gguf files directly in it, but there are some in ${sub%/*}. Set MODEL_PATH=${sub%/*} (the folder that holds the shards of one model). Nothing was downloaded." 2
|
||||
fi
|
||||
die "MODEL_PATH=$model_path holds no .gguf files. Mount the folder with the model's shards (the -0000N-of-0000M.gguf files). Nothing was downloaded." 2
|
||||
fi
|
||||
fi
|
||||
[ -n "${MODEL:-}" ] && { set -- "$@" --model "$MODEL"; have=1; }
|
||||
[ -n "${FAMILY:-}" ] && { set -- "$@" --family "$FAMILY"; have=1; }
|
||||
[ -n "$model_path" ] && { set -- "$@" --model-path "$model_path"; have=1; }
|
||||
@@ -184,7 +250,10 @@ trap on_term TERM INT
|
||||
RESET_INT='import os, signal, sys; signal.signal(signal.SIGINT, signal.SIG_DFL); os.execv(sys.argv[1], sys.argv[1:])'
|
||||
|
||||
phase preparing
|
||||
say "Starting Strata: ${MODEL:-recommended model}${model_path:+ from $model_path} (preset '$PRESET')."
|
||||
if [ -n "${MODEL:-}" ]; then what="$MODEL${model_path:+ from $model_path}"
|
||||
elif [ -n "$model_path" ]; then what="the model files in $model_path"
|
||||
else what="the recommended model"; fi
|
||||
say "Starting Strata: $what (preset '$PRESET')."
|
||||
if [ -n "$key" ]; then
|
||||
STRATA_LAUNCH_KEY="$key" "$PYBIN" -c "$RESET_INT" "$STRATA" "$@" &
|
||||
else
|
||||
@@ -197,7 +266,7 @@ launch_pid=""
|
||||
[ -n "$stopping" ] && exit 0
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
phase failed
|
||||
die "strata launch stopped with code $rc (the lines above say why). The container ends; a restart continues where it stopped (downloads resume)." "$rc"
|
||||
die "strata launch stopped with code $rc (the lines above say why). The container ends. Fix that and start it again: finished steps are not repeated, and an interrupted download continues where it stopped." "$rc"
|
||||
fi
|
||||
|
||||
# keep the key where `docker exec ... strata monitor` and the health check can read it (private file on the volume)
|
||||
|
||||
+17
-3
@@ -41,7 +41,8 @@ tag if you want updates only when you decide. The examples below use these image
|
||||
|
||||
Each command runs Strata in the background, keeps your files in the volume `strata-data`, and listens only on this computer
|
||||
(`127.0.0.1:8080`). Replace `MODEL` and the key. The first start downloads the model (tens of GB): watch it with
|
||||
`docker logs -f strata`.
|
||||
`docker logs -f strata`. Already have the model's GGUF files? Add `-e MODEL_PATH=/models -v /your/folder:/models:ro` and nothing is
|
||||
downloaded for the model itself ([Files you already have](#files-you-already-have)).
|
||||
|
||||
**NVIDIA**
|
||||
|
||||
@@ -142,6 +143,17 @@ container's user). Nothing large is written anywhere else in the container.
|
||||
Mount the folder with the model's GGUF files read-only and name it: `-v /srv/gguf/IQ3_XXS:/models:ro -e MODEL_PATH=/models
|
||||
-e MODEL=IQ3_XXS`. Nothing is downloaded for the model itself; the prepared pack is made in the volume.
|
||||
|
||||
- The folder holds the shards of one model directly (`...-00001-of-00002.gguf`, `...-00002-of-00002.gguf`), not a folder of folders.
|
||||
If you mount a parent folder, the container says which sub-folder to name in `MODEL_PATH`.
|
||||
- The folder has to be mounted: a `MODEL_PATH` that is not in the container, or a folder with no `.gguf` files, stops the start at
|
||||
once with a message, and nothing is downloaded.
|
||||
- Read-only (`:ro`) is fine. The pack (about 40 GB for IQ3_XXS) and the draft layer (about 6 GB, fetched once) are written to the
|
||||
volume, so it needs that room. With pictures on (the default) the picture reader (0.9 GB) is fetched too; `VISION=off` skips it.
|
||||
- Links to the files work when the links' targets are mounted too, and `MODEL` is set (without `MODEL`, Strata identifies the files itself
|
||||
and does not follow links).
|
||||
- Without `MODEL_PATH`, files you put into the volume by hand (`/data/Strata-data/models/<model folder>/`) are found as well, if they have the
|
||||
published names.
|
||||
|
||||
## The API key
|
||||
|
||||
The server listens on every address **inside** the container (that is what lets the published port work), and Strata does not
|
||||
@@ -260,8 +272,10 @@ package and start through `strata launch`. Mapping:
|
||||
| `HOST` | not needed: the server listens on every address inside the container; choose where it is reachable with `-p` |
|
||||
| `LOW_RAM`, `RESIDENT_BUDGET_GIB`, `KV_STREAMING`, `LAYER_SPLIT`, `CONFIG`, `REINSTALL` | ignored with a warning; use `STRATA_SET` for engine settings and `strata launch --help` for the rest |
|
||||
|
||||
The old volume layout (`/data/config`, `/data/models`) is not read; the model files are found again if you point `MODEL_PATH` at
|
||||
the old model folder. The container name, the volume and the port can stay as they were.
|
||||
A volume from the older image is picked up: the first start moves `/data/models`, `/data/packs` and `/data/mtp` into
|
||||
`/data/Strata-data` (a rename inside the volume: nothing is copied or downloaded again, and the prepared pack is kept). The old
|
||||
`/data/config` is not read; the run settings are made again from the files. A folder you mounted yourself at one of those places
|
||||
is left alone: point `MODEL_PATH` at it. The container name, the volume and the port can stay as they were.
|
||||
|
||||
## Build it yourself
|
||||
|
||||
|
||||
@@ -7663,6 +7663,26 @@ def default_model_name(cfg: dict) -> str:
|
||||
return cfg.get("model_name") or FAMILY_MODEL_NAMES.get(cfg.get("arch") or "qwen4exp", "qwen3.8-flash-next")
|
||||
|
||||
|
||||
def with_current_reader(cfg: dict, package: Path) -> dict:
|
||||
"""The picture reader (vision "exe", "cpu_exe") is written into the run config as an absolute path inside the engine package's folder,
|
||||
and that folder is named after the engine version: after an engine update, or in a container made for another card, the path is gone
|
||||
and the server would stop with "server_exited". Use the same file of the package that is installed now (the reader ships in the package)."""
|
||||
vision = cfg.get("vision")
|
||||
if not isinstance(vision, dict):
|
||||
return cfg
|
||||
fixed = dict(vision)
|
||||
for key in ("exe", "cpu_exe"):
|
||||
old = fixed.get(key)
|
||||
if isinstance(old, str) and old and not engine_component.is_reference(old) and os.path.isabs(old) and not os.path.exists(old):
|
||||
new = package / old.replace("\\", "/").rsplit("/", 1)[-1]
|
||||
if new.is_file():
|
||||
print(f"[strata] the picture reader {old} is not there any more; using {new} from the engine package in use", flush=True)
|
||||
fixed[key] = str(new)
|
||||
if fixed == vision:
|
||||
return cfg
|
||||
return {**cfg, "vision": fixed}
|
||||
|
||||
|
||||
def with_component_engine(cfg: dict) -> dict:
|
||||
"""A run config that names "component:strata-engine" gets the engine package for this PC: the path in `exe`, and
|
||||
the package's own folder first on the library path (the GPU runtime libraries ship beside the binary)."""
|
||||
@@ -7671,6 +7691,7 @@ def with_component_engine(cfg: dict) -> dict:
|
||||
cfg = dict(cfg)
|
||||
cfg["exe"] = _component_exe(cfg["exe"], cfg)
|
||||
cfg["lib_dirs"] = [*engine_component.package_lib_dirs(Path(cfg["exe"]).parent), *(cfg.get("lib_dirs") or [])]
|
||||
cfg = with_current_reader(cfg, Path(cfg["exe"]).parent)
|
||||
if cfg.get("backend") == "hip": # AMD: the package's own hipBLASLt tuning table for this card, when its hipBLASLt version matches
|
||||
cfg = hipblaslt_tuning.apply(cfg, Path(cfg["exe"]).parent, say=lambda line: print(line, flush=True))
|
||||
return cfg
|
||||
|
||||
@@ -5384,6 +5384,8 @@ def load_settings() -> dict:
|
||||
|
||||
|
||||
def save_settings(s: dict) -> None:
|
||||
if s.get("data_dir") and s.get("data_dir") != load_settings().get("data_dir"):
|
||||
s = {**s, "data_dir_at": time.time()} # when the models folder was chosen: the app and the Terminal keep the newer choice
|
||||
try:
|
||||
settings_path().parent.mkdir(parents=True, exist_ok=True)
|
||||
settings_path().write_text(json.dumps(s, indent=1), encoding="utf-8")
|
||||
|
||||
@@ -510,7 +510,7 @@ def run_launch(a: argparse.Namespace) -> int:
|
||||
sm = store.summary(i)
|
||||
_say(f"{i.name:<28} {sm['model']:<14} {S.context_label(i.context):<6} "
|
||||
f"{(str(i.parallel) + ' request' + ('s' if i.parallel != 1 else '')) if i.parallel else 'fit to card':<14} "
|
||||
f"{('tuned ' + (i.tuned_at or '')) if i.tuned_preset else 'not tuned':<16} {i.last_used or ''}")
|
||||
f"{('tuned ' + (i.tuned_at or '')) if i.is_tuned else 'not tuned':<16} {i.last_used or ''}")
|
||||
return 0
|
||||
if a.delete_preset:
|
||||
store.delete(a.delete_preset)
|
||||
|
||||
@@ -818,6 +818,9 @@ class Runner:
|
||||
return
|
||||
except presets.PresetError:
|
||||
pass
|
||||
elif s.tuned_at: # measured before: the standard settings were already the fastest, nothing was saved
|
||||
self.emit("tune", f"Already tuned on {s.tuned_at}: this computer runs best with the standard settings. Nothing to do.", 100)
|
||||
return
|
||||
mode = "thorough" if s.tune == "thorough" else "quick"
|
||||
status_file = launch_dir() / f"{self.name}.tune.json"
|
||||
try:
|
||||
|
||||
@@ -241,9 +241,9 @@ class StartScreen(Base):
|
||||
for p in self.presets:
|
||||
sm = store.summary(p)
|
||||
req = (f"{p.parallel} request" + ("s" if p.parallel != 1 else "")) if p.parallel else "fit to card"
|
||||
tuned = f"tuned {p.tuned_at[5:]}" if p.tuned_preset and p.tuned_at else "not tuned"
|
||||
tuned = f"tuned {p.tuned_at[5:]}" if p.is_tuned and p.tuned_at else "not tuned"
|
||||
used = f"last used {p.last_used[5:10]}" if p.last_used else "not used yet"
|
||||
items.append(Item([p.name or "?", str(sm["model"]), S.context_label(p.context), req, Cell(tuned, MUTE if not p.tuned_preset else ""),
|
||||
items.append(Item([p.name or "?", str(sm["model"]), S.context_label(p.context), req, Cell(tuned, MUTE if not p.is_tuned else ""),
|
||||
Cell(used, MUTE)], key=("preset", p.name)))
|
||||
items.append(Item([Cell("Set up from the beginning", "")], key=("new", None)))
|
||||
items.append(Item([Cell("Use model files I already have", "")], key=("own", None)))
|
||||
@@ -921,11 +921,11 @@ class TuningScreen(Base):
|
||||
|
||||
def on_mount(self) -> None:
|
||||
s = self.ctx.settings
|
||||
first = self.ctx.fresh_setup and not s.tuned_preset
|
||||
first = self.ctx.fresh_setup and not s.is_tuned
|
||||
items = [Item(["Quick", "about 20 minutes", "checks the most likely gains" + ("; suggested the first time" if first else "")], key="quick"),
|
||||
Item(["Thorough", "up to 2 hours", "tries more settings, measures each one several times"], key="thorough"),
|
||||
Item(["Skip", "", "use the default settings (already good on most computers)"], key="skip")]
|
||||
if not self.ctx.tune_chosen and s.tune == "skip" and not s.tuned_preset and self.ctx.fresh_setup:
|
||||
if not self.ctx.tune_chosen and s.tune == "skip" and not s.is_tuned and self.ctx.fresh_setup:
|
||||
s.tune = "quick"
|
||||
self.query_one(Menu).set_items(items, {"quick": 0, "thorough": 1, "skip": 2}.get(s.tune, 0))
|
||||
self.paint()
|
||||
|
||||
@@ -100,6 +100,12 @@ class LaunchSettings:
|
||||
last_used: str | None = None
|
||||
created: str | None = None
|
||||
|
||||
@property
|
||||
def is_tuned(self) -> bool:
|
||||
"""Tuning was done for this preset: it saved faster settings (tuned_preset), or it measured that the standard settings are already the
|
||||
fastest (only tuned_at is set). Either way the next start must not tune again."""
|
||||
return bool(self.tuned_preset or self.tuned_at)
|
||||
|
||||
def to_dict(self, *, with_key: bool = True) -> dict[str, Any]:
|
||||
d = {"schema": SCHEMA, **asdict(self)}
|
||||
if not with_key:
|
||||
|
||||
@@ -139,5 +139,5 @@ def touch_used(name: str) -> None:
|
||||
def summary(s: LaunchSettings) -> dict[str, Any]:
|
||||
"""The columns of the start screen."""
|
||||
return {"name": s.name, "model": s.model or ("own files" if s.model_path else "-"),
|
||||
"context": s.context, "parallel": s.parallel, "tuned": bool(s.tuned_preset), "tuned_at": s.tuned_at,
|
||||
"context": s.context, "parallel": s.parallel, "tuned": s.is_tuned, "tuned_at": s.tuned_at,
|
||||
"last_used": s.last_used, "access": s.access}
|
||||
@@ -202,25 +202,79 @@ def find_install(*, here: Path | None = None, explicit: str | os.PathLike | None
|
||||
|
||||
# ----------------------------------------------------------------------------------------------- the data folder
|
||||
|
||||
def _data_dir_entry(file: Path) -> tuple[str, float] | None:
|
||||
"""(the data folder a settings file names, when it was last changed): ``data_dir_at`` (seconds), else the file's own time."""
|
||||
data = _read_json(file)
|
||||
folder = data.get("data_dir")
|
||||
if not isinstance(folder, str) or not folder:
|
||||
return None
|
||||
at = data.get("data_dir_at")
|
||||
if isinstance(at, bool) or not isinstance(at, (int, float)) or at <= 0:
|
||||
try:
|
||||
at = file.stat().st_mtime
|
||||
except OSError:
|
||||
at = 0.0
|
||||
return folder, float(at)
|
||||
|
||||
|
||||
def _same(a: str, b: str) -> bool:
|
||||
return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b))
|
||||
|
||||
|
||||
def _write_data_dir(file: Path, folder: str, at: float) -> bool:
|
||||
"""Merge the data folder and its time into a settings file (atomic). False when the disk refuses; never raises."""
|
||||
try:
|
||||
current = _read_json(file)
|
||||
current["data_dir"], current["data_dir_at"] = folder, at
|
||||
file.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = file.with_name(f"{file.name}.{os.getpid()}.tmp")
|
||||
temp.write_text(json.dumps(current, indent=1), encoding="utf-8")
|
||||
os.replace(temp, file)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def sync_data_dir(*, environ=None, windows: bool | None = None, home: Path | None = None) -> tuple[Path, str] | None:
|
||||
"""One models folder for the Terminal and the desktop app. The Terminal's settings file and the app's (``app-settings.json``) each name
|
||||
a data folder; when they disagree the one changed last wins and the other file is updated. Nothing is moved. Returns (folder, source of
|
||||
the winner) or None when neither names one. The app's own processes never call this (the app syncs from its host)."""
|
||||
environ = os.environ if environ is None else environ
|
||||
if in_app_mode(environ):
|
||||
return None
|
||||
mine_file = own_settings_file(environ, windows=windows, home=home)
|
||||
app_file = app_settings_file(environ, windows=windows, home=home)
|
||||
mine, app = _data_dir_entry(mine_file), _data_dir_entry(app_file)
|
||||
if mine and app and not _same(mine[0], app[0]):
|
||||
newer, older_file, source = (mine, app_file, "settings") if mine[1] >= app[1] else (app, mine_file, "app")
|
||||
if source == "app" and not Path(app[0]).is_dir(): # a disk that is not connected is never adopted
|
||||
return Path(mine[0]), "settings"
|
||||
_write_data_dir(older_file, newer[0], newer[1])
|
||||
return Path(newer[0]), source
|
||||
if mine:
|
||||
return Path(mine[0]), "settings"
|
||||
return (Path(app[0]), "app") if app else None
|
||||
|
||||
|
||||
def data_dir_choices(*, environ=None, windows: bool | None = None, home: Path | None = None) -> list[tuple[Path, str]]:
|
||||
"""Candidate data folders with their source, best first (not checked for existence)."""
|
||||
environ = os.environ if environ is None else environ
|
||||
out: list[tuple[Path, str]] = []
|
||||
own = _read_json(own_settings_file(environ, windows=windows, home=home)).get("data_dir")
|
||||
if isinstance(own, str) and own:
|
||||
out.append((Path(own), "settings"))
|
||||
own = _data_dir_entry(own_settings_file(environ, windows=windows, home=home))
|
||||
app = None if in_app_mode(environ) else _data_dir_entry(app_settings_file(environ, windows=windows, home=home))
|
||||
entries = [(Path(e[0]), src, e[1]) for e, src in ((own, "settings"), (app, "app")) if e]
|
||||
entries.sort(key=lambda x: -x[2]) # the folder changed last first, whichever file it is in
|
||||
out.extend((p, src) for p, src, _ in entries)
|
||||
if not in_app_mode(environ):
|
||||
app = _read_json(app_settings_file(environ, windows=windows, home=home)).get("data_dir")
|
||||
if isinstance(app, str) and app:
|
||||
out.append((Path(app), "app"))
|
||||
for d in documents_dirs(environ, windows=windows, home=home):
|
||||
out.append((d / "Strata", "documents"))
|
||||
return out
|
||||
|
||||
|
||||
def data_dir(default: Path, *, environ=None, windows: bool | None = None, home: Path | None = None) -> tuple[Path, str]:
|
||||
"""(the data folder, source). The person's own setting wins; then the app's folder, then a ``Documents/Strata`` that holds models;
|
||||
else `default`."""
|
||||
"""(the data folder, source). Of the Terminal's own setting and the app's folder the one changed last wins (the other file is brought up
|
||||
to date); then a ``Documents/Strata`` that holds models; else `default`."""
|
||||
sync_data_dir(environ=environ, windows=windows, home=home)
|
||||
choices = data_dir_choices(environ=environ, windows=windows, home=home)
|
||||
for path, source in choices:
|
||||
if source == "settings":
|
||||
|
||||
@@ -202,6 +202,23 @@ class ComponentStart(unittest.TestCase):
|
||||
server.with_component_engine({"exe": "component:strata-engine", "backend": "cuda"})
|
||||
self.assertEqual(caught.exception.code, 5)
|
||||
|
||||
def test_a_picture_reader_path_from_an_older_engine_folder_follows_the_installed_package(self):
|
||||
"""After an engine update the folder name changes; the run config's absolute vision exe must not stop the server."""
|
||||
from serve import server
|
||||
folder = install_fake_engine(self.components)
|
||||
reader = folder / "strata-vision"
|
||||
reader.write_text("x", encoding="utf-8")
|
||||
gone = str(self.components / "engine" / "0.0.1-old" / "strata-vision")
|
||||
cfg = server.with_component_engine({"exe": "component:strata-engine", "backend": "cuda",
|
||||
"vision": {"exe": gone, "cpu_exe": gone, "mmproj": "/m.gguf"}})
|
||||
self.assertEqual(cfg["vision"]["exe"], str(reader))
|
||||
self.assertEqual(cfg["vision"]["cpu_exe"], str(reader))
|
||||
self.assertEqual(cfg["vision"]["mmproj"], "/m.gguf")
|
||||
ok = {"exe": "component:strata-engine", "backend": "cuda", "vision": {"exe": str(reader)}}
|
||||
self.assertEqual(server.with_component_engine(ok)["vision"], {"exe": str(reader)})
|
||||
none = server.with_component_engine({"exe": "component:strata-engine", "backend": "cuda", "vision": {"exe": gone.replace("strata-vision", "other")}})
|
||||
self.assertTrue(none["vision"]["exe"].endswith("other")) # no such file in the package: left as it is
|
||||
|
||||
def test_the_build_json_lib_dirs_follow_the_package_folder(self):
|
||||
"""The Windows HIP package keeps the ROCm DLLs in rocm/bin (BUILD.json lib_dirs): strata.exe does not load without them on PATH."""
|
||||
from serve import server
|
||||
|
||||
@@ -611,6 +611,20 @@ class AdoptRules(unittest.TestCase):
|
||||
r.check_pictures(path)
|
||||
self.assertEqual(seen, [])
|
||||
|
||||
def test_tuning_that_found_the_standard_settings_fastest_is_not_run_again(self):
|
||||
# "already fastest" saves no tuning preset, only tuned_at: the next start (a container restart with TUNE=quick) must not measure for 20 minutes again
|
||||
with Home():
|
||||
seen = []
|
||||
s = S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, tune="quick", tuned_at="2026-10-20")
|
||||
self.assertTrue(s.is_tuned)
|
||||
r = Runner(s, catalog=catalog(HW_12), emit=seen.append)
|
||||
with mock.patch.object(r, "_spawn", side_effect=AssertionError("tuned again")):
|
||||
r.tune()
|
||||
self.assertTrue(any("Already tuned on 2026-10-20" in e.text for e in seen))
|
||||
self.assertFalse(S.LaunchSettings(tune="quick").is_tuned)
|
||||
store.save(s, "Fastest")
|
||||
self.assertTrue(store.summary(store.load("Fastest"))["tuned"])
|
||||
|
||||
def test_runner_adopts_when_setup_cannot_handle_the_card(self):
|
||||
with Home() as h:
|
||||
d, m = self.files(h.base)
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""One models folder for the Terminal and the desktop app: the folder changed last wins, the other settings file is updated, nothing moves."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import setup
|
||||
from strata_control import discovery
|
||||
from tests.terminal.test_discovery import GuiLayout
|
||||
|
||||
|
||||
class SharedModelsFolder(GuiLayout):
|
||||
def files(self):
|
||||
mine = Path(os.environ["APPDATA"]) / "Strata" / "settings.json"
|
||||
mine.parent.mkdir(parents=True, exist_ok=True)
|
||||
return mine, discovery.app_settings_file()
|
||||
|
||||
def put(self, file: Path, folder: Path, at: float) -> None:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
file.parent.mkdir(parents=True, exist_ok=True)
|
||||
file.write_text(json.dumps({"data_dir": str(folder), "data_dir_at": at, "installs": ["keep"]}))
|
||||
|
||||
def read(self, file: Path) -> dict:
|
||||
return json.loads(file.read_text())
|
||||
|
||||
def test_the_terminal_choice_made_last_wins_and_the_app_file_follows(self):
|
||||
mine, app = self.files()
|
||||
old, new = self.base / "on-c", self.base / "on-d"
|
||||
self.put(app, old, 1000)
|
||||
self.put(mine, new, 2000)
|
||||
self.assertEqual(discovery.data_dir(self.base / "default"), (new, "settings"))
|
||||
self.assertEqual(Path(self.read(app)["data_dir"]), new)
|
||||
self.assertEqual(self.read(app)["data_dir_at"], 2000)
|
||||
self.assertEqual(self.read(app)["installs"], ["keep"]) # merged, not replaced
|
||||
self.assertEqual(list(old.iterdir()), []) # nothing moved
|
||||
|
||||
def test_the_app_choice_made_last_wins_and_the_terminal_file_follows(self):
|
||||
mine, app = self.files()
|
||||
old, new = self.base / "on-c", self.base / "on-d"
|
||||
self.put(mine, old, 1000)
|
||||
self.put(app, new, 3000)
|
||||
self.assertEqual(discovery.data_dir(self.base / "default")[0], new)
|
||||
self.assertEqual(Path(self.read(mine)["data_dir"]), new)
|
||||
self.assertEqual(self.read(mine)["data_dir_at"], 3000)
|
||||
self.assertEqual(self.catalog().data_dir().resolve(), new.resolve())
|
||||
|
||||
def test_an_app_folder_on_a_disk_that_is_gone_is_not_adopted(self):
|
||||
mine, app = self.files()
|
||||
keep = self.base / "kept"
|
||||
self.put(mine, keep, 1000)
|
||||
gone = self.base / "unplugged"
|
||||
app.write_text(json.dumps({"data_dir": str(gone), "data_dir_at": 5000}))
|
||||
self.assertEqual(discovery.data_dir(self.base / "default"), (keep, "settings"))
|
||||
self.assertEqual(Path(self.read(app)["data_dir"]), gone) # the app's file is left alone
|
||||
|
||||
def test_the_same_folder_in_both_changes_nothing(self):
|
||||
mine, app = self.files()
|
||||
folder = self.base / "same"
|
||||
self.put(mine, folder, 1000)
|
||||
self.put(app, folder, 2000)
|
||||
before = app.read_bytes()
|
||||
self.assertEqual(discovery.data_dir(self.base / "default")[0], folder)
|
||||
self.assertEqual(app.read_bytes(), before)
|
||||
|
||||
def test_files_without_a_time_use_the_file_time(self):
|
||||
mine, app = self.files()
|
||||
old, new = self.base / "a", self.base / "b"
|
||||
old.mkdir(), new.mkdir()
|
||||
app.write_text(json.dumps({"data_dir": str(old)}))
|
||||
os.utime(app, (time.time() - 500, time.time() - 500))
|
||||
mine.write_text(json.dumps({"data_dir": str(new)}))
|
||||
self.assertEqual(discovery.data_dir(self.base / "default")[0], new)
|
||||
|
||||
def test_the_apps_own_processes_do_not_sync(self):
|
||||
mine, app = self.files()
|
||||
self.put(mine, self.base / "t", 9000)
|
||||
self.put(app, self.base / "a", 1000)
|
||||
os.environ["STRATA_SETTINGS_FILE"] = str(app)
|
||||
self.assertIsNone(discovery.sync_data_dir())
|
||||
self.assertEqual(Path(self.read(app)["data_dir"]), self.base / "a")
|
||||
|
||||
def test_setup_stamps_a_changed_data_folder(self):
|
||||
mine, _ = self.files()
|
||||
setup.save_settings({"data_dir": str(self.base / "x")})
|
||||
first = self.read(mine)["data_dir_at"]
|
||||
self.assertGreater(first, 0)
|
||||
time.sleep(0.02)
|
||||
setup.save_settings({**self.read(mine), "installs": ["y"]}) # same folder: the time stays
|
||||
self.assertEqual(self.read(mine)["data_dir_at"], first)
|
||||
@@ -23,7 +23,7 @@ STUB = r"""#!/bin/sh
|
||||
# records every call; answers the few read-only queries the entrypoint makes
|
||||
echo "$*" >> "$STUB_LOG"
|
||||
case "$1 $2" in
|
||||
"components engine") if [ "${STUB_ENGINE:-ok}" = ok ]; then echo '{"usable": true}'; else echo '{"usable": false}'; echo "no engine for this card" >&2; fi; exit 0 ;;
|
||||
"components engine") if [ "${STUB_ENGINE:-ok}" = ok ]; then echo "{\"usable\": true, \"backend\": \"${STUB_BACKEND:-}\"}"; else echo '{"usable": false}'; echo "no engine for this card" >&2; fi; exit 0 ;;
|
||||
esac
|
||||
case "$*" in
|
||||
*"--list-presets --output json"*) if [ -n "${STUB_PRESET:-}" ]; then echo '{"presets": [{"name": "docker"}]}'; fi; exit 0 ;;
|
||||
@@ -79,11 +79,13 @@ class Entrypoint(unittest.TestCase):
|
||||
return next(line for line in log.splitlines() if line.startswith("launch --no-tui"))
|
||||
|
||||
def test_settings_become_flags_and_sigterm_stops_cleanly(self):
|
||||
(self.tmp / "models").mkdir()
|
||||
(self.tmp / "models" / "m-00001-of-00002.gguf").write_text("x")
|
||||
p = self.start(MODEL="IQ3_XXS", CONTEXT="64k", PARALLEL="2", VISION="yes", TUNE="quick", GPUS="0,1", PORT="8123", PRESET="office",
|
||||
API_KEY="a-long-enough-key-123456", MODEL_PATH="/models", STRATA_SET="prefill=65536 STRATA_PIN_BY_NEED=1")
|
||||
API_KEY="a-long-enough-key-123456", MODEL_PATH=str(self.tmp / "models"), STRATA_SET="prefill=65536 STRATA_PIN_BY_NEED=1")
|
||||
log = self.wait_for("--show-key")
|
||||
line = self.launch_line(log)
|
||||
for want in ("--access lan", "--port 8123", "--model IQ3_XXS", "--model-path /models", "--context 64k", "--parallel 2",
|
||||
for want in ("--access lan", "--port 8123", "--model IQ3_XXS", "--model-path " + str(self.tmp / "models"), "--context 64k", "--parallel 2",
|
||||
"--vision on", "--gpu 0,1", "--tune quick", "--set prefill=65536", "--set STRATA_PIN_BY_NEED=1",
|
||||
"--save-preset office", "--api-key-env STRATA_LAUNCH_KEY"):
|
||||
self.assertIn(want, line)
|
||||
@@ -166,6 +168,101 @@ class Entrypoint(unittest.TestCase):
|
||||
self.stop(p)
|
||||
self.assertTrue((install / "strata-q2_0.json").exists())
|
||||
|
||||
def test_a_volume_of_the_older_image_is_moved_not_downloaded_again(self):
|
||||
data = self.tmp / "data"
|
||||
(data / "models" / "Qwen3.8-Flash-Next-IQ3_XXS").mkdir(parents=True)
|
||||
shard = data / "models" / "Qwen3.8-Flash-Next-IQ3_XXS" / "a-00001-of-00002.gguf"
|
||||
shard.write_text("weights")
|
||||
(data / "models" / "Qwen3.8-Flash-Next-IQ3_XXS" / "a-00001-of-00002.gguf.done").write_text("x")
|
||||
(data / "packs" / "qwen3.8-flash-next-iq3_xxs").mkdir(parents=True)
|
||||
(data / "packs" / "qwen3.8-flash-next-iq3_xxs" / "experts.bin").write_text("pack")
|
||||
(data / "mtp" / "rt").mkdir(parents=True)
|
||||
(data / "mtp" / "rt" / "experts.bin").write_text("mtp")
|
||||
ino = shard.stat().st_ino
|
||||
p = self.start(MODEL="IQ3_XXS")
|
||||
self.wait_for("--show-key")
|
||||
code, out, err = self.stop(p)
|
||||
new = data / "Strata-data"
|
||||
moved = new / "models" / "Qwen3.8-Flash-Next-IQ3_XXS" / "a-00001-of-00002.gguf"
|
||||
self.assertEqual(moved.read_text(), "weights")
|
||||
self.assertEqual(moved.stat().st_ino, ino) # renamed, not copied
|
||||
self.assertTrue((moved.parent / "a-00001-of-00002.gguf.done").exists())
|
||||
self.assertTrue((new / "packs" / "qwen3.8-flash-next-iq3_xxs" / "experts.bin").exists())
|
||||
self.assertTrue((new / "mtp" / "rt" / "experts.bin").exists())
|
||||
self.assertFalse((data / "models").exists())
|
||||
self.assertIn("moved them into", out)
|
||||
|
||||
def test_a_file_already_in_the_new_place_is_never_overwritten(self):
|
||||
data = self.tmp / "data"
|
||||
(data / "models" / "t").mkdir(parents=True)
|
||||
(data / "models" / "t" / "f.gguf").write_text("old")
|
||||
(data / "Strata-data" / "models" / "t").mkdir(parents=True)
|
||||
(data / "Strata-data" / "models" / "t" / "f.gguf").write_text("new")
|
||||
p = self.start(MODEL="IQ3_XXS")
|
||||
self.wait_for("--show-key")
|
||||
self.stop(p)
|
||||
self.assertEqual((data / "Strata-data" / "models" / "t" / "f.gguf").read_text(), "new") # never overwritten
|
||||
self.assertEqual((data / "models" / "t" / "f.gguf").read_text(), "old")
|
||||
|
||||
def test_run_settings_that_name_another_images_engine_folder_are_made_again(self):
|
||||
install = self.tmp / "data" / "install"
|
||||
install.mkdir(parents=True)
|
||||
here = self.tmp / "opt" / "components" / "engine" / "0.1.46-cuda12"
|
||||
here.mkdir(parents=True)
|
||||
(here / "strata-vision").write_text("x")
|
||||
gone = self.tmp / "opt" / "components" / "engine" / "0.1.46-cuda13"
|
||||
(install / "strata-a.json").write_text('{"exe": "component:strata-engine", "vision": {"exe": "%s/strata-vision"}}' % gone)
|
||||
(install / "strata-b.json").write_text('{"exe": "component:strata-engine", "vision": {"exe": "%s/strata-vision"}}' % here)
|
||||
(install / "strata-c.json").write_text('{"exe": "component:strata-engine", "args": []}')
|
||||
(install / "strata-bad.json").write_text("not json")
|
||||
p = self.start(MODEL="IQ3_XXS")
|
||||
self.wait_for("--show-key")
|
||||
code, out, err = self.stop(p)
|
||||
self.assertFalse((install / "strata-a.json").exists())
|
||||
self.assertTrue((install / "strata-b.json").exists())
|
||||
self.assertTrue((install / "strata-c.json").exists())
|
||||
self.assertTrue((install / "strata-bad.json").exists())
|
||||
self.assertIn("strata-a.json", out)
|
||||
self.assertIn("does not have", out)
|
||||
|
||||
def test_nvidia_card_without_gpu_access_ends_before_any_work(self):
|
||||
dev = self.tmp / "dev"
|
||||
dev.mkdir()
|
||||
r = subprocess.run([SH, str(self.script)], env=self.env(STUB_BACKEND="cuda", STRATA_DEV_DIR=str(dev), MODEL="Q2_0"),
|
||||
capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(r.returncode, 3)
|
||||
self.assertIn("--gpus all", r.stderr)
|
||||
self.assertNotIn("launch --no-tui", self.log.read_text())
|
||||
(dev / "nvidia0").write_text("") # with the device files the start goes on
|
||||
p = self.start(STUB_BACKEND="cuda", STRATA_DEV_DIR=str(dev), MODEL="Q2_0")
|
||||
self.wait_for("launch --no-tui")
|
||||
self.stop(p)
|
||||
|
||||
def test_model_path_that_is_not_there_or_empty_ends_the_start_in_plain_words(self):
|
||||
missing = self.tmp / "nothing-mounted"
|
||||
r = subprocess.run([SH, str(self.script)], env=self.env(MODEL="IQ3_XXS", MODEL_PATH=str(missing)), capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(r.returncode, 2)
|
||||
self.assertIn("is not in the container", r.stderr)
|
||||
self.assertIn("-v /srv/gguf/IQ3_XXS:", r.stderr)
|
||||
empty = self.tmp / "empty"
|
||||
(empty / "IQ3_XXS").mkdir(parents=True)
|
||||
r = subprocess.run([SH, str(self.script)], env=self.env(MODEL="IQ3_XXS", MODEL_PATH=str(empty)), capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(r.returncode, 2)
|
||||
self.assertIn("holds no .gguf files", r.stderr)
|
||||
(empty / "IQ3_XXS" / "a-00001-of-00002.gguf").write_text("x")
|
||||
r = subprocess.run([SH, str(self.script)], env=self.env(MODEL="IQ3_XXS", MODEL_PATH=str(empty)), capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(r.returncode, 2)
|
||||
self.assertIn("Set MODEL_PATH=" + str(empty / "IQ3_XXS"), r.stderr)
|
||||
self.assertNotIn("launch --no-tui", self.log.read_text() if self.log.exists() else "")
|
||||
|
||||
def test_own_files_without_a_model_name_do_not_say_recommended_model(self):
|
||||
(self.tmp / "g").mkdir()
|
||||
(self.tmp / "g" / "m-00001-of-00001.gguf").write_text("x")
|
||||
p = self.start(MODEL_PATH=str(self.tmp / "g"))
|
||||
self.wait_for("--show-key")
|
||||
code, out, err = self.stop(p)
|
||||
self.assertIn("Starting Strata: the model files in " + str(self.tmp / "g"), out)
|
||||
|
||||
def test_other_commands_run_instead_of_the_server(self):
|
||||
r = subprocess.run([SH, str(self.script), "strata", "launch", "--plan", "--model", "q2_0"], env=self.env(), capture_output=True,
|
||||
text=True, timeout=30)
|
||||
|
||||
Reference in new issue
Block a user