From f681b9ad62b39cd1ae50e823c8b2bd871ab77e89 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:08:17 +0100 Subject: [PATCH 01/45] Manual mode: the look-only shell allowlist takes only options known to look (#3975) A command on the allowlist used to run without a card with any option except -delete/-exec/-execdir/-fprint/-fls/-ok. Write modes (sort -o, tree -o, uniq IN OUT), program-execution modes (sort --compress-program, rg --pre, git grep -O), date -s and tail -f got through, and so did git config -e, git branch --set-upstream-to and git remote ... forms. Each command now has a spec of the options and operands that only look (short and long, spelled in full); every other option, abbreviation or attached form asks. git subcommands have the same specs, a branch/tag name is taken only with a list option, git config only reads with --get. date takes only +FORMAT operands, uniq at most one operand, hostname none. less and more leave the list. Quoted texts are checked as operands too. `du -sh` no longer trips the 'sh' word check. Tests: apps/host/tests/gate-readonly.test.mjs (deny and allow cases for options, operands, spellings, quoting; every listed command asks for an unknown option). --- apps/host/server/agent/README.md | 2 +- .../host/server/agent/plugins/strata-gate.mjs | 236 +++++++++++++++--- apps/host/tests/gate-readonly.test.mjs | 148 +++++++++++ docs/SAFETY.md | 4 +- 4 files changed, 355 insertions(+), 35 deletions(-) create mode 100644 apps/host/tests/gate-readonly.test.mjs diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.md index b05bebcf..5afd94c1 100644 --- a/apps/host/server/agent/README.md +++ b/apps/host/server/agent/README.md @@ -61,7 +61,7 @@ The chat's Mode menu is real Harness behaviour. Each turn the page sends the cha | Bypass | `strata-bypass` | `danger-full-access` | `never` | Full access without prompts, as before. | - Manual relies on the gate, so a Manual turn does not start unless the bridge has confirmed the gate is loaded (`/strata-gate` command): without it Manual would be an open sandbox that nobody asks about. -- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked; MCP and unknown tools ask. +- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked, each only with the options listed for it in `strata-gate.mjs` (an unknown option, or one that writes, runs a program, sets something or never ends, asks); MCP and unknown tools ask. - Web search and web pages (`web_search`, `web_fetch`) ask once per chat in Manual, not once per call. The gate asks through the approval service itself (`webDecision`: "The assistant wants to search the web for: ... Search words go to ." / "... open the web page ..."), remembers a yes for the chat (a helper agent shares its chat's answer, and two searches started together share one card), and on a no gives the model `WEB_REFUSAL` ("The person did not allow web access ... Go on without it and say so."). Plan and Bypass are unchanged. Settings -> Tools has a switch, "Let the assistant search the web without asking" (off by default, `webWithoutAsking` in `tools-settings.mjs`, passed to the gate as `config.web.skipAsk`), that skips the question in Manual. A scheduled task has nobody at the card, so its web call is answered no unless that switch is on. Tests: `tests/web-ask.test.mjs`. - The mode is read once per turn; an unknown or missing value is Manual. diff --git a/apps/host/server/agent/plugins/strata-gate.mjs b/apps/host/server/agent/plugins/strata-gate.mjs index 96e59221..098ceea8 100644 --- a/apps/host/server/agent/plugins/strata-gate.mjs +++ b/apps/host/server/agent/plugins/strata-gate.mjs @@ -48,25 +48,196 @@ export const READ_ONLY_TOOLS = new Set([ const SHELL_TOOLS = new Set(['pwsh', 'bash']); -/** Commands that only look. Matched against the first word of every pipeline segment. */ -const SAFE_COMMANDS = new Set([ - // PowerShell - 'get-childitem', 'gci', 'ls', 'dir', 'get-content', 'gc', 'cat', 'type', 'get-item', 'gi', 'get-location', 'pwd', 'gl', - 'select-string', 'sls', 'measure-object', 'measure', 'select-object', 'select', 'where-object', 'where', 'sort-object', 'sort', - 'format-table', 'ft', 'format-list', 'fl', 'out-string', 'test-path', 'resolve-path', 'get-filehash', 'get-date', 'get-command', - 'get-process', 'get-itemproperty', 'write-output', 'echo', 'hostname', 'whoami', 'get-host', 'get-psdrive', 'get-help', - 'group-object', 'group', 'convertto-json', 'convertfrom-json', 'select-xml', 'compare-object', 'get-unique', 'tee-object-none', - // POSIX - 'head', 'tail', 'wc', 'grep', 'rg', 'egrep', 'fgrep', 'stat', 'file', 'du', 'df', 'uname', 'which', 'basename', 'dirname', - 'realpath', 'readlink', 'sort', 'uniq', 'cut', 'tr', 'less', 'more', 'date', 'id', 'env-none', 'tree', -]); +/** + * Which shell commands run without a card in Manual mode, and with which options. Safe by construction (#3975): a command is on the list WITH the + * options that are known to only look. Every other option, long or short, abbreviated or attached, makes the command ask. So a write mode + * (`sort -o`, `tree -o`, `uniq in out`), a program-execution mode (`sort --compress-program`, `rg --pre`, `git grep -O`), a setting mode + * (`date -s`) or one that never ends (`tail -f`) cannot slip in, and a word added to the list later starts with no options at all. + * + * A spec says what one command accepts: + * f short options without a value (letters, so `-la` is `-l -a`) v short options that need a value (`-k2`, `-k 2`) + * vn the same, and the value must be a number o short options with an optional value that must be attached (`-Iseconds`) + * n a bare `-5` is allowed l long options (`--name`, `--name=value`), spelled in full + * lv long options that need a value (`--name=value`, `--name value`) ps PowerShell parameter names, lower case, spelled in full + * max how many operands (files, patterns) are allowed op a check for each operand + * post a last check from the options seen and the operand count + */ +const words = (text) => (text ? text.trim().split(/\s+/) : []); +const spec = ({ f = '', v = '', vn = '', o = '', n = false, l = '', lv = '', ps = '', max = Infinity, op = null, post = null }) => + ({ f, v, vn, o, n, l: new Set(words(l)), lv: new Set(words(lv)), ps: ps ? new Set([...words(ps), ...PS_COMMON]) : null, max, op, post }); +/** Parameters every cmdlet has that only change how errors and warnings show. (-Debug asks a question and -OutVariable sets one: not listed.) */ +const PS_COMMON = ['erroraction', 'ea', 'warningaction', 'wa', 'informationaction', 'ia', 'verbose', 'vb']; +const NUMBER = /^[+-]?\d+[A-Za-z]{0,3}$/; + +/** What `ls`, `dir`, `gci` and `Get-ChildItem` take. */ +const LS = { f: 'aAbBcdDFgGhHiklLmnNopqQrRsStuUvxX1CZ', v: 'ITw', ps: 'path literalpath filter include exclude recurse depth name force file directory hidden readonly system attributes', + l: 'all almost-all human-readable recursive directory classify reverse size inode dereference color group-directories-first sort time time-style block-size indicator-style si numeric-uid-gid no-group literal hide ignore quote-name escape author file-type full-time width tabsize' }; +/** What `cat`, `type`, `gc` and `Get-Content` take. (-Wait never ends, so it is not here.) */ +const CAT = { f: 'AbeEnstTuv', ps: 'path literalpath totalcount tail head raw encoding readcount force filter include exclude delimiter stream asbytestream', + l: 'show-all number-nonblank show-ends number squeeze-blank show-tabs show-nonprinting' }; +const MEASURE = { ps: 'property sum average maximum minimum line word character ignorewhitespace inputobject standarddeviation allstats' }; +const SELECT = { ps: 'first last skip skiplast property expandproperty unique index excludeproperty inputobject' }; +const WHERE = { ps: 'property value inputobject eq ne gt lt ge le like notlike match notmatch contains notcontains in notin is isnot ceq cne cgt clt cge cle clike cnotlike cmatch cnotmatch ccontains cnotcontains cin cnotin' }; +const GROUP = { ps: 'property noelement ashashtable asstring casesensitive inputobject culture' }; +const FT = { ps: 'property autosize wrap hidetableheaders groupby view force expand repeatheader displayerror showerror inputobject' }; +const FL = { ps: 'property view groupby expand force displayerror showerror inputobject' }; +const SLS = { ps: 'pattern path literalpath simplematch casesensitive context list notmatch quiet allmatches include exclude encoding raw inputobject culture noemphasis' }; +const GETITEM = { ps: 'path literalpath name filter include exclude force stream' }; +const GETLOC = { ps: 'psprovider psdrive stack stackname' }; +const ECHO = { f: 'neE', ps: 'inputobject noenumerate' }; +/** The GNU/BSD grep family. */ +const GREP = { f: 'aiIlLcnvwHhEFGPqrRsTUyzZbxo', v: 'efdD', vn: 'ABCm', n: true, + l: 'extended-regexp fixed-strings basic-regexp perl-regexp ignore-case no-ignore-case word-regexp line-regexp invert-match count color colour files-with-matches files-without-match max-count only-matching quiet silent no-messages byte-offset with-filename no-filename label line-buffered initial-tab null after-context before-context context text recursive dereference-recursive include exclude exclude-dir binary-files line-number null-data no-group-separator group-separator regexp file directories devices binary' }; + +/** Commands that only look, each with the options that are known to be harmless. Matched against the first word of every pipeline segment. */ +const SPECS = new Map(); +const add = (names, s) => { for (const name of words(names)) SPECS.set(name, spec(s)); }; +// PowerShell +add('get-childitem gci', { ps: LS.ps }); +add('ls dir', LS); +add('get-content gc', { ps: CAT.ps }); +add('cat type', CAT); +add('get-item gi get-itemproperty', GETITEM); +add('get-location gl', GETLOC); +add('pwd', { ...GETLOC, f: 'LP' }); +add('select-string sls', SLS); +add('measure-object measure', MEASURE); +add('select-object select', SELECT); +add('where-object where', WHERE); +add('sort-object', { ps: 'property descending unique top bottom casesensitive culture stable inputobject' }); +add('format-table ft', FT); +add('format-list fl', FL); +add('out-string', { ps: 'stream width inputobject' }); +add('test-path', { ps: 'path literalpath pathtype isvalid filter include exclude olderthan newerthan' }); +add('resolve-path', { ps: 'path literalpath relative relativebasepath force' }); +add('get-filehash', { ps: 'path literalpath algorithm' }); +add('get-date', { ps: 'format uformat date asutc displayhint year month day hour minute second millisecond' }); +add('get-command', { ps: 'name commandtype module all syntax listimported totalcount noun verb fullyqualifiedmodule parametername parametertype' }); +add('get-process', { ps: 'name id includeusername module fileversioninfo inputobject' }); +add('write-output', { ps: ECHO.ps }); +add('echo', ECHO); +add('get-host', { ps: '' }); +add('get-psdrive', { ps: 'name psprovider scope literalname' }); +add('get-help', { ps: 'name full detailed examples parameter category component functionality role' }); +add('group-object group', GROUP); +add('convertto-json', { ps: 'depth compress enumsasstrings inputobject asarray escapehandling' }); +add('convertfrom-json', { ps: 'ashashtable depth inputobject noenumerate' }); +add('select-xml', { ps: 'xml path literalpath xpath content namespace' }); +add('compare-object', { ps: 'referenceobject differenceobject property includeequal excludedifferent passthru syncwindow casesensitive culture' }); +add('get-unique', { ps: 'inputobject asstring caseinsensitive onetype' }); +// POSIX. `sort` and `date` take no PowerShell names here: `sort -o FILE` writes, `date -s` sets the clock, and a PowerShell-looking `-Second` or `-Top` +// must not be read by a real sort or date as one of those. (Sort-Object and Get-Date above are the PowerShell forms.) +add('head', { f: 'qvz', vn: 'nc', n: true, l: 'quiet silent verbose zero-terminated lines bytes' }); +add('tail', { f: 'qvz', vn: 'nc', n: true, l: 'quiet silent verbose zero-terminated lines bytes' }); // no -f, -F, --follow, --retry, --pid, -s: those never end +add('wc', { f: 'lwcmL', l: 'lines words bytes chars max-line-length' }); +add('grep egrep fgrep', GREP); +add('rg', { // no --pre, --pre-glob, --hostname-bin (they run a program) and no -z/--search-zip (it runs decompressors) + f: 'iIsSnNHlcwFxvUoLaquhVpbP', v: 'efgtTr', vn: 'ABCjdMm', + l: 'ignore-case no-ignore-case smart-case case-sensitive fixed-strings word-regexp line-regexp invert-match count count-matches files-with-matches files-without-match files type-list hidden no-ignore no-ignore-vcs no-ignore-parent no-ignore-dot no-ignore-global no-ignore-messages follow line-number no-line-number with-filename no-filename column heading no-heading null only-matching quiet text multiline multiline-dotall pcre2 no-messages json stats trim unrestricted binary no-config vimgrep pretty byte-offset passthru crlf one-file-system no-unicode regexp file glob iglob type type-not max-count max-depth maxdepth context after-context before-context color replace threads sort sortr max-filesize max-columns path-separator encoding engine ignore-file glob-case-insensitive no-glob-case-insensitive' }); +add('stat', { f: 'LtxlnqrsFf', v: 'c', l: 'dereference file-system terse format printf' }); +add('file', { f: 'bhikLnNrvI', l: 'brief dereference no-dereference mime mime-type mime-encoding keep-going no-pad no-buffer raw' }); // no -C, -m, -f, -P (they write or read other files), no -z/-s/-p (they run decompressors, read devices, reset times) +add('du', { f: 'abchHklmsxLPSD0', v: 'tB', vn: 'd', l: 'all apparent-size bytes total dereference-args human-readable si summarize one-file-system dereference no-dereference separate-dirs count-links inodes null max-depth threshold block-size time time-style exclude' }); +add('df', { f: 'ahHiklmPTv', v: 'txB', l: 'all human-readable si inodes local portability print-type total sync no-sync output block-size type exclude-type' }); +add('uname', { f: 'asnrvmpio', max: 0, l: 'all kernel-name nodename kernel-release kernel-version machine processor hardware-platform operating-system' }); +add('which', { f: 'as', l: 'all' }); +add('basename', { f: 'az', v: 's', l: 'multiple zero suffix' }); +add('dirname', { f: 'z', l: 'zero' }); +add('realpath', { f: 'emsqzLP', l: 'canonicalize-existing canonicalize-missing no-symlinks quiet zero strip logical physical relative-to relative-base' }); +add('readlink', { f: 'femnqsvz', l: 'canonicalize canonicalize-existing canonicalize-missing no-newline quiet silent verbose zero' }); +add('sort', { f: 'bdfghiMnRrsuVzmcC', v: 'kt', l: 'ignore-leading-blanks dictionary-order ignore-case general-numeric-sort human-numeric-sort ignore-nonprinting month-sort numeric-sort random-sort reverse stable unique version-sort zero-terminated check merge sort field-separator key' }); +// uniq's second operand is its OUTPUT file, so it takes at most one. +add('uniq', { f: 'cdDuiz', vn: 'fsw', max: 1, l: 'count repeated all-repeated unique ignore-case skip-fields skip-chars check-chars zero-terminated group' }); +add('cut', { f: 'snz', v: 'bcfd', l: 'complement only-delimited zero-terminated bytes characters fields delimiter output-delimiter' }); +add('tr', { f: 'cCdst', max: 2 }); +add('date', { f: 'uR', o: 'I', v: 'dr', lv: 'date reference', l: 'utc universal rfc-email rfc-2822 iso-8601 rfc-3339', + op: (word) => word.startsWith('+') }); // a bare operand like 1026120026 SETS the clock; only +FORMAT is a format +add('id', { f: 'ugGnrazZ', l: 'user group groups name real context zero' }); +add('hostname', { f: 'sfiIdaAyv', max: 0 }); // `hostname NAME` renames the machine +add('whoami', { l: 'help version', op: (word) => /^\/(all|user|groups|priv|upn|fqdn|logonid|nh)$/i.test(word) }); +add('tree', { f: 'adfilpsugDFqNQrtvxCnASUchJX', v: 'LPIHT', vn: '', l: 'help version filelimit charset sort timefmt noreport dirsfirst filesfirst prune du si gitignore matchdirs ignore-case inodes device nolinks' }); // no -o, no -R +// `less` and `more` are not here: they wait for keys, and `less` can run commands. + +/** The names that run without a card (for the tests). */ +export const readOnlyCommandNames = () => [...SPECS.keys()]; + +/** git subcommands that only read, with the options they may take. */ +const GIT_VIEW = 'oneline graph decorate no-decorate all branches tags remotes stat shortstat numstat dirstat name-only name-status patch no-patch raw summary compact-summary abbrev-commit no-abbrev-commit abbrev reverse follow no-merges merges first-parent full-history simplify-by-decoration simplify-merges ancestry-path left-right left-only right-only cherry-pick cherry-mark cherry topo-order date-order author-date-order relative-date all-match invert-grep regexp-ignore-case extended-regexp fixed-strings perl-regexp no-color color color-words word-diff word-diff-regex minimal patience histogram diff-algorithm check exit-code quiet cached staged merge-base no-index no-ext-diff no-textconv find-renames find-copies find-copies-harder no-renames ignore-space-change ignore-all-space ignore-space-at-eol ignore-blank-lines ignore-cr-at-eol function-context show-function unified inter-hunk-context src-prefix dst-prefix no-prefix full-index binary text source use-mailmap mailmap no-mailmap log-size notes no-notes show-signature diff-merges boundary children parents no-walk sparse date format pretty author committer grep since until after before max-count skip min-parents max-parents diff-filter encoding stat-width stat-name-width stat-graph-width stat-count count'; +const LISTING = ['l', 'list', 'contains', 'no-contains', 'merged', 'no-merged', 'points-at']; +const GIT = new Map(Object.entries({ + status: spec({ f: 'sbvz', o: 'u', l: 'short branch porcelain long ignored untracked-files ignore-submodules renames no-renames find-renames show-stash ahead-behind no-ahead-behind column no-column verbose null' }), + log: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + diff: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + show: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + 'rev-list': spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + shortlog: spec({ f: 'sneciw', n: false, l: `${GIT_VIEW} summary numbered email committer group` }), + // Listing forms only. A name with no list option would CREATE a branch or a tag, and the options that change things are not here. + branch: spec({ f: 'avri', l: 'list all remotes verbose show-current ignore-case contains no-contains merged no-merged points-at sort format abbrev no-abbrev color no-color column no-column omit-empty', + post: (seen, count) => count === 0 || LISTING.some(name => seen.has(name)) }), + tag: spec({ f: 'li', o: 'n', l: 'list sort contains no-contains merged no-merged points-at format column no-column ignore-case omit-empty color no-color', + post: (seen, count) => count === 0 || LISTING.some(name => seen.has(name)) }), + remote: spec({ f: 'v', l: 'verbose', max: 0 }), + // `git config KEY` reads and `git config KEY VALUE` writes, so a key is only taken with --get; no --edit, --add, --unset, --file. + config: spec({ f: 'lz', l: 'list get get-all get-regexp show-origin show-scope local global system worktree bool int bool-or-int path expiry-date type null name-only includes no-includes', lv: 'default', + post: (seen, count) => (count > 0 ? ['get', 'get-all', 'get-regexp'].some(name => seen.has(name)) : seen.has('list') || seen.has('l')) }), + 'rev-parse': spec({ f: 'q', l: 'show-toplevel git-dir git-common-dir absolute-git-dir abbrev-ref symbolic symbolic-full-name short verify is-inside-work-tree is-inside-git-dir is-bare-repository is-shallow-repository show-prefix show-cdup show-superproject-working-tree all branches tags remotes quiet revs-only no-revs flags no-flags local-env-vars show-object-format path-format', lv: 'default git-path' }), + 'ls-files': spec({ f: 'cdmoiskuzvtfD', l: 'cached deleted modified others ignored stage directory unmerged killed no-empty-directory error-unmatch exclude-standard exclude full-name eol deduplicate recurse-submodules sparse abbrev resolve-undo format' }), + 'ls-tree': spec({ f: 'rtdlz', l: 'name-only name-status long full-name full-tree object-only abbrev format' }), + blame: spec({ f: 'wMCespltbfnc', v: 'L', l: 'porcelain line-porcelain incremental show-email show-name show-number date root abbrev' }), + describe: spec({ l: 'all tags always long dirty broken contains abbrev match exclude first-parent exact-match candidates' }), + 'cat-file': spec({ f: 'tsep', l: 'batch batch-check batch-all-objects allow-unknown-type buffer unordered follow-symlinks mailmap use-mailmap' }), // no --textconv, --filters + // No -O / --open-files-in-pager: they run a program on the matches. + grep: spec({ f: 'aiIlLcnvwHhEFGPqpWrzUo', v: 'e', vn: 'ABCm', n: true, l: 'no-index untracked cached no-exclude-standard exclude-standard recurse-submodules text ignore-case word-regexp invert-match full-name extended-regexp basic-regexp perl-regexp fixed-strings line-number column files-with-matches name-only files-without-match count null only-matching quiet no-color color break heading show-function function-context all-match and or not max-depth max-count threads after-context before-context context recursive no-recursive' }), +})); + +/** + * One command's words against its spec: every option has to be one the spec knows (anything else is not understood, so it asks). + * @param {ReturnType} sp + * @param {{t:string,q:boolean}[]} args the words after the command; q marks a quoted text, which is data and never an option + */ +function argumentsAreSafe(sp, args) { + const seen = new Set(); + let operands = 0, ended = false; + const operand = (arg) => { operands++; return operands <= sp.max && (!sp.op || sp.op(arg.t, arg.q)); }; + const valueOf = (i, numeric) => { // the next word as an option's value; it can be a quoted text, a number, or a word that is not an option + const arg = args[i + 1]; + if (!arg) return false; + return numeric ? NUMBER.test(arg.t) : arg.q || !arg.t.startsWith('-') || NUMBER.test(arg.t); + }; + for (let i = 0; i < args.length; i++) { + const { t, q } = args[i]; + if (q || ended || t === '-' || t[0] !== '-') { if (!operand(args[i])) return false; continue; } + if (t === '--') { ended = true; continue; } + if (t.startsWith('--')) { + const eq = t.indexOf('='); + const name = eq < 0 ? t.slice(2) : t.slice(2, eq); + if (sp.l.has(name)) { seen.add(name); continue; } + if (sp.lv.has(name)) { seen.add(name); if (eq < 0) { if (!valueOf(i, false)) return false; i++; } continue; } + return false; + } + if (sp.ps) { + const named = /^-([A-Za-z][A-Za-z0-9]*)(?::|$)/.exec(t); + if (named && sp.ps.has(named[1].toLowerCase())) { seen.add(named[1].toLowerCase()); continue; } + } + if (sp.n && /^-\d+$/.test(t)) continue; + for (let j = 1; j < t.length; j++) { + const c = t[j]; + if (sp.f.includes(c)) { seen.add(c); continue; } + if (sp.o.includes(c)) { seen.add(c); break; } + const numeric = sp.vn.includes(c); + if (!numeric && !sp.v.includes(c)) return false; + seen.add(c); + const rest = t.slice(j + 1); + if (rest) { if (numeric && !NUMBER.test(rest)) return false; } else { if (!valueOf(i, numeric)) return false; i++; } + break; + } + } + return sp.post ? sp.post(seen, operands) : true; +} -/** git subcommands that only read. */ -const SAFE_GIT = new Set(['status', 'log', 'diff', 'show', 'branch', 'rev-parse', 'ls-files', 'blame', 'describe', 'remote', 'tag', 'shortlog', 'rev-list', 'cat-file', 'grep', 'ls-tree', 'config']); const SAFE_VERSION = /^(node|python|python3|py|npm|pnpm|git|dotnet|cargo|rustc|go|java|pip|pip3)\s+(--version|-v|-version|version)$/i; -/** Anything that can chain, redirect, expand or start something else is not read-only. */ -const UNSAFE_SYNTAX = /[;&<>`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd-content\b|\binvoke-|\biex\b|\bstart-|\bnew-|\bremove-|\bcopy-|\bmove-|\brename-|\bclear-|\bset-|\bpush-|\bexpand-|\bsave-|\binstall-|\bcurl\b|\bwget\b|\bsudo\b|\bsh\b|\bbash\b|\bpwsh\b|\bpowershell\b|\bcmd\b|-exec\b|-delete\b|-execdir\b/i; +/** Anything that can chain, redirect, expand or start something else is not read-only. (`sh` as a word, not inside an option like `du -sh`.) */ +const UNSAFE_SYNTAX = /[;&<>`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd-content\b|\binvoke-|\biex\b|\bstart-|\bnew-|\bremove-|\bcopy-|\bmove-|\brename-|\bclear-|\bset-|\bpush-|\bexpand-|\bsave-|\binstall-|\bcurl\b|\bwget\b|\bsudo\b|(?`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd * inside double quotes a $ or a backtick expands (a variable, a sub-command), and an unterminated quote means the text was not understood. * Either one gives null, and the command asks as before. * @param {string} text + * @param {string[]} [quoted] when given, receives the text inside each quote, in order (the checks on operands read it) * @returns {string|null} */ -export function maskQuotes(text) { +export function maskQuotes(text, quoted) { let out = ''; for (let i = 0; i < text.length; i++) { const c = text[i]; @@ -91,13 +263,14 @@ export function maskQuotes(text) { const before = text[i - 1], after = text[end + 1]; if ((before !== undefined && !/[\s|]/.test(before)) || (after !== undefined && !/[\s|]/.test(after)) || text[i + 1] === '-') return null; out += '"_"'; + quoted?.push(text.slice(i + 1, end)); i = end; } return out; } /** - * Whether a shell command only reads. Conservative by design: one unrecognised word and the answer is no. + * Whether a shell command only reads. Conservative by design: one unrecognised word or option and the answer is no. * Quoted text is data and is looked at after it has been set aside (maskQuotes): Get-ChildItem "C:\Users\x\Q&A" only lists. * @param {string} command * @returns {boolean} @@ -106,24 +279,21 @@ export function isReadOnlyShell(command) { const text = String(command ?? '').trim(); if (!text || text.length > 600) return false; if (SAFE_VERSION.test(text)) return true; - const masked = maskQuotes(text); + const quoted = []; + const masked = maskQuotes(text, quoted); if (masked === null || UNSAFE_SYNTAX.test(masked)) return false; - const segments = masked.split('|').map(s => s.trim()); - return segments.every((segment) => { - if (!segment) return false; - const words = segment.split(/\s+/); - const first = words[0].toLowerCase().replace(/^\.\\/, ''); + let next = 0; + const tokens = masked.split('|').map(segment => segment.trim()).map(segment => words(segment).map(w => (w === '"_"' ? { t: quoted[next++] ?? '', q: true } : { t: w, q: false }))); + return tokens.every((segment) => { + if (!segment.length || segment[0].q) return false; + const first = segment[0].t.toLowerCase().replace(/^\.\\/, ''); if (first === 'git') { - // `git config` and `git tag`/`branch`/`remote` can write when given a value; only the bare listing forms are safe. - const sub = (words[1] ?? '').toLowerCase(); - if (!SAFE_GIT.has(sub)) return false; - if (['config', 'tag', 'branch', 'remote'].includes(sub)) { - const rest = words.slice(2).filter(w => !w.startsWith('-') || /^(-l|-a|-v|-vv|--list|--all|--show-current|--get|--get-all)$/i.test(w)); - return rest.length === 0 || (sub === 'config' && words[2] === '--get') || (sub === 'remote' && words[2] === '-v'); - } - return !words.some(w => /^--(output|ext-diff|textconv)\b/i.test(w)); + const sub = segment[1]; + const sp = sub && !sub.q ? GIT.get(sub.t) : null; + return !!sp && argumentsAreSafe(sp, segment.slice(2)); } - return SAFE_COMMANDS.has(first) && !words.some(w => /^-(delete|exec|execdir|fprint|fls|ok)$/i.test(w)); + const sp = SPECS.get(first); + return !!sp && argumentsAreSafe(sp, segment.slice(1)); }); } diff --git a/apps/host/tests/gate-readonly.test.mjs b/apps/host/tests/gate-readonly.test.mjs new file mode 100644 index 00000000..5fd9d8e8 --- /dev/null +++ b/apps/host/tests/gate-readonly.test.mjs @@ -0,0 +1,148 @@ +// #3975 (P0): Manual mode's "read-only" shell allowlist must be safe by construction. A command without a card may only use options that are known to +// look and nothing else. The first block is what the issue reported (write and program-execution modes of allowlisted commands), the rest is the +// same class: options, operands, spellings and quoting. The last block is the commands people really type, which must keep running unasked. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { isReadOnlyShell, maskQuotes, readOnlyCommandNames } from '../server/agent/plugins/strata-gate.mjs'; + +const denied = (list) => { for (const c of list) assert.equal(isReadOnlyShell(c), false, `must ask: ${c}`); }; +const allowed = (list) => { for (const c of list) assert.equal(isReadOnlyShell(c), true, `must run unasked: ${c}`); }; + +test('#3975: the five confirmed cases and the rest of the issue table now ask', () => { + denied([ + 'sort --compress-program=sh a.txt', 'sort --compress-program sh a.txt', 'sort -o out.txt a.txt', 'sort --output=out.txt a.txt', + 'rg --pre sh pattern', 'rg --pre=sh pattern', + 'git grep -Osh pattern', 'git grep -O sh pattern', 'git grep --open-files-in-pager=sh pattern', + 'uniq in.txt out.txt', + 'tree -o out.txt', 'file -C -m x', 'date -s 12:00', 'date --set=12:00', 'tail -f app.log', + ]); +}); + +test('#3975: other spellings of the same options (attached, clustered, abbreviated, repeated) ask', () => { + denied([ + 'sort -oout.txt a.txt', 'sort -ro out.txt a.txt', 'sort -nro out.txt a.txt', 'sort --out=out.txt a.txt', 'sort --outp out.txt a.txt', + 'sort --comp=sh a.txt', 'sort -T /tmp a.txt', 'sort --files0-from=list a.txt', 'sort -n -u -o out a', + 'rg --pre-glob "*" x', 'rg --hostname-bin=sh x', 'rg -z x', 'rg --search-zip x', 'rg -uz x', 'rg --pre sh --files', + 'git grep -O"sh" x', 'git grep -nOsh x', 'git grep -O x', 'git grep --open x', 'git grep -l --open-files-in-pager=sh x', + 'uniq - out.txt', 'uniq -c in.txt out.txt', 'uniq -i -u in out', + 'tree -oout.txt', 'tree -a -o out.txt', 'tree -R', 'tree --output=out', + 'file -C', 'file --compile x', 'file -m magic x', 'file -f list', 'file -bC x', 'file --magic-file=x y', + 'date -sMonth', 'date -u -s now', 'date --set now', 'date 102612002026', 'date -u 1026', 'date -d now 1026', + 'tail -F app.log', 'tail --follow app.log', 'tail --follow=name app.log', 'tail -fn5 app.log', 'tail -n 1 -f app.log', 'tail --retry x', 'tail -f -n 1 x', + 'tail --pid=1 -f x', 'tail -s 1 x', + 'head -f x', 'wc --files0-from=list', 'du --files0-from=list', 'du -X file', 'stat --foo x', 'ls --foo', 'ls -@', 'cat -@ x', 'grep --foo x y', + 'hostname newname', 'hostname -F file', 'uname -n box', 'uname box', + ]); +}); + +test('#3975: git subcommands that write or run something when given the right option ask', () => { + denied([ + 'git diff --output=out.txt', 'git diff --out=out.txt', 'git log --output=out.txt', 'git show --output out HEAD', 'git log --ext-diff', 'git diff --ext-diff', + 'git diff --textconv', 'git log --textconv', 'git grep --textconv x', 'git cat-file --textconv HEAD:a', 'git cat-file --filters HEAD:a', 'git log --exec=sh', + 'git config -e', 'git config --edit', 'git config --global --edit', 'git config --global user.name x', 'git config user.name x', 'git config --unset user.name', + 'git config --add a.b c', 'git config --replace-all a.b c', 'git config --file x --list', 'git config --get', 'git config --get a --edit', + 'git branch --set-upstream-to=origin/main', 'git branch --unset-upstream', 'git branch -u origin/main', 'git branch -d x', 'git branch -D x', 'git branch -m new', + 'git branch --edit-description', 'git branch newbranch', 'git branch -a newbranch', 'git branch --track x origin/x', + 'git tag v1', 'git tag -a v1', 'git tag -d v1', 'git tag -s v1', 'git tag -v v1', 'git tag -a -m msg v1', 'git tag --edit', + 'git remote add o u', 'git remote show origin', 'git remote update', 'git remote prune origin', 'git remote set-url o u', 'git remote rename a b', + 'git -c core.pager=sh log', 'git --paginate log', 'git -C x status', 'git --git-dir=x log', 'git -p log', + 'git commit', 'git push', 'git checkout x', 'git stash', 'git reset', 'git clean -n', 'git fetch', 'git pull', 'git rev-parse --parseopt', 'git ls-files -x', + 'git status --foo', 'git log --foo', 'git blame --contents=x a', 'git diff -O orderfile', 'git diff --no-pager', + ]); +}); + +test('#3975: PowerShell commands: parameters that wait forever, reach other machines or open windows ask', () => { + denied([ + 'Get-Content a.txt -Wait', 'gc a.txt -Wait', 'type a.txt -Wait', 'Get-Process -ComputerName other', 'Get-Help Get-ChildItem -Online', 'Get-Help Get-ChildItem -ShowWindow', + 'Select-String -Pattern x -Foo', 'Get-ChildItem -Rec', 'Get-ChildItem -Debug', 'Get-ChildItem -OutVariable x', 'Get-ChildItem -ErrorVariable x', + 'Sort-Object -Foo', 'Get-Date -Foo', 'Get-FileHash a.txt -InputStream x', + ]); +}); + +test('#3975: pagers and anything not on the list ask', () => { + denied(['less a.txt', 'more a.txt', 'less -o log a.txt', 'find . -name x', 'xargs ls', 'awk 1 a', 'sed s/a/b/ a', 'env', 'tee a', 'printenv', 'mv a b', 'cp a b', 'touch a', 'mkdir a', 'dd if=a of=b']); +}); + +test('#3975: quoting cannot hide an option or an operand', () => { + denied([ + 'sort "--output=out" a', 'sort --out"put"=out a', 'sort --"output"=out a', "sort '-o' out a", 'sort -"o" out a', 'sort -o"out" a', 'sort --compress-program="sh" a', + 'rg --pre "sh" x', "rg --pre 'sh' x", 'git grep -O"sh" x', 'git grep "-Osh" x', + 'uniq a "b"', 'uniq "a" "b"', "uniq 'a' 'b'", 'date "1026120026"', "date '1026'", 'date "-s" now', 'date "-s now"', + 'tail "-f" x', "tail '-f' x", 'tail -n 1 "-f" x', + 'tree "-o" x', 'file "-C" x', 'git diff "--output=out.txt"', 'git "diff" --output=x', + // a quoted dash value is never taken for a value of a flag that wants a number + 'head -n "-f" x', + ]); +}); + +test('#3975: operands that would write or set something ask (uniq output file, date setting, hostname)', () => { + denied(['uniq a b', 'uniq a b c', 'date 1231', 'date 12311200', 'hostname a', 'whoami /foo', 'tr a b c', 'git tag v1.0', 'git branch topic']); +}); + +test('#3975: every command on the list asks for an unknown option, long or short', () => { + const names = readOnlyCommandNames(); + assert.ok(names.length > 40, 'the list is not empty'); + for (const name of names) { + assert.equal(isReadOnlyShell(`${name} -@`), false, `${name} -@`); + assert.equal(isReadOnlyShell(`${name} --zz-no-such-option`), false, `${name} --zz-no-such-option`); + assert.equal(isReadOnlyShell(`${name} --zz-no-such-option=1 x`), false, `${name} --zz-no-such-option=1 x`); + assert.equal(isReadOnlyShell(`Get-ChildItem | ${name} -@`), false, `piped ${name} -@`); + } + for (const sub of ['status', 'log', 'diff', 'show', 'branch', 'rev-parse', 'ls-files', 'blame', 'describe', 'remote', 'tag', 'shortlog', 'rev-list', 'cat-file', 'grep', 'ls-tree', 'config']) { + assert.equal(isReadOnlyShell(`git ${sub} --zz-no-such-option`), false, `git ${sub} --zz-no-such-option`); + assert.equal(isReadOnlyShell(`git ${sub} -@`), false, `git ${sub} -@`); + } +}); + +test('#3975: commands people really type still run without a card', () => { + allowed([ + // sort, uniq, head, tail, wc, cut, tr + 'sort a.txt', 'sort -r a.txt', 'sort -n -k 2 a.txt', 'sort -u -t, -k2,2 a.txt', 'sort -nr a.txt', 'sort -k2,2nr a.txt', 'sort --reverse --numeric-sort a.txt', + 'uniq', 'uniq -c', 'uniq -c a.txt', 'uniq -d a.txt', 'uniq -f 1 a.txt', 'sort a.txt | uniq -c | sort -nr | head -5', + 'head a.txt', 'head -5 a.txt', 'head -n 5 a.txt', 'head -n5 a.txt', 'head -n -5 a.txt', 'head -c 100 a.txt', 'tail a.txt', 'tail -20 a.txt', 'tail -n 20 a.txt', 'tail -n +5 a.txt', 'tail -c 100 a.txt', + 'wc -l a.txt', 'wc -w a.txt', 'cat a.txt | wc -l', 'cut -d, -f1,3 a.txt', 'cut -c1-10 a.txt', 'tr a-z A-Z', 'tr -d "\\r"', 'tr -s " "', + // grep family and rg + 'grep foo a.txt', 'grep -rn foo src', 'grep -c foo a.txt', 'grep -E "a|b" a.txt', 'grep -A 3 foo a.txt', 'grep -i -v foo a.txt', 'grep -rl --include "*.js" foo .', 'egrep -n foo a.txt', 'fgrep -x foo a.txt', + 'rg foo', 'rg -n -i foo src', 'rg -l --type js foo', 'rg --files -g "*.md"', 'rg -C 3 foo', "rg foo -g '!node_modules'", 'rg -e foo -e bar', 'rg --hidden --no-ignore foo', 'rg --count-matches foo', 'rg -w -F "a.b"', 'rg --json foo', + // tree, file, stat, du, df, ls, dir + 'tree', 'tree -L 2', 'tree -a -I node_modules', 'tree -d src', 'tree -L 2 -d', + 'file a.bin', 'file -b --mime-type a.bin', 'file -i a.bin', 'file -L a.bin', + 'stat a.txt', 'stat -c %s a.txt', 'du -sh .', 'du -h --max-depth=1', 'du -ah -d 1', 'df -h', 'df -hT', 'df .', + 'ls', 'ls -la', 'ls -la src', 'ls -lh', 'ls -R', 'ls -1 --color=never', 'ls -lt | head -5', 'dir', 'dir /s', + // small ones + 'date', 'date -u', 'date +%s', 'date -u +%Y-%m-%dT%H:%M:%SZ', 'date -I', 'date -Iseconds', 'date -d @0', 'date --utc', 'date "+%Y-%m-%d"', "date '+%Y-%m-%d %H:%M'", + 'uname', 'uname -a', 'uname -m', 'hostname', 'hostname -s', 'whoami', 'whoami /groups', 'id', 'id -u', 'id -un', 'pwd', 'which node', 'which -a node', + 'basename a/b.txt', 'basename a/b.txt .txt', 'dirname a/b', 'realpath .', 'readlink -f a', 'echo hello', 'echo -n hello', 'cat a.txt', 'cat -n a.txt', + // git + 'git status', 'git status -s', 'git status --porcelain', 'git status -sb', 'git status --short --branch', 'git log', 'git log --oneline', 'git log --oneline -5', 'git log --oneline -n 5', + 'git log --stat -n 3', 'git log -p -1', 'git log --graph --oneline --decorate --all', 'git log --format=%H -1', 'git log --author=alice --since=2.weeks', 'git log -- a.txt', 'git log --follow -p a.txt', + 'git log main..HEAD', 'git log --oneline --no-merges origin/main..HEAD', 'git diff', 'git diff --stat', 'git diff --cached', 'git diff --name-only', 'git diff --name-status HEAD~1', 'git diff HEAD~1 -- a.txt', + 'git diff -U5', 'git diff --no-ext-diff', 'git diff main...HEAD', 'git diff -w', 'git show', 'git show HEAD', 'git show HEAD --stat', 'git show HEAD:a.txt', 'git show -s --format=%H HEAD', + 'git branch', 'git branch -a', 'git branch -v', 'git branch -vv', 'git branch -r', 'git branch --show-current', 'git branch --list', 'git branch --list "feat*"', 'git branch --contains HEAD', 'git branch --merged main', + 'git tag', 'git tag -l', 'git tag --list', 'git tag -l "v*"', 'git tag --sort=-creatordate', 'git tag --contains HEAD', 'git tag -n', + 'git remote', 'git remote -v', 'git config --get user.name', 'git config --list', 'git config --global --get user.email', 'git config -l', 'git config --get-all remote.origin.fetch', 'git config --show-origin --list', + 'git rev-parse HEAD', 'git rev-parse --abbrev-ref HEAD', 'git rev-parse --show-toplevel', 'git rev-parse --short HEAD', 'git rev-parse --is-inside-work-tree', 'git rev-parse --git-dir', + 'git ls-files', 'git ls-files --others --exclude-standard', 'git ls-files -m', 'git ls-files -s', 'git blame a.txt', 'git blame -L 1,10 a.txt', 'git describe --tags', 'git describe --always --dirty', + 'git shortlog -sn', 'git shortlog -s -n --all', 'git rev-list --count HEAD', 'git rev-list HEAD~5..HEAD', 'git cat-file -p HEAD', 'git cat-file -t HEAD', 'git ls-tree HEAD', 'git ls-tree -r --name-only HEAD', + 'git grep foo', 'git grep -n foo', 'git grep -n -i foo -- src', 'git grep -l foo', 'git grep -e foo --and -e bar', 'git grep -c foo', 'git grep -w -F "a.b"', 'git grep --no-index foo', + // PowerShell + 'Get-ChildItem', 'Get-ChildItem -Recurse src | Select-Object -First 5', 'Get-ChildItem -Path . -Recurse -Filter *.mjs | Select-Object -First 5 FullName', 'Get-ChildItem -Force -ErrorAction SilentlyContinue', + 'ls -Recurse', 'ls -Force', 'gci -Recurse -File', 'dir -Name', 'Get-ChildItem -Directory -Depth 2', 'Get-Content a.txt', 'Get-Content a.txt -Raw', 'Get-Content a.txt -Tail 5', 'Get-Content a.txt -TotalCount 5', + 'Get-Content -Path a.txt', 'gc a.txt | Select-Object -First 3', 'cat a.txt | Select-String needle', 'type a.txt', 'Select-String -Path *.txt -Pattern foo -CaseSensitive', 'sls foo a.txt', 'Select-String -Pattern foo -Path a.txt -Context 2', + 'Get-Content a.txt | Measure-Object -Line', 'Measure-Object -Property Length -Sum', 'Get-ChildItem | Where-Object Length -gt 100', 'Get-ChildItem | Sort-Object Length -Descending', 'Get-ChildItem | Group-Object Extension', + 'Get-ChildItem | Select-Object Name, Length | Format-Table -AutoSize', 'Get-ChildItem | Format-List', 'Get-ChildItem | Out-String', 'Test-Path a.txt', 'Test-Path a.txt -PathType Leaf', 'Resolve-Path .', + 'Get-FileHash a.txt', 'Get-FileHash a.txt -Algorithm SHA256', 'Get-Date', 'Get-Date -Format yyyy-MM-dd', 'Get-Command node', 'Get-Command -Name node -All', 'Get-Process', 'Get-Process -Name node', 'Get-Item a.txt', 'gi a.txt', + 'Get-ItemProperty a.txt', 'Get-Location', 'pwd', 'Get-Help Get-ChildItem', 'Get-Help Get-ChildItem -Examples', 'Write-Output hello', 'hostname', 'whoami', 'Get-Host', 'Get-PSDrive', 'Get-PSDrive -Name C', + 'Get-Content a.json | ConvertFrom-Json', 'Get-Content a.json | ConvertFrom-Json | ConvertTo-Json -Depth 3', 'Compare-Object a b', 'Get-Content a | Get-Unique', + // versions + 'node --version', 'node -v', 'python --version', 'git --version', 'dotnet --version', 'java -version', 'npm -v', + ]); +}); + +test('#3975: maskQuotes still returns the quoted text to the caller, without changing what it returned before', () => { + const quoted = []; + assert.equal(maskQuotes('date "+%Y" \'a b\'', quoted), 'date "_" "_"'); + assert.deepEqual(quoted, ['+%Y', 'a b']); + assert.equal(maskQuotes('Get-ChildItem "C:\\Q&A" | Select-Object Name'), 'Get-ChildItem "_" | Select-Object Name'); + assert.equal(maskQuotes('echo "$HOME"'), null); +}); diff --git a/docs/SAFETY.md b/docs/SAFETY.md index 6145c448..e377f355 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -164,7 +164,9 @@ In **Manual**: - **These ask:** writing or editing a file, any command that is not on a short list of look-only commands, and every tool you connect. In the browser tool, opening a page, clicking and typing ask. - **These do not ask:** reading files, listing and searching folders, and look-only commands such as `ls`, `cat` and - `git status`. A command with a redirect, a chain (`;`, `&&`), a variable or anything else the check does not recognise asks. + `git status`. Each of those commands runs unasked only with options that just look: `sort -o FILE`, `rg --pre PROGRAM`, + `tail -f`, `date -s` and `git grep -O` ask, as does any option the check does not know. A command with a redirect, a + chain (`;`, `&&`), a variable or anything else the check does not recognise asks. - **Web search and opening web pages ask once per chat.** The first one in a chat shows a card with the search words and the service they go to, or with the address of the page. **Approve** covers the rest of that chat. **Deny** tells the assistant you did not allow the web, and it carries on without it. Plan and Bypass do not ask. The model picks the search words and From d398f353252a43d782e20531290be74e5a231f57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=A9=E7=A9=BABlond?= <8587572+hurui200320@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:19:09 +0100 Subject: [PATCH 02/45] docker: the build context carries the nested tools/ scripts the Terminal bundle reads (#3974) docker/build.sh staged only top-level tools/*.py, so the Terminal stage stopped at 'installer tool missing: tools/dsv41/tune.py'. Ported from PR #3974 by hurui200320: the pathspec is tools/**/*.py, the no-.git fallback finds nested files, and the context test reads INSTALLER_TOOLS and INSTALLER_SCRIPTS from packaging/package_terminal.py. Fixes the failure that images built from v0.2.4.1 and v0.2.4.2 had. --- docker/build.sh | 7 +++++-- tests/terminal/test_docker_files.py | 10 ++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/docker/build.sh b/docker/build.sh index bba83ff2..3048b8bc 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -61,14 +61,17 @@ commit=${STRATA_BUILD_COMMIT:-$(git -C "$repo" rev-parse HEAD 2>/dev/null || tru case "$commit" in *[!0-9a-f]*|"") commit="" ;; esac # 1. the Terminal's sources: exactly what packaging/package_terminal.py copies (the working tree, so local edits are in the image) +# tools/: every .py at any depth, because the bundle's DeepSeek scripts are nested (INSTALLER_SCRIPTS in package_terminal.py names dsv41/*: +# the Dockerfile's terminal stage stops at "installer tool missing: tools/dsv41/tune.py" when only the top-level modules are in the context) cd "$repo" paths="packaging bin strata.py strata_control strata_cli serve requirements.txt requirements-monitor.txt docs/MANAGEMENT_PROTOCOL.md docs/TERMINAL_LAUNCH.md data bench/prompts/standard-v1 setup.py ref/load.py CMakeLists.txt" if git rev-parse --git-dir >/dev/null 2>&1; then # shellcheck disable=SC2086 - { git ls-files -z -- $paths ':(glob)tools/*.py'; } | tar --null -T - -cf - | tar -xf - -C "$ctx/terminal-src" + { git ls-files -z -- $paths ':(glob)tools/**/*.py'; } | tar --null -T - -cf - | tar -xf - -C "$ctx/terminal-src" else + tools_py=$(find tools -name '*.py') # nested too: the bundle's dsv41 scripts live in tools/dsv41/ # shellcheck disable=SC2086 - tar -cf - --exclude='__pycache__' $paths tools/*.py | tar -xf - -C "$ctx/terminal-src" + tar -cf - --exclude='__pycache__' $paths $tools_py | tar -xf - -C "$ctx/terminal-src" fi # 2. the engine package(s): hard-linked when on the same file system (no second copy of GBs), copied otherwise diff --git a/tests/terminal/test_docker_files.py b/tests/terminal/test_docker_files.py index 0792d65f..a51cee8a 100644 --- a/tests/terminal/test_docker_files.py +++ b/tests/terminal/test_docker_files.py @@ -54,6 +54,16 @@ class Scripts(unittest.TestCase): self.assertTrue((ctx / "Dockerfile").is_file()) self.assertTrue((ctx / "terminal-src" / "docs" / "TERMINAL_LAUNCH.md").is_file()) self.assertTrue((ctx / "engine" / "pkg" / "engine-component.json").is_file()) + # the bundle reads tools/ modules by path as well (INSTALLER_SCRIPTS), and the DeepSeek ones are nested: every name must be in the + # context, or package_terminal.py stops the build at "installer tool missing: tools/.py" (the image build after v0.2.4.1 was broken this way) + pt = ast.parse((ROOT / "packaging" / "package_terminal.py").read_text(encoding="utf-8")) + tools: set[str] = set() + for node in pt.body: + if isinstance(node, ast.Assign) and any(getattr(t, "id", "") in ("INSTALLER_TOOLS", "INSTALLER_SCRIPTS") for t in node.targets): + tools.update(ast.literal_eval(node.value)) + self.assertTrue({"dsv41/pack_gguf", "dsv41/tune"} <= tools) # the nested ones this assertion exists for + for name in sorted(tools): + self.assertTrue((ctx / "terminal-src" / "tools" / f"{name}.py").is_file(), f"build.sh did not copy tools/{name}.py into the context") def test_scripts_use_unix_line_ends(self): for name in ("entrypoint.sh", "strata-wrapper.sh", "healthcheck.sh", "build.sh", "publish.sh"): From 255861c442ed4a0f1e4e797899d6207c85051ab8 Mon Sep 17 00:00:00 2001 From: Roberto Jose Etcheverry Romero <63941860+robertoetcheverryr@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:19:35 +0100 Subject: [PATCH 03/45] docker: the root Dockerfile passes the source commit to the Terminal stage (#3644) .git is not in the build context, so package_terminal.py had no commit to put in the archive and the documented source build stopped. Ported from PR #3644 by robertoetcheverryr: ARG STRATA_COMMIT / ENV STRATA_BUILD_COMMIT as in docker/Dockerfile, and the two 'From source' commands in docs/DOCKER.md pass --build-arg STRATA_COMMIT=$(git rev-parse HEAD). Added: .dockerignore leaves out the folders docker/entrypoint.sh creates in a mounted data/ (install, state, home, Strata-data). A dangling data/install/third_party/llama.cpp link in a clone that had been mounted made the Terminal stage fail with a copytree error (seen in the review thread of #3644). Not built with docker here (no docker on this PC). --- .dockerignore | 5 +++++ Dockerfile | 2 ++ docs/DOCKER.md | 15 ++++++++------- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/.dockerignore b/.dockerignore index 4f341af3..2550d9bf 100644 --- a/.dockerignore +++ b/.dockerignore @@ -17,6 +17,11 @@ __pycache__/ /mtp/ /models/ /Strata-data/ +# the folders docker/entrypoint.sh creates in a mounted data/ (a link to llama.cpp, the models, the keys): never part of a build (#3644) +/data/install/ +/data/state/ +/data/home/ +/data/Strata-data/ third_party/llama.cpp/ third_party/*.zip *.done diff --git a/Dockerfile b/Dockerfile index 82f096cf..eba34a01 100644 --- a/Dockerfile +++ b/Dockerfile @@ -68,6 +68,8 @@ RUN set -e; \ # ---- 2. the Terminal (the release archive, built here) FROM ${RUNTIME_BASE} AS terminal +ARG STRATA_COMMIT= +ENV STRATA_BUILD_COMMIT=${STRATA_COMMIT} ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update && apt-get install -y --no-install-recommends python3 ca-certificates git && rm -rf /var/lib/apt/lists/* COPY . /src/ diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 81672d74..3ea6f661 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -296,13 +296,14 @@ to the system or the graphics driver (`packaging/binary_deps.py`); finally it ch library inside the finished image. A package that fails any of these stops the build. Nothing is pushed anywhere. `docker/smoke-test.sh` runs the checks we ran on real cards (serves, key, chat, tool call, monitor, clean stop, memory freed, restart); see its first lines for the variables. -**From source.** `docker build -t strata:src .` in the repository compiles the CUDA 13 engine inside Docker, makes the package -and puts it in the same kind of image (`--build-arg CUDA_ARCHITECTURES=89` for one card only, much faster). For a GTX 10, P100 or -V100 build the CUDA 12 variant: `docker build -t strata:src-cuda12 --build-arg CUDA_IMAGE=nvidia/cuda:12.9.1-devel-ubuntu24.04 ---build-arg CUDA_ARCHITECTURES="60;61;70;75;80;86;89" --build-arg BUILD_VISION=0 .` (the build turns on the Pascal / Volta code by itself -when an architecture below 75 is listed, and names the package `cuda12` with driver 575.51). For AMD and Intel -builds from source see [AMD_HIP.md](AMD_HIP.md) and [INTEL.md](INTEL.md); then package the result with -`packaging/package_engine.py` and use `docker/build.sh`. +**From source.** `docker build -t strata:src --build-arg STRATA_COMMIT=$(git rev-parse HEAD) .` in the repository compiles the CUDA 13 +engine inside Docker, makes the package and puts it in the same kind of image (`--build-arg CUDA_ARCHITECTURES=89` for one card only, +much faster). `.git` is not copied into the build, so the commit comes in as `STRATA_COMMIT`; without it the Terminal stage stops. +For a GTX 10, P100 or V100 build the CUDA 12 variant: `docker build -t strata:src-cuda12 --build-arg STRATA_COMMIT=$(git rev-parse HEAD) +--build-arg CUDA_IMAGE=nvidia/cuda:12.9.1-devel-ubuntu24.04 --build-arg CUDA_ARCHITECTURES="60;61;70;75;80;86;89" --build-arg BUILD_VISION=0 .` +(the build turns on the Pascal / Volta code by itself when an architecture below 75 is listed, and names the package `cuda12` with +driver 575.51). For AMD and Intel builds from source see [AMD_HIP.md](AMD_HIP.md) and [INTEL.md](INTEL.md); then package the result +with `packaging/package_engine.py` and use `docker/build.sh`. ## Publishing the images (for maintainers) From 9e2c0b6eb080816325626f7666833bff4ef5b643 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:19:55 +0100 Subject: [PATCH 04/45] docker: test that both Dockerfiles take the source commit and the source-build commands pass it (#3644) --- tests/terminal/test_docker_files.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/terminal/test_docker_files.py b/tests/terminal/test_docker_files.py index a51cee8a..3f2a5520 100644 --- a/tests/terminal/test_docker_files.py +++ b/tests/terminal/test_docker_files.py @@ -197,6 +197,18 @@ class Publishing(unittest.TestCase): for item in payload: self.assertTrue(any(item == p or item.startswith(p.rstrip("/") + "/") for p in listed), f"build.sh does not copy {item}") + def test_the_source_build_passes_the_commit_to_the_terminal_stage(self): + """.git is not in the build context (.dockerignore), so the root Dockerfile's terminal stage gets the commit as a build argument, the way + docker/Dockerfile does; without it package_terminal.py stops (#3644). The documented source-build commands pass it.""" + for dockerfile in (ROOT / "Dockerfile", DOCKER / "Dockerfile"): + text = dockerfile.read_text(encoding="utf-8") + self.assertRegex(text, r"(?m)^ARG STRATA_COMMIT=", dockerfile.name) + self.assertIn("ENV STRATA_BUILD_COMMIT=${STRATA_COMMIT}", text, dockerfile.name) + self.assertIn(".git", (ROOT / ".dockerignore").read_text(encoding="utf-8").split()) + doc = (ROOT / "docs" / "DOCKER.md").read_text(encoding="utf-8") + self.assertEqual(doc.count("docker build -t strata:src"), doc.count("--build-arg STRATA_COMMIT=$(git rev-parse HEAD)")) + self.assertIn("/data/install/", (ROOT / ".dockerignore").read_text(encoding="utf-8")) + def test_workflow_is_manual_and_pushes_only_on_request(self): data = yaml.safe_load(self.WORKFLOW.read_text(encoding="utf-8")) triggers = data.get("on", data.get(True)) # YAML 1.1 reads a bare `on` as True From d2c69e6d4b19069084d760462047a505c953273d Mon Sep 17 00:00:00 2001 From: SuperDistance <43229543+SuperDistance@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:20:17 +0100 Subject: [PATCH 05/45] tools/strata_bench.py: read CMakeLists.txt as UTF-8, not with the locale's code page (#4011, #2792) Ported from PR #4011 by SuperDistance. project_version() read CMakeLists.txt with Path.read_text() and no encoding, which raised UnicodeDecodeError on Windows code pages such as cp936. The test makes read_text default to each of 14 Windows code pages. The same crash was reported in #3235 and #3414. --- tools/strata_bench.py | 3 ++- tools/test_strata_bench.py | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/tools/strata_bench.py b/tools/strata_bench.py index 93d92ee1..0bb0711d 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -563,7 +563,8 @@ def detect_quant(view: dict) -> str | None: def project_version() -> str | None: try: - m = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text()) + # UTF-8 as setup.py reads it, whatever the locale's code page (#2792) + m = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8")) return m.group(1) if m else None except OSError: return None diff --git a/tools/test_strata_bench.py b/tools/test_strata_bench.py index 30d3978b..986ab1a3 100644 --- a/tools/test_strata_bench.py +++ b/tools/test_strata_bench.py @@ -339,6 +339,24 @@ class ReportTests(unittest.TestCase): def test_no_server_is_an_error_not_a_crash(self): self.assertEqual(B.main(["--url", "http://127.0.0.1:9", "--quiet"]), 2) + def test_project_version_does_not_use_the_locale_code_page(self): + # #2792: on Windows a text file read without an encoding is decoded with the locale's code page, and CMakeLists.txt + # is UTF-8 with non-ASCII text. Path.read_text here defaults to each Windows ANSI code page in turn. + original = Path.read_text + with tempfile.TemporaryDirectory() as d: + root = Path(d) + (root / "CMakeLists.txt").write_bytes( + "cmake_minimum_required(VERSION 3.24)\n# notes — § €\nproject(strata VERSION 9.8.7 LANGUAGES CXX)\n" + .encode("utf-8")) + for code_page in ("cp874", "cp932", "cp936", "cp949", "cp950", "cp1250", "cp1251", "cp1252", "cp1253", + "cp1254", "cp1255", "cp1256", "cp1257", "cp1258"): + def locale_default(self, encoding=None, errors=None, **kw): + return original(self, encoding=encoding or code_page, errors=errors, **kw) + + with self.subTest(code_page=code_page), mock.patch.object(B, "ROOT", root), \ + mock.patch.object(Path, "read_text", locale_default): + self.assertEqual(B.project_version(), "9.8.7") + if __name__ == "__main__": unittest.main() From 14bef6bb4647ca409cf75851ddf2bde07e810ab5 Mon Sep 17 00:00:00 2001 From: jubeater <11894816+jubeater@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:20:42 +0100 Subject: [PATCH 06/45] setup: hand component engines to the server for validation (#4027, #4026) _start() checked cfg['exe'] with Path.exists(), so a run config whose engine is component:strata-engine was refused as a missing file before the server could resolve and verify it. Ported from PR #4027 by jubeater. A component reference is no longer tested as a file; model files and literal engine paths are checked as before. ensure_engine_for, the Windows HIP runtime repair and the HIP architecture lookup skip the source-build engine folder for a component. Eight tests (tools/test_setup_component_start.py). --- setup.py | 12 +++- tools/test_setup_component_start.py | 98 +++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 3 deletions(-) create mode 100644 tools/test_setup_component_start.py diff --git a/setup.py b/setup.py index 55f8941f..0213d6c4 100644 --- a/setup.py +++ b/setup.py @@ -69,6 +69,7 @@ tls.install() # #3722: HTTPS checks the server against the operating system from strata_control import atomic from strata_control import draft_layer from strata_control import dsv41_context +from strata_control import engine_component from strata_control.discovery import in_trash from strata_control import user_args @@ -6851,7 +6852,10 @@ def _start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open """keep: settings given on this start that the model keeps from now on (--host, --api-key, --draft-vocab, --vram-reserve-mib).""" cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig"))) - missing = [p for p in [cfg["exe"], *[a for a in cfg["args"] if a.endswith(".gguf")]] if not Path(p).exists()] + component = engine_component.is_reference(cfg["exe"]) + # The server resolves and verifies component engines; the reference itself is not a file. + files = ([] if component else [cfg["exe"]]) + [a for a in cfg["args"] if a.endswith(".gguf")] + missing = [p for p in files if not Path(p).exists()] if missing: fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run it again with --setup to repair") keep = {k: v for k, v in (keep or {}).items() if v is not None} @@ -6879,12 +6883,12 @@ def _start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), "--port", str(port or cfg.get("port", 8080))] if cfg.get("backend") == "hip": # AMD, numbered as HIP numbers them (setup's KFD order) - if WIN: + if WIN and not component: hip_runtime_beside_exe(Path(cfg["exe"]).parent) # #468 #461: also fixes a 0.1.34 install amd = amd_gpus() if isinstance(gpu, list): # --gpus: saved, this model runs on these cards from now on cards = amd_parse_gpus(",".join(str(i) for i in gpu), amd) - built = (engine_archs_hip() or []) + built = [] if component else (engine_archs_hip() or []) miss = [x for x in cards if built and x["arch"] not in built] if miss: fail("the installed engine has no code for " + ", ".join(f"{x['name']} ({x['arch']})" for x in miss), @@ -7297,6 +7301,8 @@ def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: older or newer generation, #128) or a new GPU in the PC otherwise stops the start with 'no kernel image'. Such a card gets the engine compiled for all of them, before the start. A Pascal / Volta card added to a model on the CUDA 13 engine moves the model to the experimental CUDA 12 engine (CUDA 13 has no code for it).""" + if engine_component.is_reference(cfg.get("exe")): + return cfg # the server checks the installed component, not ROOT/engine tk = config_toolkit(cfg) if tk == 13 and any(int(g["arch"]) < CUDA13_MIN_ARCH for g in cards): return use_cuda12(cards, cfg_path, cfg, yes) diff --git a/tools/test_setup_component_start.py b/tools/test_setup_component_start.py new file mode 100644 index 00000000..e9104db2 --- /dev/null +++ b/tools/test_setup_component_start.py @@ -0,0 +1,98 @@ +"""Setup can start a component-backed config without treating the reference as a file. + + python -m unittest tools.test_setup_component_start -v +""" +import contextlib +import io +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import setup + + +class ComponentStart(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.config = self.root / "strata-iq3_s.json" + self.gguf = self.root / "model.gguf" + self.gguf.write_bytes(b"GGUF") + self.cards = [{"index": i, "name": f"RTX {i}", "arch": "89", "vram_gb": 24.0} for i in range(2)] + + def run_start(self, exe="component:strata-engine", backend="cuda", gpu=0, win=False, keep=None): + cfg = {"exe": exe, "backend": backend, "args": ["--native", str(self.gguf)], + "gpu": gpu, "gpus_asked": True, "model_name": "test", "port": 8080} + self.config.write_text(json.dumps(cfg), encoding="utf-8") + self.output = io.StringIO() + with contextlib.ExitStack() as st: + st.enter_context(contextlib.redirect_stdout(self.output)) + st.enter_context(mock.patch.object(setup, "WIN", win)) + st.enter_context(mock.patch.dict(os.environ, {"STRATA_EXECV": ""})) + st.enter_context(mock.patch.object(setup, "gpus", return_value=self.cards)) + st.enter_context(mock.patch.object(setup, "amd_gpus", return_value=[ + {"index": i, "name": f"Radeon {i}", "arch": "gfx1201", "vram_gb": 24.0} for i in range(2)])) + st.enter_context(mock.patch.object(setup, "check_gpus")) + st.enter_context(mock.patch.object(setup, "split_budget", return_value=False)) + st.enter_context(mock.patch.object(setup, "split_mmap", return_value=False)) + st.enter_context(mock.patch.object(setup, "recommend_remote_expert_opt")) + st.enter_context(mock.patch.object(setup, "old_gpus_opt_in", return_value=[])) + for name in ("engine_runs_on", "engine_archs_hip", "hip_runtime_beside_exe"): + st.enter_context(mock.patch.object(setup, name, side_effect=AssertionError("legacy engine lookup: " + name))) + self.server = st.enter_context(mock.patch.object(setup.subprocess, "call", return_value=0)) + return setup.start(self.config, None, gpu=gpu, open_browser=False, yes=True, keep=keep) + + def test_component_reaches_the_server_and_keeps_its_reference(self): + self.assertEqual(self.run_start(), 0) + self.server.assert_called_once() + argv = self.server.call_args.args[0] + self.assertIn(str(setup.ROOT / "serve" / "server.py"), argv) + self.assertEqual(argv[argv.index("--config") + 1], str(self.config)) + self.assertEqual(self.server.call_args.kwargs["env"][setup.acquisition.ENV], "1") + self.assertEqual(json.loads(self.config.read_text())["exe"], "component:strata-engine") + + def test_component_uses_saved_gpu_without_looking_for_a_source_build(self): + self.assertEqual(self.run_start(gpu=None), 0) + self.server.assert_called_once() + + def test_component_can_save_several_gpus_without_looking_for_a_source_build(self): + self.assertEqual(self.run_start(gpu=[0, 1]), 0) + self.assertEqual(json.loads(self.config.read_text())["gpu"], [0, 1]) + + def test_windows_hip_component_does_not_repair_the_legacy_engine_folder(self): + self.assertEqual(self.run_start(backend="hip", win=True), 0) + self.server.assert_called_once() + + def test_hip_component_does_not_read_source_build_architectures(self): + self.assertEqual(self.run_start(backend="hip", gpu=[0, 1]), 0) + self.server.assert_called_once() + + def test_missing_model_file_is_still_reported(self): + self.gguf.unlink() + with self.assertRaises(SystemExit): + self.run_start() + self.assertIn(str(self.gguf), self.output.getvalue()) + self.server.assert_not_called() + + def test_missing_literal_engine_path_is_still_reported(self): + missing = str(self.root / "strata") + with self.assertRaises(SystemExit): + self.run_start(exe=missing) + self.assertIn(missing, self.output.getvalue()) + self.server.assert_not_called() + + def test_component_reference_survives_saving_start_settings(self): + self.assertEqual(self.run_start(keep={"host": "127.0.0.1", "vram_reserve_mib": 1024}), 0) + saved = json.loads(self.config.read_text()) + self.assertEqual(saved["exe"], "component:strata-engine") + self.assertEqual(saved["args"][-2:], ["--vram-reserve-mib", "1024"]) + + +if __name__ == "__main__": + unittest.main() From e2e99ae54aae9a5a28938223679ab9a5ec4ef33c Mon Sep 17 00:00:00 2001 From: kossum <127719370+kossum@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:21:07 +0100 Subject: [PATCH 07/45] Windows: the token default DACL grants generic rights, so a child process can still be opened after adopt_user_defaults (#3428, #3399) adopt_user_defaults() set the token's default DACL with FA (FILE_ALL_ACCESS). That default also applies to new process objects, and the file mask has no process query or set-information right, so a child could not be reopened by PID: the HighQoS helper timed out and procs.start_token could not record the child. GA lets Windows map the mask to the object being created; the principals are unchanged. Ported from PR #3428 by kossum (QoS reopen test). Test from PR #3399 by midhatn (a live child is identified and recorded) added; both fail without the change and pass with it. Co-authored-by: MIDHAT NASHAR <35053211+midhatn@users.noreply.github.com> --- strata_control/private_files.py | 5 +- tests/terminal/test_default_object_access.py | 54 ++++++++++++++++++++ tests/terminal/test_private_files.py | 31 +++++++++++ 3 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 tests/terminal/test_default_object_access.py diff --git a/strata_control/private_files.py b/strata_control/private_files.py index 318fee9a..b272d1bb 100644 --- a/strata_control/private_files.py +++ b/strata_control/private_files.py @@ -372,8 +372,11 @@ def adopt_user_defaults() -> bool: ok_owner = bool(_advapi.SetTokenInformation(token, _TOKEN_OWNER, ctypes.byref(_Owner(psid)), ctypes.sizeof(_Owner))) descriptor = ctypes.c_void_p() + # A token default DACL also applies to processes, not just files. FA is + # FILE_ALL_ACCESS (0x1f01ff), which omits process query/set-information. + # GA is mapped to the full rights of the object being created. if not _advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW( - f"D:(A;;FA;;;{sid})(A;;FA;;;SY)(A;;FA;;;BA)", _SDDL_REVISION_1, ctypes.byref(descriptor), None): + f"D:(A;;GA;;;{sid})(A;;GA;;;SY)(A;;GA;;;BA)", _SDDL_REVISION_1, ctypes.byref(descriptor), None): return False present, defaulted, dacl = wintypes.BOOL(), wintypes.BOOL(), ctypes.c_void_p() if not _advapi.GetSecurityDescriptorDacl(descriptor, ctypes.byref(present), ctypes.byref(dacl), diff --git a/tests/terminal/test_default_object_access.py b/tests/terminal/test_default_object_access.py new file mode 100644 index 00000000..b2f9ae70 --- /dev/null +++ b/tests/terminal/test_default_object_access.py @@ -0,0 +1,54 @@ +"""Windows token defaults must permit identifying children, not just opening files.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PROBE = r""" +import json, subprocess, sys +from pathlib import Path +from strata_control import private_files, procs + +assert private_files.adopt_user_defaults() +child = subprocess.Popen( + [sys.executable, "-c", "import time; print('ready', flush=True); time.sleep(30)"], + stdout=subprocess.PIPE, text=True, +) +try: + assert child.stdout.readline().strip() == "ready" + assert child.poll() is None + token = procs.start_token(child.pid) + assert token is not None, "live child became unreadable after adopting user defaults" + recorded = procs.write_record(child.pid, "engine") + assert recorded == token, "child identity could not be recorded" + print(json.dumps({"identified": True, "recorded": True}), flush=True) +finally: + child.kill() + child.wait(timeout=10) + child.stdout.close() +""" + + +@unittest.skipUnless(os.name == "nt", "Windows token default DACL") +class DefaultObjectAccess(unittest.TestCase): + def test_adopting_user_defaults_preserves_child_identity(self): + # Token defaults affect every subsequent object creation in this process. + # Exercise them in a disposable helper, not in the test runner itself. + with tempfile.TemporaryDirectory(prefix="strata-default-access-") as folder: + env = dict(os.environ, LOCALAPPDATA=folder, PYTHONPATH=str(ROOT)) + result = subprocess.run( + [sys.executable, "-c", PROBE], cwd=ROOT, env=env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=25, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout), {"identified": True, "recorded": True}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_private_files.py b/tests/terminal/test_private_files.py index 6da7d197..df80af0d 100644 --- a/tests/terminal/test_private_files.py +++ b/tests/terminal/test_private_files.py @@ -163,6 +163,37 @@ class ElevatedRunLockoutTests(unittest.TestCase): path.write_text("{}") self.assertEqual(path.read_text(), "{}") + def test_default_dacl_allows_reopening_child_process_for_qos(self): + import subprocess + import sys + # Isolate token changes and keep this test independent of the test runner's defaults. + script = ''' +import ctypes +from ctypes import wintypes +import subprocess +import sys +from strata_control import private_files as pf +from serve import winjob +assert pf.adopt_user_defaults() +k32 = ctypes.WinDLL("kernel32", use_last_error=True) +k32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) +k32.OpenProcess.restype = wintypes.HANDLE +k32.CloseHandle.argtypes = (wintypes.HANDLE,) +child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) +try: + handle = k32.OpenProcess(0x1000 | 0x0200, False, child.pid) + assert handle, "OpenProcess failed: %s" % ctypes.get_last_error() + try: + assert winjob.no_throttle(handle), "Setting child QoS failed" + finally: + k32.CloseHandle(handle) +finally: + child.terminate() + child.wait() +''' + result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=40) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + def test_only_the_users_own_folders_are_ever_repaired(self): self.assertFalse(pf.repair_access(os.environ.get("SystemRoot", "C:\Windows") + "\System32\drivers")) From cc2c628cbe09cbc1351e086e8cca1d78a1b86a7f Mon Sep 17 00:00:00 2001 From: Demetree Kallergis <1394829+demetree@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:22:30 +0100 Subject: [PATCH 08/45] setup (Mac): say when an update was asked for a model that is not installed (#3848) metal/setup_mac.py returned right after the engine step on --update while the model questions had been asked, so choosing a model the Mac did not have ended with no download and no word. The update now names the missing model (or image encoder) and points at ./setup.sh --setup; an update for a model that is installed prints what it printed before. Ported from PR #3848 by demetree, with its two tests (mocked; not run on a Mac). --- metal/setup_mac.py | 12 ++++++++++ tools/test_setup_mac.py | 50 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/metal/setup_mac.py b/metal/setup_mac.py index b939e246..774ac3b2 100644 --- a/metal/setup_mac.py +++ b/metal/setup_mac.py @@ -433,6 +433,18 @@ def main(argv=None) -> int: (BUILD_DIR / "BUILD.json").unlink(missing_ok=True) exe = build_engine(llama) if a.update: + # update.sh's own text: "The model files are not touched". The questions are asked anyway, so when the + # answers name a model (or an image encoder) that is not here, say it: a silent exit reads like a broken + # download (an M1 Max chose IQ3_S in update.sh and got no model and no message). + files = [Path(a.gguf_dir) / n if a.gguf_dir else models_root / tag / n for n in model_shard_names(model)] + pack = S.find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower() + pack_done = (pack / "native_experts.txt").exists() and (pack / "tokenizer" / "vocab.json").exists() + if not (all(f.exists() and S.done(f) for f in files) and pack_done): + S.warn(f"{model} is not installed here, and an update does not download model files: nothing was installed") + S.say(f" to download and prepare {model}: ./setup.sh --setup") + elif vision == "yes" and not (models_root / fam["mmproj"]).exists(): + S.warn("the image encoder is not downloaded here, and an update does not download model files") + S.say(" to add image support: ./setup.sh --setup") return 0 # ---- 5. the model diff --git a/tools/test_setup_mac.py b/tools/test_setup_mac.py index 92f2a596..463a9a72 100644 --- a/tools/test_setup_mac.py +++ b/tools/test_setup_mac.py @@ -389,6 +389,56 @@ class ControlMode(unittest.TestCase): self.assertIn('if sys.platform == "darwin" and CONTROL:', src) +class UpdateFlow(unittest.TestCase): + """update.sh asks the same questions as a setup run but does not download model files: a model chosen there must + be named, not dropped in silence (an M1 Max picked IQ3_S in update.sh and got no model and no message).""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.data = Path(self.tmp.name).resolve() / "data" + self.models = Path(self.tmp.name).resolve() / "own" + self.data.mkdir() + self.models.mkdir() + self.said, self.warned = [], [] + + def run_update(self, argv=("--update", "--model", "IQ3_S", "--vision", "no", "--yes")): + with mock.patch.object(M, "mac_configs", lambda: []), \ + mock.patch.object(M.S, "data_folder_for", lambda a: (self.data, [])), \ + mock.patch.object(M, "mac_info", lambda run=None: {"chip": "Apple M1 Max", "ram_gb": 32.0, + "macos": "26.6.2", "arm64": True, "clt": True}), \ + mock.patch.object(M, "mac_problems", lambda info: []), \ + mock.patch.object(M.S, "free_gb", lambda p: 200.0), \ + mock.patch.object(M.S, "step", lambda *a, **k: None), \ + mock.patch.object(M.S, "say", lambda *a, **k: self.said.append(" ".join(str(x) for x in a))), \ + mock.patch.object(M.S, "ok", lambda *a, **k: None), \ + mock.patch.object(M.S, "warn", lambda *a, **k: self.warned.append(" ".join(str(x) for x in a))), \ + mock.patch.object(M.S, "pip_install", lambda *a, **k: None), \ + mock.patch.object(M.S, "get_llama_cpp", lambda: self.data / "llama"), \ + mock.patch.object(M, "build_engine", lambda llama, jobs=None: self.data / "strata"), \ + mock.patch.object(M.S, "download", side_effect=AssertionError("an update must not download")): + return M.main([*argv, "--data-dir", str(self.data), "--gguf-dir", str(self.models)]) + + def test_a_model_chosen_in_an_update_is_named_not_dropped(self): + self.assertEqual(self.run_update(), 0) + self.assertIn("IQ3_S is not installed here", " ".join(self.warned)) + self.assertIn("does not download model files", " ".join(self.warned)) + self.assertIn("./setup.sh --setup", " ".join(self.said)) + + def test_an_installed_model_keeps_the_update_quiet(self): + for n in M.model_shard_names("IQ3_S"): + f = self.models / n + f.write_bytes(b"x") + f.with_name(f.name + ".done").write_text("whole") + tag = M.S.FAMILIES["qwen"]["tag"] + "IQ3_S" + pack = self.data / "packs" / tag.lower() + (pack / "tokenizer").mkdir(parents=True) + (pack / "native_experts.txt").write_text("x") + (pack / "tokenizer" / "vocab.json").write_text("{}") + self.assertEqual(self.run_update(), 0) + self.assertFalse([w for w in self.warned if "not installed here" in w], self.warned) + + class Source(unittest.TestCase): """setup.py hands a Mac over before its own parser runs, so the Mac parser has to know --source: source_hint() recommends it on every platform (#2363).""" From 3cda075b5152f854634c9cdd41e5cc5977ca3c47 Mon Sep 17 00:00:00 2001 From: xxxliqu1dxxx <83290244+xxxliqu1dxxx@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:23:22 +0100 Subject: [PATCH 09/45] setup (AMD, Linux): the engine probes get the engine's lib_dirs on LD_LIBRARY_PATH (#3305) engine_env put the ROCm library folders first on PATH, which only Windows' loader reads. On AMD Linux strata --families exited 127 on libhipblas.so.3, so setup falsely said the engine does not run Qwen3.6. On Linux and elsewhere the folders now go first on LD_LIBRARY_PATH (an existing value is kept); Windows keeps PATH. Ported from PR #3305 by xxxliqu1dxxx (resubmission of #2914), with its tests. --- setup.py | 10 +++++++--- tools/test_setup_amd.py | 20 ++++++++++++++++---- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/setup.py b/setup.py index 0213d6c4..c1a06ab6 100644 --- a/setup.py +++ b/setup.py @@ -4197,12 +4197,16 @@ def amd_gpus_windows(adapters=None, registry=None) -> list[dict]: def engine_env(eng: Path) -> dict: """The environment for running an installed engine's own programs (`strata --families`, `strata-device - --list-devices`): the ready-made Windows HIP engine keeps hipblas.dll / libhipblaslt.dll in its rocm/bin, which the - loader finds through PATH only (#2372: a launch without it shows a "not found" dialog per DLL and prints nothing).""" + --list-devices`): the engine's ROCm library folders (its BUILD.json "lib_dirs") first on the dynamic-library path - + on Windows that is PATH, where the ready-made HIP engine keeps hipblas.dll / libhipblaslt.dll in its rocm/bin and the + loader finds them only through PATH (#2372: a launch without it shows a "not found" dialog per DLL and prints + nothing); on Linux and elsewhere it is LD_LIBRARY_PATH, where a probe without it exits 127 on libhipblas.so.3 and + prints nothing.""" env = dict(os.environ) dirs = [str(d) for d in hip_lib_dirs(eng)] if dirs: - env["PATH"] = os.pathsep.join(dirs + [env.get("PATH", "")]) + var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH" + env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else [])) return env diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py index cd853654..fa2847b5 100644 --- a/tools/test_setup_amd.py +++ b/tools/test_setup_amd.py @@ -675,14 +675,25 @@ class EngineLaunchEnv(unittest.TestCase): (eng / "BUILD.json").write_text('{"backend": "hip", "lib_dirs": ["rocm/bin"]}', encoding="utf-8") return eng - def test_engine_env_puts_rocm_bin_first(self): + def test_engine_env_puts_rocm_bin_first_on_windows(self): with tempfile.TemporaryDirectory() as t: eng = self.engine(Path(t)) - with mock.patch.dict("os.environ", {"PATH": "C:\\Windows"}): + with mock.patch.dict("os.environ", {"PATH": "C:\\Windows"}), \ + mock.patch.object(setup.os, "name", "nt"): env = setup.engine_env(eng) self.assertEqual(env["PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin")) self.assertTrue(env["PATH"].endswith("C:\\Windows")) + def test_engine_env_puts_rocm_bin_first_on_ld_library_path(self): + with tempfile.TemporaryDirectory() as t: + eng = self.engine(Path(t)) + with mock.patch.dict("os.environ", {"PATH": "/usr/bin", "LD_LIBRARY_PATH": "/usr/lib"}), \ + mock.patch.object(setup.os, "name", "posix"): + env = setup.engine_env(eng) + self.assertEqual(env["LD_LIBRARY_PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin")) + self.assertTrue(env["LD_LIBRARY_PATH"].endswith("/usr/lib")) + self.assertEqual(env["PATH"], "/usr/bin") + def test_engine_without_lib_dirs_keeps_the_environment(self): with tempfile.TemporaryDirectory() as t: with mock.patch.dict("os.environ", {"PATH": "/usr/bin"}): @@ -696,7 +707,8 @@ class EngineLaunchEnv(unittest.TestCase): return mock.Mock(stdout="qwen4exp qwen35moe\n") with tempfile.TemporaryDirectory() as t: eng = self.engine(Path(t)) - with mock.patch.object(setup.subprocess, "run", fake_run): + with mock.patch.object(setup.subprocess, "run", fake_run), \ + mock.patch.object(setup.os, "name", "nt"): names = setup.engine_families(eng) self.assertEqual(names, {"qwen4exp", "qwen35moe"}) self.assertEqual(seen["cmd"][1], "--families") @@ -712,7 +724,7 @@ class EngineLaunchEnv(unittest.TestCase): eng = self.engine(Path(t)) probe = eng / ("strata-device.exe" if setup.WIN else "strata-device") probe.write_text("x") - with mock.patch.object(setup.subprocess, "run", fake_run), mock.patch.object(setup, "hip_runtime_beside_exe", lambda d: None): + with mock.patch.object(setup.subprocess, "run", fake_run), mock.patch.object(setup, "hip_runtime_beside_exe", lambda d: None), mock.patch.object(setup.os, "name", "nt"): found = setup.hip_devices(probe) self.assertEqual(found[0]["arch"], "gfx1100") self.assertEqual(seen["env"]["PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin")) From bc939b6303e23b5e8693a8430ba46a054b394b45 Mon Sep 17 00:00:00 2001 From: Patrick Schaub <11846736+pschaub@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:23:38 +0100 Subject: [PATCH 10/45] docs/SAFETY.md: strata launch updates an installed DeepSeek engine package by itself (#4028, #4022) The page said that starting a model never downloads and that nothing checks for updates in the background. Since 0.2.4.2 strata launch with a DeepSeek model checks the signed feed (10 s at most, silent without a connection) and replaces an older installed DeepSeek engine package. Ported from PR #4028 by pschaub (wording from issue #4022), checked against strata_cli/launch/runner.py upgrade_dsv41_engine. --- docs/SAFETY.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/SAFETY.md b/docs/SAFETY.md index e377f355..43412633 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -10,11 +10,13 @@ you trust can check it. Where Strata does less than you might hope, the page say outside model service, you open the server to other devices or to the internet, or the agent searches the web or opens a page (see [What the agent can do](#what-the-coding-agent-can-do-on-your-pc)). - **There is no telemetry.** Strata sends no usage data, no crash reports and no analytics, and has no account to sign in to. -- **Starting and running a model never downloads anything.** Downloads and updates are separate steps that you start. +- **Starting and running a model never downloads anything**, except that `strata launch` updates an installed DeepSeek + engine package by itself when the signed feed has a newer one (below). Other downloads and updates are steps that you start. - **The server listens on your PC only.** Reaching it from another device needs an API key. - **Once a model is downloaded, Strata runs without internet.** Starting, loading, serving and chatting need no connection. Only things you ask for use it: the agent's web search and web pages, an outside model service, the tunnel, - and installs and updates (a first model install also fetches llama.cpp's preparation scripts). + and installs and updates (a first model install also fetches llama.cpp's preparation scripts), plus the DeepSeek engine + check of `strata launch` (without a connection it gives up after at most 10 s and the launch goes on). - **Downloads are checked.** Updates come from a signed feed. Every model file has a fixed SHA-256 and size, and an install stops if the pinned version of a file is gone (the details are [below](#how-downloads-are-checked)). - **In its default mode the coding agent asks before it changes anything**, and once per chat before its first web search or web page. @@ -44,7 +46,7 @@ Like any download, each connection below shows the other side your IP address an | --- | --- | --- | | Model files, the picture reader, the speed-up layer (MTP) | huggingface.co, or the mirror in `HF_ENDPOINT` if you set one | When you install a model | | The same files from ModelScope, for PCs that cannot reach Hugging Face | modelscope.cn | Only if you ask for it (`--source modelscope`). Strata never switches to it by itself | -| Engine, Terminal and Control updates | The signed feed on GitHub Releases of Niko1221/Strata | When you install an engine, press **Update engine** or **Check for updates**, or run `strata update`. Opening **Settings, Engine** does not connect: it shows the result of your last check | +| Engine, Terminal and Control updates | The signed feed on GitHub Releases of Niko1221/Strata | When you install an engine, press **Update engine** or **Check for updates**, or run `strata update`; the DeepSeek engine also on `strata launch` (below). Opening **Settings, Engine** does not connect: it shows the result of your last check | | App updates | `latest.json` on the same GitHub Releases, through Tauri's updater | When you press **Check for updates** or **Update Strata** | | llama.cpp source code (a fixed commit) | github.com/ggml-org/llama.cpp | During a model install, if it is not on your PC yet. Strata uses only its model-preparation scripts | | Web search and web pages | DuckDuckGo, with Bing as the second source; or Exa, Perplexity or DeepSeek if you save a key for them. Any page the agent is asked to open goes to that page's site | When the agent uses its search or "open web pages" tool. In Manual mode it asks you first, once per chat | @@ -61,7 +63,11 @@ That is the full list found in the code. Some details: - **Nothing checks for updates in the background.** The app does not check when it starts, and not when you open Settings, Engine either: that screen shows the result of your last check, or nothing if you have not checked. The checks in the table run when you press a button or run a command. With no connection, the check says so and nothing else happens. The Terminal fetches an engine by itself only when none is - installed, and `strata launch` asks first. + installed, and `strata launch` asks first. One exception: `strata launch` with a DeepSeek model first checks whether the + signed feed can be reached (at most 10 s; without a connection it says nothing and goes on), then reads it, and when it has + a newer DeepSeek engine package for this PC, fetches and checks it, starts it once (`--version`), switches to it and removes + the older one. On a failure the installed one keeps running. Not when the launch is given `--dsv41-package` or + `STRATA_DSV41_EXE` is set (`strata_cli/launch/runner.py`, `upgrade_dsv41_engine`). - **Starting and serving never download.** `strata serve` and the app's load button fetch nothing. The app sets `STRATA_PACKAGED=1` and `STRATA_NO_ACQUIRE=1` for its parts (`apps/desktop/src-tauri/src/main.rs`), and the downloaders refuse to run under them (`strata_control/acquisition.py`, `apps/host/server/acquisition.mjs`). That is why the app From 800730103c67fe6c1159c3e01d01bab388ec55b8 Mon Sep 17 00:00:00 2001 From: ctr-137 <343917439+ctr-137@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:24:35 +0100 Subject: [PATCH 11/45] tools/strata_bench.py: the redactor replaces a folder before the short user name inside it (#3619, #3326) Substitutions were ordered by the length of their regular expression, and a user name wrapped in word bounds outranked the Strata or home folder that contains it, so a report kept /home//Strata instead of . They are now ordered by the text they replace. Ported from PR #3619 by ctr-137 with its test (Linux and Windows layouts). --- tools/strata_bench.py | 8 ++++---- tools/test_strata_bench.py | 26 +++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/tools/strata_bench.py b/tools/strata_bench.py index 0bb0711d..be0e39cf 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -68,14 +68,14 @@ BURST_MAX_TOKENS = 128 def redactor(extra: list[str] = (), key: str = ""): """-> f(text) -> text with this machine's home folders, user and host names, the Strata folder, IP addresses and the API key replaced. Applied to everything that is written or printed from the server's or the machine's own text.""" - subs: list[tuple[re.Pattern, str]] = [] + subs: list[tuple[re.Pattern, str, int]] = [] def add(value, label, word=False): if value and len(str(value)) >= 4: v = str(value) for form in sorted({v, v.replace("\\", "/"), v.replace("/", "\\")}, key=len, reverse=True): pat = re.escape(form) - subs.append((re.compile(r"(?") add(Path.home(), "") @@ -89,7 +89,7 @@ def redactor(extra: list[str] = (), key: str = ""): for x in extra: add(x, "", True) add(key, "") - subs.sort(key=lambda p: -len(p[0].pattern)) + subs.sort(key=lambda s: -s[2]) # by the text that is replaced: the word wrappers would make a short user name outrank the folder holding it path_user = re.compile(r"(?i)([A-Za-z]:)?([\\/])(Users|home)([\\/])(?!<)[^\\/\s\"':;,]+") ip4 = re.compile(r"\b(?:192\.168|10\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])|169\.254)\.\d{1,3}\.\d{1,3}\b") bearer = re.compile(r"(?i)(bearer\s+)[A-Za-z0-9._~+/=-]{8,}") @@ -97,7 +97,7 @@ def redactor(extra: list[str] = (), key: str = ""): def f(text): if not isinstance(text, str): return text - for pat, label in subs: + for pat, label, _ in subs: text = pat.sub(label, text) text = path_user.sub(lambda m: f"{m.group(1) or ''}{m.group(2)}{m.group(3)}{m.group(4)}", text) text = bearer.sub(r"\1", text) diff --git a/tools/test_strata_bench.py b/tools/test_strata_bench.py index 986ab1a3..80babc65 100644 --- a/tools/test_strata_bench.py +++ b/tools/test_strata_bench.py @@ -12,7 +12,7 @@ import threading import unittest from unittest import mock from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path +from pathlib import Path, PurePosixPath, PureWindowsPath sys.path.insert(0, str(Path(__file__).resolve().parent)) import strata_bench as B # noqa: E402 @@ -186,6 +186,30 @@ class RedactionTests(unittest.TestCase): if len(user) >= 4: self.assertNotIn(user, red(f"hello {user} world")) + def test_a_folder_under_a_short_home_keeps_its_own_placeholder(self): + # issue #3326 with a fixed machine (user name "dgbox", the repository directly under the home folder): + # a name is wrapped in word bounds, which makes its pattern longer than the pattern of the folder + # holding it, so the name won and the report kept the folder layout instead of and . + def red(root, home, user, host, tmp): + with mock.patch.object(B, "ROOT", root), mock.patch.object(B.Path, "home", return_value=home), \ + mock.patch.object(B.getpass, "getuser", return_value=user), \ + mock.patch.object(B.socket, "gethostname", return_value=host), \ + mock.patch.object(B.platform, "node", return_value=host), \ + mock.patch.object(B.tempfile, "gettempdir", return_value=tmp): + return B.redactor() + + linux = red(PurePosixPath("/home/dgbox/Strata"), PurePosixPath("/home/dgbox"), "dgbox", "dgbox-ubuntu-server", "/tmp") + self.assertEqual(linux("loading /home/dgbox/Strata/strata-x.json"), "loading /strata-x.json") + self.assertEqual(linux("dgbox-ubuntu-server wrote /home/dgbox/Strata/bench/results/run/results.json"), + " wrote /bench/results/run/results.json") + self.assertEqual(linux("in /home/dgbox/data"), "in /data") + self.assertEqual(linux("hello dgbox world"), "hello world") + self.assertEqual(linux("log /tmp/strata.log"), "log /strata.log") + win = red(PureWindowsPath(r"C:\Users\dgbox\Strata"), PureWindowsPath(r"C:\Users\dgbox"), "dgbox", "dgbox-pc", + r"C:\Users\dgbox\AppData\Local\Temp") + self.assertEqual(win(r"in C:\Users\dgbox\data"), r"in \data") + self.assertEqual(win(r"loading C:\Users\dgbox\Strata\strata-x.json"), r"loading \strata-x.json") + def test_objects_are_redacted_deeply(self): red = B.redactor() out = B.redact_obj({"a": [{"p": r"D:\Users\zed\x"}], "n": 3}, red) From 1be7eb77c1757e5a49a359007f8d5020292e6d46 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:25:25 +0100 Subject: [PATCH 12/45] tests: the setup golden compares the platform's vision binary names, and test_nvfp4_local_pack skips without pytest (#3325) tools/test_setup_golden normalized strata.exe but not strata-vision.exe, so all 25 baseline entries failed on Linux (48 subtests). VEXE and HVEXE are mapped to and like EXE, and the baseline records . test_nvfp4_local_pack imports pytest, which is not in requirements.txt; under python -m unittest discover the module is now skipped with a reason instead of failing to import. --- tools/test_nvfp4_local_pack.py | 7 ++++- tools/test_setup_golden.json | 50 +++++++++++++++++----------------- tools/test_setup_golden.py | 6 +++- 3 files changed, 36 insertions(+), 27 deletions(-) diff --git a/tools/test_nvfp4_local_pack.py b/tools/test_nvfp4_local_pack.py index 6d85b619..dd6fbe32 100644 --- a/tools/test_nvfp4_local_pack.py +++ b/tools/test_nvfp4_local_pack.py @@ -3,7 +3,12 @@ import pathlib import sys import numpy as np -import pytest +import unittest + +try: + import pytest +except ImportError: # not in requirements.txt: python -m unittest skips this module instead of failing to import it (#3325) + raise unittest.SkipTest("pytest is not installed") sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) import nvfp4_local_pack as P # noqa: E402 diff --git a/tools/test_setup_golden.json b/tools/test_setup_golden.json index e4e654c2..284c0a92 100644 --- a/tools/test_setup_golden.json +++ b/tools/test_setup_golden.json @@ -43,7 +43,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -95,7 +95,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -147,7 +147,7 @@ "port": 8080, "tokenizer": "/data/packs/q2_0/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -199,7 +199,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -253,7 +253,7 @@ "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -313,7 +313,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -373,7 +373,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -433,7 +433,7 @@ "port": 8080, "tokenizer": "/data/packs/q2_0/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -493,7 +493,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -550,7 +550,7 @@ "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -608,7 +608,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -667,7 +667,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -725,7 +725,7 @@ "port": 8080, "tokenizer": "/data/packs/q2_0/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -784,7 +784,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -840,7 +840,7 @@ "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -891,7 +891,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -943,7 +943,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -995,7 +995,7 @@ "port": 8080, "tokenizer": "/data/packs/q2_0/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1045,7 +1045,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1098,7 +1098,7 @@ "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1148,7 +1148,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1199,7 +1199,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1250,7 +1250,7 @@ "port": 8080, "tokenizer": "/data/packs/q2_0/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1301,7 +1301,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1354,7 +1354,7 @@ "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", diff --git a/tools/test_setup_golden.py b/tools/test_setup_golden.py index eb940cee..2ac754e3 100644 --- a/tools/test_setup_golden.py +++ b/tools/test_setup_golden.py @@ -56,7 +56,11 @@ def normalize(v, t: Path): if isinstance(v, list): return [normalize(x, t) for x in v] if isinstance(v, str): - return re.sub(rf"(?", v.replace(str(t), "").replace("\\", "/")) # #973: only the whole name, not "strata-x.log" on Linux + v = v.replace(str(t), "").replace("\\", "/") + # the platform's own names of the programs (strata.exe or strata, strata-vision.exe or strata-vision, ...) so the baseline compares on Windows and Linux (#3325) + for name, label in ((setup.HVEXE, ""), (setup.VEXE, ""), (setup.EXE, "")): + v = re.sub(rf"(? Date: Mon, 26 Oct 2026 18:26:18 +0100 Subject: [PATCH 13/45] sycl/tools/build.sh exits with the build's own status (#2990) The script ended with a grep pipeline, so a failed compile exited 0 (and, before the ocloc check was added at the end, a good build exited 1). A build.sh && next-step chain then ran after a failure. The status of cmake --build is kept and the script exits with it. The test runs the real script with a stub cmake on PATH (good build: 0, failed compile: 1; the old script exits 0 on the failed compile). --- docs/A770_SPEED_SPEC.md | 7 +-- sycl/tools/build.sh | 4 +- tests/terminal/test_sycl_build_script.py | 74 ++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 5 deletions(-) create mode 100644 tests/terminal/test_sycl_build_script.py diff --git a/docs/A770_SPEED_SPEC.md b/docs/A770_SPEED_SPEC.md index 14ea3398..66fa7e10 100644 --- a/docs/A770_SPEED_SPEC.md +++ b/docs/A770_SPEED_SPEC.md @@ -445,10 +445,9 @@ docker run --rm -u "$(id -u):$(id -g)" -v "$PWD/..:/work" strata-sycl-dev \ cmake --build /work/strata-v0.1.40.3/build-sycl --target strata -j 8" ``` -Use the actual `cmake --build` exit status: `sycl/tools/build.sh` currently -prints `BUILD EXIT 0` but can itself return nonzero because its last failure- -search pipeline finds no failures. Do not chain tests behind that misleading -script status. +Use the actual `cmake --build` exit status. `sycl/tools/build.sh` from 0.2.7 on exits with it; older copies +printed `BUILD EXIT 0` but could return nonzero because their last failure-search pipeline found no failures. +Do not chain tests behind the status of an older script. ## Artifacts and implementation sequence diff --git a/sycl/tools/build.sh b/sycl/tools/build.sh index 144dd427..046c2e2f 100755 --- a/sycl/tools/build.sh +++ b/sycl/tools/build.sh @@ -41,9 +41,11 @@ b=${BUILD_DIR:-$repo/build-sycl} # an existing build folder keeps its cache: a switch given now reaches it (only this one, so AOT and the rest stay as configured) [ -z "${I8_ESIMD:-}" ] || cmake -S $repo/sycl -B $b -DSTRATA_SYCL_I8_ESIMD="$I8_ESIMD" >/dev/null 2>&1 cmake --build $b -j ${JOBS:-12} ${1:+--target "$@"} -- -k 0 2>&1 | tee $b/build.log | grep -E '^FAILED|error:|^ninja: build stopped|Linking|^\[[0-9]+/[0-9]+\] Linking' | tail -40 -echo "BUILD EXIT ${PIPESTATUS[0]}" +rc=${PIPESTATUS[0]} # cmake's status, kept: the script ends with this, not with the status of the greps below (#2990) +echo "BUILD EXIT $rc" grep -c 'error:' $b/build.log | sed 's/^/errors: /' grep -E '^FAILED' $b/build.log | sed 's#.*/##' | sort | uniq | head -60 if grep -q 'IGC: Internal Compiler Error' $b/build.log 2>/dev/null; then echo "build.sh: the device compiler (ocloc $(ocloc_version || echo '?')) crashed: try docker build --pull -t strata-sycl-dev sycl/tools or I8_ESIMD=OFF (#3219)" fi +exit "$rc" diff --git a/tests/terminal/test_sycl_build_script.py b/tests/terminal/test_sycl_build_script.py new file mode 100644 index 00000000..71d93ee4 --- /dev/null +++ b/tests/terminal/test_sycl_build_script.py @@ -0,0 +1,74 @@ +"""sycl/tools/build.sh exits with the build's own status (#2990): 0 after a good build, nonzero after a failed one. + +It once ended with a grep pipeline, so a good build exited 1 (nothing to find) and a failed compile exited 0, and a `build.sh && next-step` chain ran +the wrong way round. The test runs the real script with a stub cmake on PATH; no compiler, no oneAPI, no docker. +""" +from __future__ import annotations + +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "sycl" / "tools" / "build.sh" +BASH = shutil.which("bash") # the full path: on Windows a bare "bash" can start the WSL launcher in System32 instead of Git bash +CYGPATH = shutil.which("cygpath") + + +def sh_path(p) -> str: + if CYGPATH is None: + return str(p) + return subprocess.run([CYGPATH, "-u", str(p)], capture_output=True, text=True, check=True).stdout.strip() + + +STUB = """#!/bin/sh +# a stand-in for cmake: `cmake --build DIR ...` prints what ninja prints and exits with STUB_RC; any other call does nothing +case "$1" in + --build) + echo "[1/2] Building CXX object CMakeFiles/strata.dir/main.cpp.o" + if [ "${STUB_RC:-0}" != 0 ]; then + echo "FAILED: [code=1] CMakeFiles/strata.dir/main.cpp.o" + echo "main.cpp:1:21: error: 'x' was not declared in this scope" + echo "ninja: build stopped: cannot make progress due to previous errors." + else + echo "[2/2] Linking CXX executable strata" + fi + exit "${STUB_RC:-0}" ;; +esac +exit 0 +""" + + +@unittest.skipIf(BASH is None, "needs bash") +class BuildScriptStatus(unittest.TestCase): + def run_script(self, rc: int): + with tempfile.TemporaryDirectory() as tmp: + bindir, build = Path(tmp) / "bin", Path(tmp) / "build" + bindir.mkdir() + build.mkdir() + (build / "build.ninja").write_text("", encoding="utf-8") # an existing build folder: the script does not configure it + (bindir / "cmake").write_text(STUB, encoding="utf-8", newline="\n") + (bindir / "cmake").chmod(0o755) + env = dict(os.environ, PATH=sh_path(bindir) + os.pathsep + os.environ["PATH"], STUB_RC=str(rc), REPO=sh_path(ROOT), + BUILD_DIR=sh_path(build), AOT="", I8_ESIMD="OFF") + done = subprocess.run([BASH, sh_path(SCRIPT), "strata"], capture_output=True, text=True, env=env, timeout=120) + return done + + def test_a_good_build_exits_zero(self): + done = self.run_script(0) + self.assertIn("BUILD EXIT 0", done.stdout) + self.assertIn("errors: 0", done.stdout) + self.assertEqual(done.returncode, 0, done.stdout + done.stderr) + + def test_a_failed_compile_exits_nonzero_with_the_builds_status(self): + done = self.run_script(1) + self.assertIn("BUILD EXIT 1", done.stdout) + self.assertIn("errors: 1", done.stdout) + self.assertEqual(done.returncode, 1, done.stdout + done.stderr) + + +if __name__ == "__main__": + unittest.main() From 590c69a578709de9f52fa1f2efed08c042f34fa1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:27:27 +0100 Subject: [PATCH 14/45] cmake/ggml_tq_overlay_test.cmake sets CMP0057 NEW so IN_LIST works under CMake 3.x (#3412) A cmake -P script has no cmake_minimum_required, so CMake 3.x used the OLD behaviour and stopped at 'if given arguments ... IN_LIST: Unknown arguments' (ctest ggml_tq_overlay with CMake 3.31). Checked with pip cmake 3.31.6 and 4.4.3 against the pinned llama.cpp: both print 'ggml_tq_overlay_test: ok'. A static test keeps the policy before the first IN_LIST in every cmake/*_test.cmake. --- cmake/ggml_tq_overlay_test.cmake | 2 ++ tests/terminal/test_cmake_script_policies.py | 29 ++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 tests/terminal/test_cmake_script_policies.py diff --git a/cmake/ggml_tq_overlay_test.cmake b/cmake/ggml_tq_overlay_test.cmake index e56604c8..ca637e5f 100644 --- a/cmake/ggml_tq_overlay_test.cmake +++ b/cmake/ggml_tq_overlay_test.cmake @@ -1,6 +1,8 @@ # cmake -DLLAMA= -DOUT= -P cmake/ggml_tq_overlay_test.cmake # The trellis MMQ overlay on a pinned llama.cpp: it generates, every copied header is the pinned one except the patched # ones, and the patched ones only gain lines (TQ routing, three externs, config copies of IQ2_XS's). +# a -P script has no cmake_minimum_required, so CMake 3.x applies the OLD CMP0057 and IN_LIST below is not an operator (#3412) +cmake_policy(SET CMP0057 NEW) get_filename_component(CMAKE_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE) include(${CMAKE_CURRENT_LIST_DIR}/strata_ggml_tq_overlay.cmake) file(REMOVE_RECURSE "${OUT}") diff --git a/tests/terminal/test_cmake_script_policies.py b/tests/terminal/test_cmake_script_policies.py new file mode 100644 index 00000000..cad4e98d --- /dev/null +++ b/tests/terminal/test_cmake_script_policies.py @@ -0,0 +1,29 @@ +"""A `cmake -P` script has no cmake_minimum_required, so CMake 3.x applies the OLD behaviour of CMP0057 and `IN_LIST` is not an operator +(ctest ggml_tq_overlay stopped at its first IN_LIST with CMake 3.31, #3412). Every script in cmake/ that is run with -P and uses IN_LIST +sets the policy before the first use. (Static check: the project accepts CMake 3.24 and newer, and CMake 4 sets the policy by itself.)""" +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +CMAKE = Path(__file__).resolve().parents[2] / "cmake" + + +class ScriptPolicies(unittest.TestCase): + def test_p_scripts_that_use_in_list_set_cmp0057_first(self): + found = 0 + for path in sorted(CMAKE.glob("*_test.cmake")): + text = path.read_text(encoding="utf-8") + code = re.sub(r"(?m)^\s*#.*$", "", text) + if "IN_LIST" not in code: + continue + found += 1 + policy = re.search(r"cmake_policy\(\s*SET\s+CMP0057\s+NEW\s*\)", code) or re.search(r"cmake_minimum_required\(\s*VERSION\s+3\.(1[0-9]|[2-9]\d)", code) + self.assertTrue(policy, f"{path.name} uses IN_LIST without CMP0057 NEW") + self.assertLess(policy.start(), code.index("IN_LIST"), f"{path.name} sets the policy after its first IN_LIST") + self.assertGreaterEqual(found, 1) + + +if __name__ == "__main__": + unittest.main() From bf994ca4141c81d089e6975bc01eea9474f48ae8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:28:23 +0100 Subject: [PATCH 15/45] setup: a build folder configured with another generator is configured again instead of stopping cmake (#4038) The manual build in docs/INSTALL.md uses CMake's default generator (Unix Makefiles on Linux) in build/, and setup --build always asks for Ninja, so cmake stopped with 'Does not match the generator used previously'. cmake_build now reads CMAKE_GENERATOR from the folder's CMakeCache.txt; when it is not Ninja it says so in one line and removes the cache and CMakeFiles (no other file). A Ninja folder or a new folder is untouched. Tests: tools/test_setup_build_dir.py. --- setup.py | 26 +++++++++++ tools/test_setup_build_dir.py | 86 +++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 tools/test_setup_build_dir.py diff --git a/setup.py b/setup.py index c1a06ab6..f994d32e 100644 --- a/setup.py +++ b/setup.py @@ -5577,9 +5577,35 @@ def ensure_build_tools(): return cmake, ninja +def configured_generator(bdir: Path) -> str | None: + """The generator a build folder was configured with (CMakeCache.txt), None when it was never configured.""" + try: + for line in (Path(bdir) / "CMakeCache.txt").read_text(encoding="utf-8", errors="replace").splitlines(): + if line.startswith("CMAKE_GENERATOR:"): + return line.split("=", 1)[1].strip() + except OSError: + pass + return None + + +def fresh_if_other_generator(bdir: Path, generator: str = "Ninja") -> bool: + """CMake refuses to configure a folder with another generator than the one it was made with ("Does not match the generator used + previously"). The manual build in docs/INSTALL.md uses CMake's default, Unix Makefiles on Linux, in the same build/ folder (#4038). + Such a folder is configured afresh: its cache is removed (the compiled objects of the other generator are not reused anyway), with one + plain line. True when it did.""" + had = configured_generator(bdir) + if had is None or had == generator: + return False + say(f" {Path(bdir).name}/ was configured with {had}; setup builds with {generator}, so it is configured again (the other build is not used)") + (Path(bdir) / "CMakeCache.txt").unlink(missing_ok=True) + shutil.rmtree(Path(bdir) / "CMakeFiles", ignore_errors=True) + return True + + def cmake_build(src, bdir, target, defs, vcvars, bat_name): acquisition.require("a compile (cmake)") cmake, ninja = ensure_build_tools() + fresh_if_other_generator(bdir) conf = [cmake, "-G", "Ninja", f"-DCMAKE_MAKE_PROGRAM={ninja}", "-S", str(src), "-B", str(bdir), "-DCMAKE_BUILD_TYPE=Release", *defs] build = [cmake, "--build", str(bdir), "--target", target, "-j", str(max(2, (os.cpu_count() or 4) // 2))] diff --git a/tools/test_setup_build_dir.py b/tools/test_setup_build_dir.py new file mode 100644 index 00000000..b69add3d --- /dev/null +++ b/tools/test_setup_build_dir.py @@ -0,0 +1,86 @@ +"""A build folder made by the manual build in docs/INSTALL.md (CMake's default generator) does not stop setup --build (#4038). + +CMake refuses a folder configured with another generator ("Does not match the generator used previously: Unix Makefiles"), and setup +always asks for Ninja. The folder is configured afresh, with one plain line; a folder made with Ninja, or never configured, is left alone. + + python -m unittest tools.test_setup_build_dir +""" +from __future__ import annotations + +import contextlib +import io +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +def configured(folder: Path, generator: str) -> Path: + folder.mkdir(parents=True, exist_ok=True) + (folder / "CMakeCache.txt").write_text( + f"# This is the CMakeCache file.\nCMAKE_BUILD_TYPE:STRING=Release\nCMAKE_GENERATOR:INTERNAL={generator}\nCMAKE_HOME_DIRECTORY:INTERNAL=/x\n", encoding="utf-8") + (folder / "CMakeFiles").mkdir(exist_ok=True) + (folder / "CMakeFiles" / "marker.txt").write_text("x", encoding="utf-8") + (folder / "keep.o").write_text("object", encoding="utf-8") + return folder + + +class OtherGenerator(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + + def call(self, folder): + out = io.StringIO() + with contextlib.redirect_stdout(out): + return setup.fresh_if_other_generator(folder), out.getvalue() + + def test_the_generator_is_read_from_the_cache(self): + self.assertEqual(setup.configured_generator(configured(self.root / "a", "Unix Makefiles")), "Unix Makefiles") + self.assertEqual(setup.configured_generator(configured(self.root / "b", "Ninja")), "Ninja") + self.assertIsNone(setup.configured_generator(self.root / "never")) + + def test_a_folder_made_with_makefiles_is_configured_again(self): + folder = configured(self.root / "build", "Unix Makefiles") + again, said = self.call(folder) + self.assertTrue(again) + self.assertIn("Unix Makefiles", said) + self.assertIn("Ninja", said) + self.assertFalse((folder / "CMakeCache.txt").exists()) + self.assertFalse((folder / "CMakeFiles").exists()) + self.assertTrue((folder / "keep.o").exists(), "only the CMake cache goes, no other file of the folder") + + def test_a_ninja_folder_and_a_new_folder_are_left_alone(self): + folder = configured(self.root / "ninja", "Ninja") + again, said = self.call(folder) + self.assertFalse(again) + self.assertEqual(said, "") + self.assertTrue((folder / "CMakeCache.txt").exists() and (folder / "CMakeFiles" / "marker.txt").exists()) + self.assertEqual(self.call(self.root / "new"), (False, "")) + self.assertFalse((self.root / "new").exists(), "a folder that does not exist is not created by the check") + + def test_cmake_build_does_it_before_it_configures(self): + folder = configured(self.root / "build", "Unix Makefiles") + seen = [] + + def fake_run(cmd, **kw): + seen.append((list(map(str, cmd)), (folder / "CMakeCache.txt").exists())) + return mock.Mock(returncode=0) + + with mock.patch.object(setup, "ensure_build_tools", return_value=("cmake", "ninja")), \ + mock.patch.object(setup.acquisition, "require"), mock.patch.object(setup, "WIN", False), \ + mock.patch.object(setup, "run", fake_run), contextlib.redirect_stdout(io.StringIO()): + setup.cmake_build(self.root, folder, "strata", [], None, "") + configure = seen[0] + self.assertIn("Ninja", configure[0]) + self.assertFalse(configure[1], "the old cache was gone when cmake was asked to configure") + + +if __name__ == "__main__": + unittest.main() From bb62a048b89aa86c55530cf715a7989376791cc5 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:35:15 +0100 Subject: [PATCH 16/45] updater: a failed test start keeps the runtime records, not only the engine log tail (#3654) The sandbox of a test start was deleted at once, so the PID records that show why a start failed were lost; only the last 64 KiB of the engine log stayed. A failed start now also keeps run.json (without keys), the host, child and ready JSON records of the runtime (tokens cut to their first 8 characters) and the host and server logs in .updates/logs/test-start--failed. The last three failed starts are kept. Best effort, never hides the failure. Tests: tests/terminal/test_updater.py (FailedStartRecords). --- strata_control/updater.py | 53 ++++++++++++++++++++++++++++++ tests/terminal/test_updater.py | 59 ++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) diff --git a/strata_control/updater.py b/strata_control/updater.py index d5a7f7eb..30f226ac 100644 --- a/strata_control/updater.py +++ b/strata_control/updater.py @@ -792,6 +792,55 @@ def _keep_log(sandbox: Path, component: ec.EngineComponent, ctx: Context) -> Non pass +_RECORD_LIMIT = 65536 # bytes read from any one kept file +_RECORDS_KEPT = 3 # failed test starts whose records stay in .updates/logs + + +def _scrub(value, key: str = ""): + """A kept JSON record without anything that could authorise a request: keys that name a token or a key keep only their first + characters (enough to see that two records agree), the API key is dropped.""" + if isinstance(value, dict): + return {k: _scrub(v, str(k)) for k, v in value.items()} + if isinstance(value, list): + return [_scrub(v, key) for v in value] + low = key.lower() + if isinstance(value, str) and value and ("api_key" in low or low in ("key", "authorization")): + return "" + if isinstance(value, str) and ("token" in low or "secret" in low or low.endswith("_key")): + return value[:8] + "...(rest removed)" + return value + + +def _keep_records(sandbox: Path, component: ec.EngineComponent, ctx: Context) -> None: + """A failed test start keeps what the sandbox knew, because the sandbox is deleted right after (#3654): the run config the test used + (without keys), the host, child and ready records of the runtime (their PIDs show a mismatch), and the host and server logs, next to the + engine log in ``.updates/logs/test-start--failed``. The last few failed starts are kept. Best effort: it never hides the failure.""" + try: + target = updates_dir(ctx.components) / "logs" / f"test-start-{component.version}-failed" + shutil.rmtree(target, ignore_errors=True) + target.mkdir(parents=True) + wanted = [sandbox / "run.json", sandbox / "engine.log"] + wanted += sorted((sandbox / "runtime").glob("*.json")) + sorted((sandbox / "runtime").glob("*.log")) + for source in wanted: + try: + if not source.is_file(): + continue + data = source.read_bytes()[-_RECORD_LIMIT:] + if source.suffix == ".json": + try: + data = (json.dumps(_scrub(json.loads(data.decode("utf-8-sig"))), indent=1) + "\n").encode("utf-8") + except ValueError: + pass # not JSON after all: kept as it is + (target / source.name).write_bytes(data) + except OSError: + continue + folders = sorted((d for d in target.parent.glob("test-start-*-failed") if d.is_dir()), key=lambda d: d.stat().st_mtime) + for old in folders[:-_RECORDS_KEPT]: + shutil.rmtree(old, ignore_errors=True) + except OSError: + pass + + def _warn_if_deep(ctx: Context, folder: Path, longest_inside: int) -> None: """Tell the person, in plain words, when the engine will sit too deep for Windows' ordinary path limit and long paths are off. The install continues: Strata's own file work uses extended paths; only the engine's own loading may not.""" @@ -916,14 +965,18 @@ def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Con started = {**started, **runtime.verify(name, timeout=min(ctx.test_timeout, 600), load=True)} if not started.get("ok") or started.get("state") != "ready" or started.get("generation_ready") is not True: _keep_log(sandbox, component, ctx) + _keep_records(sandbox, component, ctx) raise _test_start_failure(component, started, ctx, _log_tail(sandbox, component)) _keep_log(sandbox, component, ctx) return {"mode": "full", "model": cfg.get("model_name") or source.stem, "state": started["state"], "generation_ready": True, "detail": "started, answered a one-token probe, stopped"} except TestStartFailed: _keep_log(sandbox, component, ctx) + _keep_records(sandbox, component, ctx) raise except Exception as exc: # noqa: BLE001 + _keep_log(sandbox, component, ctx) + _keep_records(sandbox, component, ctx) raise TestStartFailed(component.version, f"{type(exc).__name__}: {exc}") from None finally: try: diff --git a/tests/terminal/test_updater.py b/tests/terminal/test_updater.py index 4969a34d..267506a4 100644 --- a/tests/terminal/test_updater.py +++ b/tests/terminal/test_updater.py @@ -799,5 +799,64 @@ class AnotherCardFamilyNote(unittest.TestCase): self.assertEqual(report["note"], "This build of Strata is for AMD RX 7000 cards. This computer has an AMD RX 9000 card (gfx1201). Ask for the RX 9000 build.") +class FailedStartRecords(LazyModel): + """#3654: a failed test start used to leave only the last 64 KiB of the engine log, because the sandbox that held the host, child and + ready records was deleted at once. The records are kept (without tokens or keys) next to the log.""" + + def failing_start(self): + def start(name, **kw): + runtime_dir = Path(os.environ["STRATA_RUNTIME_DIR"]) # the sandbox's, set by default_test_start + runtime_dir.mkdir(parents=True, exist_ok=True) + (runtime_dir / f"{name}.json").write_text(json.dumps({"pid": 4321, "token": "a1b2c3d4" * 8, "state": "starting"}), encoding="utf-8") + (runtime_dir / f"{name}-{'a1b2c3d4' * 8}.child.json").write_text(json.dumps({"host_token": "a1b2c3d4" * 8, "child_pid": 111}), encoding="utf-8") + (runtime_dir / f"{name}-9f.ready.json").write_text(json.dumps({"pid": 222, "api_key": "sekret-key"}), encoding="utf-8") + (runtime_dir / f"{name}.server.log").write_text("server: model loaded\nserver: pid 222\n", encoding="utf-8") + (runtime_dir / f"{name}.host.log").write_text("", encoding="utf-8") + return {"ok": False, "state": "starting", "error": "startup_wait_expired", "phase": "ready_file_not_matched"} + return start + + def test_the_runtime_records_of_a_failed_start_are_kept_without_tokens_or_keys(self): + from strata_control import runtime + self.install_current() + folder = fx.build_package(self.root / "lazy", "0.1.46", key=self.key) + stage = self.root / "stage" + (stage / "engine").mkdir(parents=True) + shutil.copytree(folder, stage / "engine" / folder.name) + component = ec.read_manifest(stage / "engine" / folder.name) + self.config.write_text(json.dumps({**json.loads(self.config.read_text()), "api_key": "sekret-key"}), encoding="utf-8") + with mock.patch.object(runtime, "start", side_effect=self.failing_start()), mock.patch.object(runtime, "stop", return_value={}): + with self.assertRaises(updater.TestStartFailed): + updater.default_test_start(stage, component, self.ctx()) + kept = updater.updates_dir(self.components) / "logs" / f"test-start-{component.version}-failed" + names = sorted(p.name for p in kept.iterdir()) + self.assertIn("run.json", names) + self.assertTrue(any(n.endswith(".child.json") for n in names), names) + self.assertTrue(any(n.endswith(".ready.json") for n in names), names) + self.assertIn("updtest.server.log", names) + text = "".join(p.read_text(encoding="utf-8") for p in kept.iterdir()) + self.assertNotIn("sekret-key", text) + self.assertNotIn("a1b2c3d4a1b2c3d4", text, "no full token is kept") + self.assertIn('"child_pid": 111', text) # the PIDs that show a mismatch are + self.assertIn("server: pid 222", text) + self.assertFalse((self.components / ".updates").exists() and any(p.name.startswith("t-") for p in (self.components / ".updates").rglob("*") if p.is_dir()), + "the sandbox itself is still removed") + + def test_only_the_last_few_failed_starts_are_kept(self): + logs = updater.updates_dir(self.components) / "logs" + for i in range(5): + folder = logs / f"test-start-0.1.4{i}-failed" + folder.mkdir(parents=True) + (folder / "run.json").write_text("{}", encoding="utf-8") + os.utime(folder, (1_700_000_000 + i, 1_700_000_000 + i)) + from types import SimpleNamespace + sandbox = self.root / "sandbox" + sandbox.mkdir() + (sandbox / "run.json").write_text("{}", encoding="utf-8") + updater._keep_records(sandbox, SimpleNamespace(version="0.1.49"), self.ctx()) + left = sorted(p.name for p in logs.glob("test-start-*-failed")) + self.assertEqual(len(left), 3, left) + self.assertIn("test-start-0.1.49-failed", left) + + if __name__ == "__main__": unittest.main() From e6f598c0a2a0b11a1336aa03eca722a5a94572ae Mon Sep 17 00:00:00 2001 From: Norm <304706238+Buddychek@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:36:43 +0100 Subject: [PATCH 17/45] docs: STRATA_VCVARS, /metrics/prometheus behind the API key, and the Monitor's prompt speed (#3244) Three 0.1.42 changes no page told. Ported by hand from PR #3244 by Buddychek (the PR conflicted with the rewritten pages), each sentence checked against the code: /metrics/prometheus needs the API key like /metrics (serve/server.py _authorized), the prompt-speed row is (prompt_tokens - reused) / prompt_ms (apps/host/server/monitor-dashboard.mjs), STRATA_VCVARS is read by setup.find_vcvars. The compiler text now says Visual Studio 2022 (2019 is refused since 0.2.5, #3566) and went to docs/SOURCE_INSTALL.md. --- SECURITY.md | 5 +++-- docs/DETAILS.md | 4 +++- docs/SOURCE_INSTALL.md | 7 +++++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 8bd61c84..8afbf44c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -23,8 +23,9 @@ this PC only. The details and every setting are in [docs/DETAILS.md](docs/DETAIL - **Where it listens.** `127.0.0.1` by default. `--host 0.0.0.0` (or `"host"` in `strata-.json`) opens it to your network, and the server then warns when no API key is set. - **API key.** `"api_key"` in the run config (or `STRATA_API_KEY`) is required on `/v1/*` and on every endpoint - that shows the model's state, requests or answers (`/status`, `/metrics`, `/settings`, `/mcp`, `/props`, `/slots`, - `/api/requests`, `/config`) and on every `POST`. It is compared in constant time. Set one before you open the + that shows the model's state, requests or answers (`/status`, `/metrics`, `/metrics/prometheus`, `/settings`, + `/mcp`, `/props`, `/slots`, `/api/requests`, `/config`) and on every `POST`. It is compared in constant time. + Set one before you open the server to your network or put a tunnel in front of it. - **Host check (DNS rebinding, 0.1.38).** Without an API key the server answers only requests whose `Host` is a name it knows (`localhost`, an IP address, the address it listens on and, when it listens beyond this PC, this PC's diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 43538ddc..9ccf7685 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -292,7 +292,9 @@ files, read time; `routing prefetch`: how many file reads had been warmed). The `GET /metrics` lists `ram_blobs`, `file_blobs`, `file_mb`, `drafts_offered` and `drafts_accepted` per recent request, with `totals` since the start. `hit_rate` is the VRAM share of the experts looked up; experts the GPU reads over PCIe (`--pcie-frac`) are not in it, so a higher `--pcie-frac` raises it even when decoding gets slower. `pcie_share` is their -share of all routed experts. The Monitor tab shows both. +share of all routed experts. The Monitor tab shows both. The request list in the Monitor tab also shows the prompt's own speed: what the cache already held is not read +again, so it is the fresh tokens (`prompt_tokens` minus `reused`) over the prompt time (`prompt_ms`), and a request that read no +new token shows no number. Profiling: start the server with `STRATA_DECODE_TIMING=1` (and `STRATA_VERIFY_PROFILE=1` for the GPU side). After each request the engine log has a `strata decode timing:` line and a `strata decode GPU stages (ms/window):` line. The GPU profile slows diff --git a/docs/SOURCE_INSTALL.md b/docs/SOURCE_INSTALL.md index 1c0d7ec0..1db38150 100644 --- a/docs/SOURCE_INSTALL.md +++ b/docs/SOURCE_INSTALL.md @@ -34,6 +34,13 @@ In PowerShell, prefix the wrapper with `.\`, for example `.\START-HERE.bat`. `SETUP.bat` opens setup again to add a model or change settings. The wrapper can reuse an existing install; first-start and later load times depend on the pack, disk, RAM and backend. A model can take several minutes to load. +When no ready-made engine fits the PC, setup compiles one. That needs the Visual Studio 2022 Build Tools with the C++ workload; +Visual Studio 2019 is too old (the sources are C++20). With a CUDA toolkit, CUDA 13.0 to 13.2 accept Visual Studio 2022 only, and +Visual Studio 2026 works from CUDA 13.3. The CPU image encoder alone (no CUDA toolkit on the PC) builds with MSVC and takes any +Visual Studio that has the C++ tools. If setup cannot find an install it could use, name the file before running it, for example +`set STRATA_VCVARS=C:\Program Files\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat`. Setup uses that file +only if it exists; a wrong path is answered as no build tools at all. + ## From source: Linux Clone or extract the source, enter its folder, then run: From f06bfc30e75926a911e7eb2574b9445222058f1a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:37:19 +0100 Subject: [PATCH 18/45] docs/TROUBLESHOOTING.md: the Windows AMD driver-reset entry is back The 0.2.5 rewrite of the page dropped the 'Windows AMD: the driver resets' entry (v0.2.4.2 had it), although setup.py still tells a Windows gfx12 card owner to read it and tools/test_setup_amd.py (TdrPointer) checks for it, so that test failed on main. Restored from v0.2.4.2 with the log and config locations worded for a source checkout. --- docs/TROUBLESHOOTING.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 1c5035cb..f55fba05 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -116,6 +116,40 @@ Check system logs for an out-of-memory kill. Also check `ulimit -R`: a desktop-s kill even when memory is available. The engine prints a warning for that condition; see the [detailed troubleshooting table](DETAILS.md#troubleshooting) before changing system limits. +**Windows AMD: the driver resets (VIDEO_ENGINE_TIMEOUT_DETECTED / screen flicker / the engine dies mid-answer).** +Windows gives a GPU about 2 seconds to answer; when a graphics card does not, it resets the driver (a TDR): the screen +flickers, the engine dies, and the Event Viewer shows `VIDEO_ENGINE_TIMEOUT_DETECTED` (#613, with #579 and #541 on +Linux). Strata 0.1.39 and newer say "the GPU stopped responding" in the log. It was seen with KV streaming on +(`--kv-resident 32768`, which setup turns on from 64K context) while reading a long prompt on a gfx1201 card. Try these +in order, one at a time, and tell us what changed: +1. **Send us the evidence.** The last ~80 lines of the engine log (`strata-.log` in the Strata folder of a source checkout; the server window + shows the same lines), your AMD driver version (AMD Software > System), your card and Windows version, the Strata + version, and the exact steps (context size, how long the prompt was, which app sent it). If Windows wrote a + dump, the newest `.dmp` in `C:\Windows\LiveKernelReports\WATCHDOG` (or `C:\Windows\Minidump`) helps; it holds no + chats, only the driver state. +2. **Find the step that hangs:** add `"STRATA_PF_STEP_SYNC": "1"` to the `"env"` block of the model's run config (`strata-.json` + in a source checkout) and restart. The prompt path then waits for the GPU after each step and logs any step over 250 ms, so the log names + the step. It is slower; use it to diagnose, then take it out. +3. **`"STRATA_KV_HOST_DMA": "1"`** in the same `"env"` block: no GPU kernel writes the RAM copy of the K/V during a + prompt, it is copied by DMA instead. Same answers. +4. **No KV streaming:** run setup again and pick 32K context (or remove `--kv-resident` and its number from + `"args"` in the JSON, with a context that fits the VRAM). +5. **A smaller prompt chunk:** change `--prefill` in `"args"` (for example `--prefill 512`): each GPU launch then does + less work between two checks by Windows. Prompts are read more slowly. +6. **Optional, your decision: give Windows more time (`TdrDelay`).** The default is 2 seconds. In the registry, + `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers`, a DWORD `TdrDelay` of `10` (seconds) + lets a long GPU job finish before Windows resets the driver; restart the PC. It hides the symptom and does not fix + a GPU that has really hung, and a hung GPU then freezes the screen for those 10 seconds. Strata changes no Windows + setting itself; to undo it, delete the value. +7. **Driver:** use the newest AMD Software release for your card (Adrenalin, not a Windows Update driver) and restart + after installing. If it started after a driver update, tell us both versions; going back one version is a fair + test. + +**Large pinned host allocations fail on ROCm although RAM is free.** +See [AMD_HIP.md](AMD_HIP.md#model-and-serving-configuration): the mapped expert mode avoids the full pinned arena. + +**"verify: timed out at layer N" or "no progress for 60 s" on AMD (Linux), mostly with `--mmap-experts`.** + **A hand-edited engine option disappears.** The run config tracks explicit options in `user_args` and the generated baseline in `args_written`. Prefer the app's Expert settings or Terminal `--set` for supported overrides. Context, KV, picture reading and drafting are From 5b14fe23f7ea171ba473fec3c567f8c78b3af671 Mon Sep 17 00:00:00 2001 From: Norm <304706238+Buddychek@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:38:42 +0100 Subject: [PATCH 19/45] tests: three suite gaps a live PC showed (#3236) test_iq_pack imports without llama.cpp's gguf-py and skips the classes that build GGUF fixtures with a named reason; the MCP discovery tests use a free port, not whatever Strata serves on 8080; the six conversation-cache tests add the repo root to sys.path so they run from the repo root as the suite does. Ported from PR #3236 by Buddychek (tests only, no shipped code). --- tools/test_conversation_cache_disabled.py | 2 ++ tools/test_conversation_cache_growth.py | 2 ++ tools/test_conversation_cache_http_smoke.py | 2 ++ tools/test_conversation_cache_isolation.py | 2 ++ tools/test_conversation_cache_parity.py | 2 ++ tools/test_conversation_cache_soak.py | 2 ++ tools/test_iq_pack.py | 30 ++++++++++++++++++--- tools/test_strata_mcp.py | 4 +++ 8 files changed, 42 insertions(+), 4 deletions(-) diff --git a/tools/test_conversation_cache_disabled.py b/tools/test_conversation_cache_disabled.py index d389ac9f..59c3e685 100644 --- a/tools/test_conversation_cache_disabled.py +++ b/tools/test_conversation_cache_disabled.py @@ -8,6 +8,8 @@ import sys import tempfile import unittest +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_disabled import NAMES, SETTINGS, STATE_KEYS, common_args, state_hashes, verify diff --git a/tools/test_conversation_cache_growth.py b/tools/test_conversation_cache_growth.py index 36423449..f89f2be8 100644 --- a/tools/test_conversation_cache_growth.py +++ b/tools/test_conversation_cache_growth.py @@ -8,6 +8,8 @@ import sys import tempfile import unittest +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_growth import NAMES, SECRET, SETTINGS, STATE_KEYS, verify diff --git a/tools/test_conversation_cache_http_smoke.py b/tools/test_conversation_cache_http_smoke.py index fd0a79d2..50211a87 100644 --- a/tools/test_conversation_cache_http_smoke.py +++ b/tools/test_conversation_cache_http_smoke.py @@ -9,6 +9,8 @@ import tempfile import unittest from unittest.mock import Mock +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_http_smoke import run diff --git a/tools/test_conversation_cache_isolation.py b/tools/test_conversation_cache_isolation.py index 7205d4d4..d87e9287 100644 --- a/tools/test_conversation_cache_isolation.py +++ b/tools/test_conversation_cache_isolation.py @@ -7,6 +7,8 @@ import sys import tempfile import unittest +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_isolation import STATE_KEYS, fixtures, verify from tools.gguf_reader import GGUFFile diff --git a/tools/test_conversation_cache_parity.py b/tools/test_conversation_cache_parity.py index 3f950ebd..b9a79013 100644 --- a/tools/test_conversation_cache_parity.py +++ b/tools/test_conversation_cache_parity.py @@ -6,6 +6,8 @@ import sys import tempfile import unittest +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_parity import STATE_KEYS, engine_args, pressure_budget_hint, verify_admission, verify_exchange, verify_pressure, verify_results diff --git a/tools/test_conversation_cache_soak.py b/tools/test_conversation_cache_soak.py index 7d815890..7ac12a6d 100644 --- a/tools/test_conversation_cache_soak.py +++ b/tools/test_conversation_cache_soak.py @@ -6,6 +6,8 @@ import sys import tempfile import unittest +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_soak import STATE_KEYS, answer_text, verify diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py index 0e0f5e8b..f1faeabe 100644 --- a/tools/test_iq_pack.py +++ b/tools/test_iq_pack.py @@ -14,9 +14,25 @@ import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parent)) # runnable from the repo root too from _paths import add_gguf_py -add_gguf_py() -from gguf import GGUFWriter, GGMLQuantizationType as Q, quants -import iq_pack +import iq_pack # needs numpy + gguf_reader only, not gguf-py: import it unguarded + +try: + add_gguf_py() # llama.cpp's gguf-py: setup.py clones it; gguf_py() exits when absent + from gguf import GGUFWriter, GGMLQuantizationType as Q, quants +except SystemExit: + GGUF_PY = None +else: + GGUF_PY = "found" + + +def require_gguf_py(test): + """setUpClass for the classes that build GGUF fixtures: skip (not fail) on a checkout without llama.cpp.""" + @classmethod + def setUpClass(cls): + if GGUF_PY is None: + raise unittest.SkipTest("llama.cpp's gguf-py not found: run setup.py (it clones llama.cpp into " + "third_party/) or set STRATA_GGUF_PY") + return setUpClass def write_gguf(path, tensors, split=None, arch=True): @@ -37,6 +53,7 @@ def write_gguf(path, tensors, split=None, arch=True): class CompatibilityTests(unittest.TestCase): + setUpClass = require_gguf_py(unittest.TestCase) def test_bf16_halfway_rounds_to_even(self): values = np.array([0x3F808000, 0x3F818000, 0xBF808000, 0xBF818000], dtype=np.uint32) got = np.frombuffer(iq_pack.bf16_bytes(values.view(np.uint8), "F32"), dtype=np.uint16) @@ -253,6 +270,8 @@ class ConversionTests(unittest.TestCase): """CS2: FORM decides the engine's form; exact F32->BF16 by default, rounding only with --compat-bf16, the PLE conv F32 -> F16 by the loader (index kind 3), non-finite values refused, every conversion in conversions.json.""" + setUpClass = require_gguf_py(unittest.TestCase) + def test_exact_f32_to_bf16_by_default(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: x = bits(np.arange(64, dtype=np.uint32).reshape(2, 32) << 16 | 0x3F000000) # BF16 values held as F32 @@ -362,8 +381,9 @@ def expert(seed, shape): return np.random.default_rng(seed).standard_normal((N_EXPERT, *shape)).astype(np.float32) -def split_model(root, name="model", split_layer=True, dup=False, split_no=None, gate1=Q.Q8_0, seed=0): +def split_model(root, name="model", split_layer=True, dup=False, split_no=None, gate1=None, seed=0): """Writes the 4 shards; returns their paths.""" + gate1 = Q.Q8_0 if gate1 is None else gate1 # not a default arg: the module imports without gguf-py gu, dn = (32, 32), (32, 32) router = [(f"blk.{l}.ffn_gate_inp.weight", np.full((N_EXPERT, 32), 0.5, np.float32), Q.F32) for l in (0, 1)] l0 = [(f"blk.0.ffn_{r}_exps.weight", expert(seed + 10 + i, gu if r != "down" else dn), Q.Q8_0) @@ -406,6 +426,7 @@ def expected_experts(model): class SplitArtifactTests(unittest.TestCase): + setUpClass = require_gguf_py(unittest.TestCase) def test_four_shards_and_a_layer_split_per_role(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) @@ -689,6 +710,7 @@ class HadamardTests(unittest.TestCase): class NativeExpertsV5Tests(unittest.TestCase): """The v5 mark (Hadamard-folded experts) rewrites only the tables the packer writes, v3 and v4.""" + setUpClass = require_gguf_py(unittest.TestCase) # test_packer_refuses_before_writing builds GGUF fixtures ROWS = "0 145 146 0 100 1 2 3\n1 145 146 100 100 4 5 6\n" def table(self, version, tail="(n_expert 2, total 200)"): diff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.py index 0fdb78bc..fab2199f 100644 --- a/tools/test_strata_mcp.py +++ b/tools/test_strata_mcp.py @@ -164,8 +164,12 @@ class FakeRoot(unittest.TestCase): self.strata.disk_free = lambda p: 1000.0 self.tools = M.Tools(self.strata) self.extra = [] + # the tests must never see a Strata server that happens to run on the real default port on this PC + self._default_port = M.DEFAULT_PORT + M.DEFAULT_PORT = free_port() def tearDown(self): + M.DEFAULT_PORT = self._default_port for p in self.extra: if p.poll() is None: p.kill() From 2ac3482144e98330b59331d17b83f9d56d550312 Mon Sep 17 00:00:00 2001 From: l33tm4st3r <26746186+l33tm4st3r@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:41:53 +0100 Subject: [PATCH 20/45] bench: the standard report names an AMD card and its ROCm runtime when only amd-smi exists (#3519) ROCm 7 and newer ship amd-smi and no rocm-smi, and the amdgpu product_name is empty on gfx1201, so a Radeon AI PRO R9700 run was filed under 'unknown' with 'runtime: not measured'. bench_facts reads the market name from amd-smi static --asic, the VRAM from the amdgpu sysfs file of the PCI address amd-smi list reports, the ROCm version from the install (or amd-smi -h), and keeps the probe's card name when the server only says 'AMD Radeon'. Ported from PR #3519 by l33tm4st3r with its tests and the BENCHMARK_PROTOCOL.md text. Changed while porting: the amd-smi branch also took macOS (os.name is posix there), which would have hidden the Apple chip; it now skips darwin, and a test keeps the chip. --- docs/BENCHMARK_PROTOCOL.md | 7 +- strata_cli/bench_facts.py | 67 ++++++++++- tests/terminal/test_bench_facts_amd.py | 157 +++++++++++++++++++++++++ 3 files changed, 227 insertions(+), 4 deletions(-) create mode 100644 tests/terminal/test_bench_facts_amd.py diff --git a/docs/BENCHMARK_PROTOCOL.md b/docs/BENCHMARK_PROTOCOL.md index 29e9e9eb..949f9d8f 100644 --- a/docs/BENCHMARK_PROTOCOL.md +++ b/docs/BENCHMARK_PROTOCOL.md @@ -329,7 +329,12 @@ An install with neither has no commit, and the run is `nonconforming`. `engine_v from `/props` (`build_info`), or `/v1/status` when `/props` has none. `build_kind` is `source` when the folder has a `.git`, otherwise `release`. The runner cannot read build options from a server; pass `--build-options` for a source build. The drivers and the CUDA version come from `nvidia-smi` (or `rocm-smi`, or the Windows display -driver key), read on the machine that runs the engine. +driver key), read on the machine that runs the engine. ROCm 7 and newer ship `amd-smi` and no `rocm-smi`: the card's +name is that tool's `static --asic` market name, its memory is the amdgpu sysfs file of the PCI address `amd-smi list` +reports, and the `rocm` runtime entry is the version file inside the ROCm install (`amd-smi -h` prints the same +version). Where the kernel builds amdgpu in there is no driver version to read, and `gpu-driver` stays null with a +reason. When the server can only name a vendor, because the amdgpu `product_name` is empty on some cards, the card the +local probe named is kept instead. Except for typed objects, arrays, numbers and booleans identified above, identity and descriptive fields are strings (or null with a reason where unavailable). Empty configuration objects mean no relevant options; diff --git a/strata_cli/bench_facts.py b/strata_cli/bench_facts.py index 309223bf..026b5c49 100644 --- a/strata_cli/bench_facts.py +++ b/strata_cli/bench_facts.py @@ -1,12 +1,13 @@ """What a standard benchmark report says about the machine, the build, the model and the settings (docs/BENCHMARK_PROTOCOL.md). -Every probe is best effort and local: it reads the inference host's own tools (nvidia-smi, rocm-smi, PowerShell, /proc, sysctl) and the +Every probe is best effort and local: it reads the inference host's own tools (nvidia-smi, rocm-smi, amd-smi, PowerShell, /proc, sysctl) and the server's answers. A fact that cannot be read becomes `None` with a reason in `Why`, never a guess. Nothing here changes the machine. """ from __future__ import annotations import getpass +import glob import hashlib import json import os @@ -193,6 +194,37 @@ def other_gpus() -> tuple[list[dict], str | None]: driver = next((c.get("driver") for c in found if c.get("driver")), None) except Exception: # noqa: BLE001 - a report without the card's name is still a report pass + elif os.name != "nt" and sys.platform != "darwin": # (a Mac has no AMD card to ask for; its chip is read below) + # ROCm 7 and newer ship amd-smi and no rocm-smi (verified on ROCm 10.1). Different grammar: `static --asic` + # gives the marketing name, `static --driver` the kernel driver's version, and the PCI address only comes + # from `amd-smi list`; the VRAM size is the amdgpu driver's sysfs file for that address. + def amd_json(args): + try: + return json.loads(run_cmd(["amd-smi", "static"] + args + ["--json"]).strip() or "{}").get("gpu_data") or [] + except (ValueError, OSError): + return [] + try: + bdf = {e.get("gpu"): (e.get("bdf") or "") for e in json.loads(run_cmd(["amd-smi", "list", "--json"]).strip() or "[]")} + except (ValueError, OSError): + bdf = {} + drv = {e.get("gpu"): ((e.get("driver") or {}).get("version") or "") for e in amd_json(["--driver"])} + for i, e in enumerate(amd_json(["--asic"])): + name = ((e.get("asic") or {}).get("market_name") or "").strip() + if not name: + continue + d = drv.get(e.get("gpu"), "") + driver = driver or (d if d.upper() not in ("", "N/A") else None) + vram = None + for dev in glob.glob("/sys/class/drm/card[0-9]*/device"): + try: + if bdf.get(e.get("gpu")) and os.path.basename(os.path.realpath(dev)).lower() == bdf[e["gpu"]].lower(): + with open(os.path.join(dev, "mem_info_vram_total"), encoding="utf-8") as f: + total = f.read().strip() + vram = int(total) if total.isdigit() else None + except OSError: + pass + cards.append({"device_index": i, "name": name, "memory_bytes": vram, "memory_kind": "dedicated", + "power_limit_w": None}) elif sys.platform == "darwin": chip = cpu_name() if chip: @@ -201,6 +233,25 @@ def other_gpus() -> tuple[list[dict], str | None]: return cards, driver +def rocm_version() -> str | None: + """ROCm's own version, which `rocm-smi --showdriverversion` used to report with the driver. ROCm 10 has no + `rocm-smi` and no `/opt/rocm/.info/`: its version file sits under `/core/.info/version`, and + `amd-smi -h` prints the same version.""" + for base in [os.environ.get("ROCM_PATH", ""), "/opt/rocm"]: + if not base: + continue + for sub in (".info/version", "core/.info/version"): + try: + with open(os.path.join(base, sub), encoding="utf-8") as f: + found = f.read().strip() + if found: + return found + except OSError: + pass + match = re.search(r"ROCm version:\s*([\d.]+)", run_cmd(["amd-smi", "-h"])) + return match.group(1) if match else None + + def lsblk_disk(data: dict) -> list[dict] | None: """The first physical disk in `lsblk -J -s` output. `-s` lists the parents of a device as nested children: an LVM volume is lvm -> partition -> disk, two levels down, so the walk goes all the way down.""" @@ -277,7 +328,12 @@ def hardware(why: Why, *, selected: list[int], served_gpu: str | None, model_dir named = [c for c in cards if c["name"] == served_gpu] cards = named[:1] or cards[:1] served = [n for n in (served_gpu or "").split(" + ") if n and n != "?"] - if served and cards and not all(n in {c["name"] for c in cards} for n in served): + # the amdgpu driver's product_name is empty on some cards (gfx1201 among them), so the server falls back to a bare + # "AMD Radeon": that names the vendor, not the card, and the local probe's marketing name is the one to keep + stub = re.compile(r"(?i)^(amd radeon|advanced micro devices(,? inc\.?)?|nvidia( corporation)?|intel" + r"( corporation)?)( graphics)?$") + if served and cards and not all(stub.match(n) for n in served) \ + and not all(n in {c["name"] for c in cards} for n in served): # the server reads cards the local tools do not list (another vendor's, or a different numbering) cards = [{"device_index": i, "name": n, "memory_bytes": None, "memory_kind": "dedicated", "power_limit_w": None} for i, n in enumerate(served)] @@ -308,7 +364,10 @@ def hardware(why: Why, *, selected: list[int], served_gpu: str | None, model_dir if not declared_background: why.add(pointer("hardware", "background_workloads"), "the runner does not inspect other programs; none were declared with --background") - return block, {"driver": driver, "cuda": cuda} + # an AMD card on Linux runs on ROCm, which the report names as the runtime; on ROCm 7 and newer that version no + # longer comes from rocm-smi, but from the install itself + rocm = rocm_version() if (sys.platform.startswith("linux") and cards and not cuda) else None + return block, {"driver": driver, "cuda": cuda, "rocm": rocm} # ------------------------------------------------------------------------------------------------------------ software @@ -364,6 +423,8 @@ def software(why: Why, machine: dict, *, engine_version: str | None, build_optio runtime.append({"name": "cuda-driver-supports", "version": machine["cuda"]}) elif machine.get("cuda"): runtime.append({"name": "cuda", "version": machine["cuda"]}) + if machine.get("rocm") and not any(r.get("name") == "rocm" for r in runtime): + runtime.append({"name": "rocm", "version": machine["rocm"]}) if sys.platform == "darwin": runtime.append({"name": "metal", "version": platform.mac_ver()[0] or platform.release()}) drivers = [{"name": "gpu-driver", "version": machine["driver"]}] if machine.get("driver") else [] diff --git a/tests/terminal/test_bench_facts_amd.py b/tests/terminal/test_bench_facts_amd.py new file mode 100644 index 00000000..353f432f --- /dev/null +++ b/tests/terminal/test_bench_facts_amd.py @@ -0,0 +1,157 @@ +"""ROCm 7 and newer ship `amd-smi` and no `rocm-smi`, and the amdgpu driver's `product_name` is empty on gfx1201, so a +report from a Radeon wrote the vendor as the card ("AMD Radeon", `...-standard-unknown-...`) and `runtime: not +measured`. The strings below are the real output of `amd-smi static --asic --json`, `static --driver --json`, +`list --json` and `-h` on one AI PRO R9700 (gfx1201) with ROCm 10.1, trimmed to the fields the probe reads.""" +from __future__ import annotations + +import json +import os +import tempfile +import unittest +from unittest import mock + +from strata_cli import bench_facts as bf + +ASIC = {"gpu_data": [{"gpu": 0, "asic": {"market_name": "AMD Radeon AI PRO R9700", "target_graphics_version": "gfx1201"}}, + {"gpu": 1, "asic": {"market_name": "AMD Radeon Graphics", "target_graphics_version": "gfx1036"}}]} +DRIVER = {"gpu_data": [{"gpu": 0, "driver": {"name": "amdgpu", "version": "N/A", + "os_kernel_version": "7.3.0-rc6-2-cachyos-rc"}}]} +LIST = [{"gpu": 0, "bdf": "0000:03:00.0", "node_id": 1}, {"gpu": 1, "bdf": "0000:7c:00.0", "node_id": 2}] +HELP = "AMD System Management Interface | Version: 27.1.0+7da43026 | ROCm version: 10.1.0 |" +BDF_TO_TOTAL = {"0000:03:00.0": "34208743424", "0000:7c:00.0": "805306368"} + + +def run_cmd(cmd: list[str], timeout: float = 15) -> str: + """ROCm 10.1 answers, with `rocm-smi` missing entirely.""" + if cmd[:1] == ["rocm-smi"]: + return "" + if cmd[:3] == ["amd-smi", "list", "--json"]: + return json.dumps(LIST) + if cmd[:2] == ["amd-smi", "static"]: + return json.dumps(DRIVER if "--driver" in cmd else ASIC) + if cmd == ["amd-smi", "-h"]: + return HELP + return "" + + +@unittest.skipIf(os.name == "nt", "the probe is the non-Windows branch") +class AmdSmiProbe(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + # /sys/class/drm/cardN/device is a symlink whose target's last component is the PCI address; the probe matches + # that address against `amd-smi list`, so the fake tree repeats the shape instead of the path + devices = [] + for card, bdf in (("card1", "0000:03:00.0"), ("card2", "0000:7c:00.0")): + pci = os.path.join(self.tmp.name, "pci", bdf) + os.makedirs(pci) + with open(os.path.join(pci, "mem_info_vram_total"), "w", encoding="utf-8") as f: + f.write(BDF_TO_TOTAL[bdf] + "\n") + link = os.path.join(self.tmp.name, "drm", card, "device") + os.makedirs(os.path.dirname(link)) + os.symlink(pci, link) + devices.append(link) + self.globs = mock.patch.object(bf.glob, "glob", lambda pattern: devices) + self.globs.start() + self.addCleanup(self.globs.stop) + self.cmds = mock.patch.object(bf, "run_cmd", run_cmd) + self.cmds.start() + self.addCleanup(self.cmds.stop) + + def test_names_both_cards_with_their_vram(self): + cards, driver = bf.other_gpus() + self.assertEqual([c["name"] for c in cards], ["AMD Radeon AI PRO R9700", "AMD Radeon Graphics"]) + self.assertEqual([c["memory_bytes"] for c in cards], [34208743424, 805306368]) + self.assertEqual([c["device_index"] for c in cards], [0, 1]) + + def test_a_stub_driver_version_stays_unmeasured(self): + # `amd-smi static --driver` says N/A when amdgpu is built into the kernel: that is not a version, so the report + # must keep saying it did not measure one instead of writing "N/A" + _, driver = bf.other_gpus() + self.assertIsNone(driver) + + def test_an_asic_without_a_market_name_is_skipped(self): + blank = {"gpu_data": [{"gpu": 0, "asic": {"market_name": ""}}, + {"gpu": 1, "asic": {"market_name": "AMD Radeon AI PRO R9700"}}]} + with mock.patch.object(bf, "run_cmd", lambda cmd, timeout=15: json.dumps(blank) if "static" in cmd else ""): + cards, _ = bf.other_gpus() + self.assertEqual([c["name"] for c in cards], ["AMD Radeon AI PRO R9700"]) + + def test_rocm_version_comes_from_the_install(self): + base = os.path.join(self.tmp.name, "rocm") + os.makedirs(os.path.join(base, "core", ".info")) + with open(os.path.join(base, "core", ".info", "version"), "w", encoding="utf-8") as f: + f.write("10.1.0\n") + with mock.patch.object(bf.os, "environ", {"ROCM_PATH": base}): + self.assertEqual(bf.rocm_version(), "10.1.0") + + def test_rocm_version_falls_back_to_the_help_text(self): + real_open = open + + def refuse(path, *args, **kwargs): + if "/opt/rocm" in str(path): + raise OSError("no ROCm install here") + return real_open(path, *args, **kwargs) + + env = {k: v for k, v in os.environ.items() if k != "ROCM_PATH"} + with mock.patch.object(bf.os, "environ", env), mock.patch("builtins.open", side_effect=refuse): + self.assertEqual(bf.rocm_version(), "10.1.0") + + +@unittest.skipIf(os.name == "nt", "the probe is the non-Windows branch") +class ServedName(unittest.TestCase): + """The server's `gpu` string is the driver's product_name, empty on gfx1201, so it degrades to the vendor. That + must not overwrite the card the local probe named, while a card only the server can see still wins.""" + + def cards(self): + return [{"device_index": 0, "name": "AMD Radeon AI PRO R9700", "memory_bytes": 34208743424, + "memory_kind": "dedicated", "power_limit_w": None}] + + def hardware(self, served_gpu): + with mock.patch.object(bf, "nvidia_gpus", lambda: ([], None, None)), \ + mock.patch.object(bf, "other_gpus", lambda: (self.cards(), None)): + block, machine = bf.hardware(bf.Why(), selected=[], served_gpu=served_gpu, model_dir=None, + declared_background=[]) + return block, machine + + def test_a_vendor_only_name_does_not_replace_the_card(self): + block, machine = self.hardware("AMD Radeon") + self.assertEqual([c["name"] for c in block["gpus"]], ["AMD Radeon AI PRO R9700"]) + self.assertEqual(block["gpus"][0]["memory_bytes"], 34208743424) + + def test_a_card_only_the_server_lists_still_wins(self): + block, _ = self.hardware("AMD Radeon RX 7900 XTX") + self.assertEqual([c["name"] for c in block["gpus"]], ["AMD Radeon RX 7900 XTX"]) + self.assertIsNone(block["gpus"][0]["memory_bytes"]) + + def test_the_rocm_runtime_reaches_the_report(self): + why = bf.Why() + with mock.patch.object(bf, "nvidia_gpus", lambda: ([], None, None)), \ + mock.patch.object(bf, "other_gpus", lambda: (self.cards(), None)), \ + mock.patch.object(bf, "rocm_version", lambda: "10.1.0"): + _, machine = bf.hardware(why, selected=[], served_gpu="AMD Radeon", model_dir=None, + declared_background=[]) + software = bf.software(why, dict(machine), engine_version="0.1.46.2", build_options=None) + self.assertEqual(machine["rocm"], "10.1.0") + self.assertIn({"name": "rocm", "version": "10.1.0"}, software["runtime"]) + + +class MacStillReadsItsChip(unittest.TestCase): + """The amd-smi branch is for Linux; a Mac (os.name is posix there too) still takes its card from the chip name.""" + + def test_a_mac_is_not_sent_down_the_amd_smi_branch(self): + calls = [] + + def run(cmd, timeout=15): + calls.append(cmd[0]) + return "" + + with mock.patch.object(bf.os, "name", "posix"), mock.patch.object(bf.sys, "platform", "darwin"), mock.patch.object(bf, "run_cmd", run), mock.patch.object(bf, "cpu_name", lambda: "Apple M5 Max"), mock.patch.object(bf, "ram_bytes", lambda: 137438953472): + cards, driver = bf.other_gpus() + self.assertEqual([c["name"] for c in cards], ["Apple M5 Max"]) + self.assertEqual(cards[0]["memory_kind"], "shared") + self.assertNotIn("amd-smi", calls) + + +if __name__ == "__main__": + unittest.main() From c471588f3ec289d292ae2b330ea3efc7c1239265 Mon Sep 17 00:00:00 2001 From: l33tm4st3r <26746186+l33tm4st3r@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:46:33 +0100 Subject: [PATCH 21/45] bench: tools/strata_bench.py (BENCH.bat, bench.sh) names an AMD card on ROCm 7+ too (#3630) The quick speed check has its own GPU probe, separate from strata_cli/bench_facts.py, and tried nvidia-smi then rocm-smi only. On a Radeon with amd-smi alone it wrote the server's vendor stub and 'GPU driver: not read'. The same amd-smi probe as #3519 is added in the shape this file uses, and a bare vendor name from the server no longer replaces a card the probe named. Ported from PR #3630 by l33tm4st3r. The three new tests are POSIX-only (symlinks, /sys); run on z440 (Linux, Python 3.12): OK. tools/test_strata_bench.py on Windows: OK. --- tests/terminal/test_bench_community_amd.py | 90 ++++++++++++++++++++++ tools/strata_bench.py | 37 +++++++++ 2 files changed, 127 insertions(+) create mode 100644 tests/terminal/test_bench_community_amd.py diff --git a/tests/terminal/test_bench_community_amd.py b/tests/terminal/test_bench_community_amd.py new file mode 100644 index 00000000..2aa53068 --- /dev/null +++ b/tests/terminal/test_bench_community_amd.py @@ -0,0 +1,90 @@ +"""`bench.sh` (tools/strata_bench.py) has its own GPU probe, so the ROCm 7+ fix in strata_cli/bench_facts.py did not +reach it: with no `rocm-smi` on the box it wrote the server's vendor stub as the card ("AMD Radeon", +`...-community-unknown-...`) and `GPU driver: not read`. The strings below are the real answers of `amd-smi static +--asic --json`, `static --driver --json` and `list --json` on one AI PRO R9700 (gfx1201) plus a Ryzen iGPU, with ROCm +10.1, trimmed to the fields the probe reads.""" +from __future__ import annotations + +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from tools import strata_bench as sb + +ASIC = {"gpu_data": [{"gpu": 0, "asic": {"market_name": "AMD Radeon AI PRO R9700", "target_graphics_version": "gfx1201"}}, + {"gpu": 1, "asic": {"market_name": "AMD Radeon Graphics", "target_graphics_version": "gfx1036"}}]} +DRIVER = {"gpu_data": [{"gpu": 0, "driver": {"name": "amdgpu", "version": "N/A", + "os_kernel_version": "7.3.0-rc6-2-cachyos-rc"}}, + {"gpu": 1, "driver": {"name": "amdgpu", "version": "6.16.4"}}]} +LIST = [{"gpu": 0, "bdf": "0000:03:00.0", "node_id": 1}, {"gpu": 1, "bdf": "0000:7c:00.0", "node_id": 2}] +BDF_TO_TOTAL = {"0000:03:00.0": "34208743424", "0000:7c:00.0": "805306368"} + + +def run_cmd(cmd: list[str], timeout: float = 15) -> str: + """ROCm 10.1 answers, with `rocm-smi` missing entirely.""" + if cmd[:1] == ["rocm-smi"] or cmd[:1] == ["nvidia-smi"]: + return "" + if cmd[:3] == ["amd-smi", "list", "--json"]: + return json.dumps(LIST) + if cmd[:2] == ["amd-smi", "static"]: + return json.dumps(DRIVER if "--driver" in cmd else ASIC) + return "" + + +@unittest.skipIf(os.name == "nt", "the probe is the non-Windows branch") +class AmdSmiProbe(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + # /sys/class/drm/cardN/device is a symlink whose target ends in the PCI address; the fake tree repeats the + # shape, and the probe matches that address against `amd-smi list` + root = Path(self.tmp.name) + drm = root / "drm" + for card, bdf in (("card1", "0000:03:00.0"), ("card2", "0000:7c:00.0")): + real = root / "devices" / bdf + real.mkdir(parents=True) + (real / "mem_info_vram_total").write_text(BDF_TO_TOTAL[bdf], encoding="utf-8") + drm.mkdir(parents=True, exist_ok=True) + (drm / card).mkdir(exist_ok=True) + os.symlink(real, drm / card / "device") + self.drm = str(drm) + real_path = Path + + class DrmPath(real_path): + def __new__(cls, *a, **kw): + return real_path(self.drm) if a == ("/sys/class/drm",) else real_path(*a, **kw) + + self.drm_patch = mock.patch.object(sb, "Path", DrmPath) + self.drm_patch.start() + self.addCleanup(self.drm_patch.stop) + self.cmd_patch = mock.patch.object(sb, "run_cmd", run_cmd) + self.cmd_patch.start() + self.addCleanup(self.cmd_patch.stop) + + def test_the_probe_names_both_cards(self): + info = sb.gpu_info_local() + self.assertEqual([g["name"] for g in info["gpus"]], ["AMD Radeon AI PRO R9700", "AMD Radeon Graphics"]) + self.assertEqual([g["vram_mib"] for g in info["gpus"]], [34208743424 >> 20, 805306368 >> 20]) + self.assertEqual([g["driver"] for g in info["gpus"]], [None, "6.16.4"]) + self.assertEqual(info.get("rocm_driver"), "6.16.4") + + def test_the_folder_names_the_card_it_used(self): + # the suite reports the card the engine runs on: the words gpu_slug drops are the vendor ones only + self.assertEqual(sb.gpu_slug({"gpu": ["AMD Radeon AI PRO R9700"]}), "ai-pro-r9700") + + def test_the_vendor_stub_does_not_replace_the_card(self): + metrics = {"hardware_static": {"gpu_name": "AMD Radeon", "cpu_name": "AMD Ryzen 9 9950X3D", + "cores": 16, "threads": 32}, "engine": {}} + with mock.patch.object(sb, "try_json", lambda base, path, key="", timeout=20: metrics if path == "/metrics" else {}): + m = sb.collect_machine("http://127.0.0.1:1", "", None) + self.assertEqual(m["gpu"], ["AMD Radeon AI PRO R9700"]) + self.assertEqual(m["gpu_vram_mib"], 34208743424 >> 20) + self.assertEqual(m["gpu_driver"], None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/strata_bench.py b/tools/strata_bench.py index be0e39cf..36d919e7 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -502,6 +502,39 @@ def gpu_info_local() -> dict: m2 = re.search(r"Driver version:\s*(\S+)", v) if m2: info["rocm_driver"] = m2.group(1) + if not info["gpus"] and os.name != "nt": + # ROCm 7 and newer ship `amd-smi` and no `rocm-smi`, so a Radeon wrote the server's vendor stub ("AMD + # Radeon", `...-community-unknown-...`) and `GPU driver: not read`. `static --asic` gives the marketing + # name, `static --driver` the kernel driver's version, the PCI address only comes from `amd-smi list` and + # the VRAM size is the amdgpu driver's sysfs file for that address (same probe as strata_cli/bench_facts.py). + def amd_json(args): + try: + return json.loads(run_cmd(["amd-smi", "static"] + args + ["--json"]).strip() or "{}").get("gpu_data") or [] + except ValueError: # noqa: BLE001 - a report without the card's name is a report + return [] + try: + bdf = {e.get("gpu"): (e.get("bdf") or "") for e in json.loads(run_cmd(["amd-smi", "list", "--json"]).strip() or "[]")} + except ValueError: + bdf = {} + drv = {e.get("gpu"): ((e.get("driver") or {}).get("version") or "") for e in amd_json(["--driver"])} + cards = [] + for e in amd_json(["--asic"]): + name = ((e.get("asic") or {}).get("market_name") or "").strip() + if not name: + continue + d = drv.get(e.get("gpu"), "") + d = d if d.upper() not in ("", "N/A") else None + if d: + info["rocm_driver"] = info.get("rocm_driver") or d + vram = None + for dev in Path("/sys/class/drm").glob("card[0-9]*/device"): + try: + if bdf.get(e.get("gpu")) and os.path.basename(os.path.realpath(dev)).lower() == bdf[e["gpu"]].lower(): + vram = int((dev / "mem_info_vram_total").read_text(encoding="utf-8").strip()) >> 20 + except (OSError, ValueError): + pass + cards.append({"name": name, "vram_mib": vram, "driver": d}) + info["gpus"] = cards if not info["gpus"] and os.name == "nt": # #1587: Windows with only an AMD card has neither nvidia-smi nor rocm-smi; the display class in the registry # names the card, its VRAM and its driver (the run was labelled "CPU only" before) @@ -624,6 +657,10 @@ def collect_machine(base: str, key: str, cfg: dict | None, gpu_arg: str | None = # engine runs on another vendor's card (an Intel Arc beside a GeForce): the server's names are the right ones, and # so is its VRAM total - the PC's NVIDIA cards were not used. served = [n for n in (static.get("gpu_name") or "").split(" + ") if n and n != "?"] + # the engine's own stub when the driver names no card is the vendor alone ("AMD Radeon"), not a card name: + # taking it as one would throw away the real name amd-smi read (same guard as strata_cli/bench_facts.py) + served = [n for n in served if not re.fullmatch(r"(?i)\s*(nvidia|amd|intel|advanced micro devices)" + r"([ -](geforce|radeon|graphics|arc))?\s*", n)] if served and not all(n in {g["name"] for g in local["gpus"]} for n in served): gpu_names, used = served, [] local = {**local, "cuda": None} # the PC's CUDA belongs to cards the engine did not use From a332cc95dbc2a9398860e468a94d758729d25750 Mon Sep 17 00:00:00 2001 From: Jakub Luwierski <91573380+j-luwierski@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:47:46 +0100 Subject: [PATCH 22/45] setup: an explicit --rope-scale must be finite and at least 1 (#3393) resolve_rope accepted nan, inf, zero and values below 1 and handed them to the engine. It now stops with a message that names --rope-scale and the valid range, before any configuration is written; valid factors and the automatic scaling are unchanged. Ported from PR #3393 by j-luwierski (follow-up to #2950) with its tests; the --help text gets the range. --- setup.py | 8 +++++--- tools/test_setup_rope.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index f994d32e..ab6dad1b 100644 --- a/setup.py +++ b/setup.py @@ -7427,7 +7427,7 @@ def derived_factor(ctx: int, trained: int = 262144) -> float: def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): """The rope config for the context ACTUALLY SERVED: (scaling, scale); scaling None = no scaling flags. - An explicit --rope-scaling/--rope-scale always wins - a user-supplied factor is kept verbatim even + An explicit --rope-scaling/--rope-scale always wins - a valid user-supplied factor is kept verbatim even when a reduction changed the context. Past the trained range an omitted method defaults to yarn - llama.cpp's extension method: the trained angles survive on the high-frequency pairs and the magnitude correction keeps the attention temperature - and an omitted factor is derived from the @@ -7436,6 +7436,8 @@ def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): past the trained range (the setup will not configure a run it knows is out of spec) rather than silently overridden. """ + if scale is not None and (not math.isfinite(scale) or scale < 1.0): + raise ValueError("--rope-scale must be a finite value >= 1, e.g. --rope-scale 4") if ctx <= trained: if scale is not None and scaling in (None, "none"): raise ValueError("--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the " @@ -8640,8 +8642,8 @@ def main() -> int: "interpolation) or yarn - llama.cpp's types. Omitted with a scaled context, the setup " "picks yarn; 'none' is refused for such a context") ap.add_argument("--rope-scale", type=float, - help="the extension factor (default: the final context over the trained 262144, at least 1 - " - "1.5 for 384K, 2 for 512K, 1 inside the trained range)") + help="the extension factor, finite and >= 1 (default: the final context over the trained " + "262144, at least 1 - 1.5 for 384K, 2 for 512K, 1 inside the trained range)") ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4", "fp16"], help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " "precise) k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell) or fp16 (16-bit, twice the memory of int8)") diff --git a/tools/test_setup_rope.py b/tools/test_setup_rope.py index 85b47f98..743fd045 100644 --- a/tools/test_setup_rope.py +++ b/tools/test_setup_rope.py @@ -35,6 +35,21 @@ class DerivedFactor(unittest.TestCase): class ResolveRope(unittest.TestCase): + def test_invalid_explicit_factors_are_rejected(self): + for ctx in (131072, 262144, 1048576): + for method in (None, "none", "linear", "yarn"): + for scale in (float("nan"), float("inf"), float("-inf"), -1.0, 0.0, 0.5): + with self.subTest(ctx=ctx, method=method, scale=scale): + with self.assertRaisesRegex(ValueError, r"--rope-scale.*finite.*>= 1"): + setup.resolve_rope(ctx, method, scale) + + def test_valid_explicit_factors_remain_verbatim(self): + for ctx in (131072, 262144, 1048576): + for method in ("linear", "yarn"): + for scale in (1.0, 1.5, 4.0): + with self.subTest(ctx=ctx, method=method, scale=scale): + self.assertEqual(setup.resolve_rope(ctx, method, scale), (method, scale)) + # ---- the automatic flow the docs promise (an omitted flag, --yes or the interactive default) def test_omitted_384k_gets_yarn_and_1_5(self): self.assertEqual(setup.resolve_rope(393216, None, None), ("yarn", 1.5)) From 560cc9fbbc4272a1d5be73118972572a1dae6216 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnter?= <24978919+ai-bits@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:48:14 +0100 Subject: [PATCH 23/45] setup: --gguf-dir files for Qwen3.6 no longer need a .done mark made by setup (#3606) install_own_path treated a file as present only when .done existed, and that mark is written by setup's own download or by verify_sha256, which a file from another tool (LM Studio) never reached: setup said it was missing and asked for the full download size in free disk. With --gguf-dir an existing file and its mmproj go to verify_sha256(own=True), which checks size and SHA-256, leaves a mismatching file alone and writes the mark. A file that is not in the folder is still reported missing. Ported from PR #3606 by ai-bits with its two tests. --- setup.py | 8 +++++--- tools/test_setup_qwen36.py | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index ab6dad1b..d72ba3e3 100644 --- a/setup.py +++ b/setup.py @@ -7757,7 +7757,9 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte gguf = folder / fam["file"].format(q=model) size = fam["sha256"][gguf.name][0] part = gguf.with_name(gguf.name + ".part") - left = 0 if gguf.exists() and done(gguf) else (size - (part.stat().st_size if part.is_file() else 0)) / 1e9 + def have(p: Path) -> bool: # --gguf-dir: the person's own file has no finish mark; verify_sha256 checks and writes it + return p.exists() and (done(p) or bool(a.gguf_dir)) + left = 0 if have(gguf) else (size - (part.stat().st_size if part.is_file() else 0)) / 1e9 if left and free_gb(folder) < left: fail(f"not enough free disk space in {folder}: need ~{left:.0f} GB, {free_gb(folder):.0f} GB free", ("use --data-dir on a bigger drive (strata launch --data-dir)" if CONTROL else "use --models-dir on a bigger drive")) if left and free_gb(folder) < left + 1: @@ -7781,7 +7783,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte ok("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: {eng / EXE}") step(5, f"downloading {fam['title']} {model}") - if gguf.exists() and done(gguf): + if have(gguf): ok(f"{gguf.name} already downloaded") else: if a.gguf_dir: @@ -7791,7 +7793,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte ok(f"model file: {gguf}") mmproj = folder / fam["mmproj"] if vision != "none": # the image encoder: Unsloth's mmproj, pinned, size + SHA-256 checked - if mmproj.exists() and done(mmproj): + if have(mmproj): ok(f"{mmproj.name} already downloaded") else: if a.gguf_dir: diff --git a/tools/test_setup_qwen36.py b/tools/test_setup_qwen36.py index 0baef2e9..b71cab23 100644 --- a/tools/test_setup_qwen36.py +++ b/tools/test_setup_qwen36.py @@ -151,6 +151,25 @@ class InstallOwnPath(unittest.TestCase): self.assertEqual(Path(self.cfg["exe"]).parent, self.root / "engine") self.assertIn(("config", "strata-qwen36-ud-q4_k_xl.json"), self.calls) + def test_gguf_dir_takes_the_persons_own_files_that_have_no_finish_mark(self): + folder = self.root / "own" + folder.mkdir() + for name in ("Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf", "mmproj-F16.gguf"): + (folder / name).write_text("x") # no .done: verify_sha256 checks the file and marks it + with mock.patch.object(setup, "free_gb", lambda p: 1.0): # nothing to download: no disk needed + rc, out = self.install(model="UD-Q4_K_XL", vision="cpu", gguf_dir=str(folder)) + self.assertEqual(rc, 0, out) + self.assertEqual([c for c in self.calls if c[0] == "get"], []) + self.assertIn(("sha", "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf"), self.calls) + self.assertIn(("sha", "mmproj-F16.gguf"), self.calls) + + def test_gguf_dir_without_the_file_still_says_it_is_missing(self): + folder = self.root / "empty" + folder.mkdir() + rc, out = self.install(model="UD-Q4_K_XL", vision="no", gguf_dir=str(folder)) + self.assertEqual(rc, 1) + self.assertIn("is missing", out) + def test_default_size_follows_the_ram(self): rc, out = self.install(ram=64.0) self.assertEqual(rc, 0, out) From a1d2fd7ed1792410af20431da4bc71290060a72a Mon Sep 17 00:00:00 2001 From: Keyan Hu <177766066+KeyanHu-git@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:48:49 +0100 Subject: [PATCH 24/45] setup: use the published size when the download length probes fail (#2287) When HEAD and the one-byte range probe both gave no length, download() took an early EOF as a finished file even though the repository pin (or ModelScope's published size) names the size. The published size now stands in for the length, so the existing resume, retry and parallel code publishes the file only after it has all its bytes; a size that disagrees with the pin is still refused before the transfer and the SHA-256 check is unchanged. Ported from PR #2287 by KeyanHu-git with its tests (tools/test_setup_download_length.py). --- setup.py | 4 +- tools/test_setup_download_length.py | 109 ++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 1 deletion(-) create mode 100644 tools/test_setup_download_length.py diff --git a/setup.py b/setup.py index d72ba3e3..7f3193a9 100644 --- a/setup.py +++ b/setup.py @@ -2885,12 +2885,14 @@ def download(url, dst: Path, what=None): time.sleep(5) if not total: total = range_total(url) + meta = ms_meta(*ms) if ms is not None else None + if not total: # published size also governs partial-file completion + total = pin[0] if pin else (meta[0] if meta else 0) if pin and total and total != pin[0]: # not the pinned file: stop before the download, not after fail(f"{what or dst.name} is {total:,} bytes on {url.split('/')[2]}, not the pinned {pin[0]:,}", "update Strata (the file there has changed since this version pinned it)") label = what or dst.name conns = dl_connections() - meta = ms_meta(*ms) if ms is not None else None fixed = pin if pin else (meta if meta is not None and meta[1] else None) again = (lambda: repair_download(url, dst, total, label, conns)) if total >= DL_MIN_PARALLEL and conns > 1 else None if dst.exists() and total and dst.stat().st_size == total: # finished by an older setup (no mark yet), or stopped before the check diff --git a/tools/test_setup_download_length.py b/tools/test_setup_download_length.py new file mode 100644 index 00000000..2ad726b6 --- /dev/null +++ b/tools/test_setup_download_length.py @@ -0,0 +1,109 @@ +"""Published size drives resume when HEAD and the range probe have no length.""" +import contextlib +import hashlib +import io +import tempfile +import unittest +from pathlib import Path +from unittest import mock +from tools.test_setup_download import DATA, Server, small_pieces, setup + + +class PublishedDownloadLength(unittest.TestCase): + def run_download(self, metadata, persistent=False, digest=True, parallel=False): + def faults(path, start, end, nth): + if (start, end) == (0, 0) and (not parallel or nth == 1): + return 'status', 405 + if start == 0 and nth == 1: + return 'cut', 262144 + if persistent: + return 'cut', 0 + + with Server(length=False, faults=faults, delay=0) as server, tempfile.TemporaryDirectory() as tmp: + dst = Path(tmp) / 'model.gguf' + published = (len(DATA), hashlib.sha256(DATA).hexdigest() if digest else '') + with contextlib.ExitStack() as stack: + stack.enter_context(small_pieces(DL_MIN_PARALLEL=0 if parallel else len(DATA) + 1)) + stack.enter_context(contextlib.redirect_stdout(io.StringIO())) + stack.enter_context(mock.patch.object(setup, 'file_pin', return_value=None if metadata else published)) + stack.enter_context(mock.patch.object(setup, 'model_source', return_value='modelscope' if metadata else 'huggingface')) + stack.enter_context(mock.patch.object(setup, 'ms_file', return_value=('repo', 'model.gguf'))) + stack.enter_context(mock.patch.object(setup, 'ms_url', return_value=server.url)) + stack.enter_context(mock.patch.object(setup, 'reachable', return_value=True)) + meta = stack.enter_context(mock.patch.object(setup, 'ms_meta', return_value=published)) + if persistent: + with self.assertRaises(SystemExit): + setup.download(server.url, dst) + self.assertFalse(dst.exists()) + self.assertFalse(dst.with_name(dst.name + '.done').exists()) + self.assertEqual(dst.with_name(dst.name + '.part').read_bytes(), DATA[:262144]) + else: + setup.download(server.url, dst) + self.assertEqual(dst.read_bytes(), DATA) + self.assertTrue(dst.with_name(dst.name + '.done').exists()) + if parallel: + self.assertTrue(any(start > 0 and end < len(DATA) - 1 for start, end in server.gets)) + else: + self.assertIn((262144, len(DATA) - 1), server.gets) + self.assertEqual(meta.call_count, 1 if metadata else 0) + + def test_pin_size_recovers_clean_early_eof(self): + self.run_download(metadata=False) + + def test_modelscope_metadata_size_recovers_clean_early_eof(self): + self.run_download(metadata=True) + + def test_exhausted_transfer_keeps_resumable_partial(self): + self.run_download(metadata=False, persistent=True) + + def test_metadata_size_without_hash_still_recovers(self): + self.run_download(metadata=True, digest=False) + + def test_published_size_also_drives_parallel_download(self): + self.run_download(metadata=False, parallel=True) + + def test_complete_partial_is_published_without_downloading_again(self): + def faults(path, start, end, nth): + return ('status', 405) if (start, end) == (0, 0) else None + + with Server(length=False, faults=faults) as server, tempfile.TemporaryDirectory() as tmp: + dst = Path(tmp) / 'model.gguf' + dst.with_name(dst.name + '.part').write_bytes(DATA) + published = (len(DATA), hashlib.sha256(DATA).hexdigest()) + with small_pieces(DL_MIN_PARALLEL=len(DATA) + 1), \ + mock.patch.object(setup, 'file_pin', return_value=published), \ + contextlib.redirect_stdout(io.StringIO()): + setup.download(server.url, dst) + self.assertEqual(dst.read_bytes(), DATA) + self.assertIn(published[1], dst.with_name(dst.name + '.done').read_text()) + self.assertEqual(server.gets, [(0, 0)]) + heads = server.heads + setup.download(server.url, dst) + self.assertEqual(server.heads, heads) + self.assertEqual(server.gets, [(0, 0)]) + + def test_transport_size_conflict_is_still_refused_before_transfer(self): + with Server() as server, tempfile.TemporaryDirectory() as tmp: + dst = Path(tmp) / 'model.gguf' + with small_pieces(), mock.patch.object(setup, 'file_pin', return_value=(len(DATA) + 1, '0' * 64)), \ + contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit): + setup.download(server.url, dst) + self.assertEqual(server.gets, []) + self.assertEqual(list(Path(tmp).iterdir()), []) + + def test_fallback_size_does_not_bypass_hash_verification(self): + def faults(path, start, end, nth): + return ('status', 405) if (start, end) == (0, 0) else None + + with Server(length=False, faults=faults) as server, tempfile.TemporaryDirectory() as tmp: + dst = Path(tmp) / 'model.gguf' + with small_pieces(DL_MIN_PARALLEL=len(DATA) + 1), \ + mock.patch.object(setup, 'file_pin', return_value=(len(DATA), '0' * 64)), \ + contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit): + setup.download(server.url, dst) + self.assertFalse(dst.exists()) + self.assertFalse(dst.with_name(dst.name + '.done').exists()) + + +if __name__ == '__main__': + unittest.main() From eba3106c0e31d18a0f48cdff596afb1ffd41673e Mon Sep 17 00:00:00 2001 From: PurrSec <87878066+purrsec@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:50:11 +0100 Subject: [PATCH 25/45] serve: support IPv6 bind addresses (#3212) --host :: failed before the model loaded because Server always opened an IPv4 socket. Server now selects AF_INET6 when the bind address contains a colon; the ready line, the 'from other devices' lines and the browser address bracket an IPv6 address. The bind is still the person's choice and no default changes. Ported from PR #3212 by purrsec with its tests (serve/test_security.py, including a real :: bind). setup.py's --host help and docs/DETAILS.md say :: is all IPv6 interfaces; the README hunks of the PR (they name strata launch --host, not checked) are left out. --- docs/DETAILS.md | 2 ++ serve/server.py | 16 +++++++++++----- serve/test_security.py | 38 +++++++++++++++++++++++++++++++++++++- setup.py | 9 +++++---- 4 files changed, 55 insertions(+), 10 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 9ccf7685..27d0fdf3 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -544,6 +544,8 @@ tables per token). The scaling is fixed for the whole run, because the KV cache `--host 0.0.0.0 --api-key some-long-secret`, or add `"host": "0.0.0.0"` and `"api_key": "..."` to the config. A key is recommended, not required: without one the server starts and warns that anyone who can reach the port can use the model and its tools. `--no-api-key` (or `"api_key": "none"`) says it is on purpose. The server window prints this PC's addresses. + For IPv6 use `--host ::` (or `"host": "::"`, all IPv6 interfaces) and put the address in brackets in URLs, for example + `http://[2001:db8::7]:8080/v1`. On Windows allow the port in the firewall for private networks: `New-NetFirewallRule -DisplayName "Strata 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow -Profile Private` (admin PowerShell). diff --git a/serve/server.py b/serve/server.py index 76b5a2c7..8a51e2e9 100644 --- a/serve/server.py +++ b/serve/server.py @@ -7445,6 +7445,11 @@ class Server(ThreadingHTTPServer): # (STRATA_HTTP_BACKLOG overrides it) request_queue_size = max(5, int(os.environ.get("STRATA_HTTP_BACKLOG") or 256)) + def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): + if ":" in server_address[0]: + self.address_family = socket.AF_INET6 + super().__init__(server_address, RequestHandlerClass, bind_and_activate) + def handle_error(self, request, client_address): if not isinstance(sys.exc_info()[1], ConnectionError): # a client that hangs up needs no stack trace super().handle_error(request, client_address) @@ -8143,7 +8148,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in "written by setup.py") ap.add_argument("--host", default=None, help="the address to listen on: 127.0.0.1 = this PC only (the default), 0.0.0.0 = also other devices " - "on your network (set an API key); also \"host\" in the config") + "on your network, :: = all IPv6 interfaces (set an API key); also \"host\" in the config") ap.add_argument("--script-cycle", action="store_true", help="with --script given more than once: repeat the scripts by position instead of advancing " "to the last one and staying there, so extra requests a harness makes (a session title, " @@ -8617,18 +8622,19 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in bound_port = httpd.server_address[1] # --port 0: report the port the OS actually assigned svc.start_idle_unload() svc.start_vision_idle() - here = "127.0.0.1" if a.host in ("0.0.0.0", "", "::") else a.host + here = "[::1]" if a.host == "::" else "127.0.0.1" if a.host in ("0.0.0.0", "") else f"[{a.host}]" if ":" in a.host else a.host print(f"ready: http://{here}:{bound_port}/v1 (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, " f"context {engine.max_context} tokens{', images on' if vision else ''}" f"{', API key required' if svc.api_key else ''})", flush=True) print(f" open http://{here}:{bound_port}/ in a browser to chat; close this window to stop the model", flush=True) if a.host not in ("127.0.0.1", "localhost", "::1"): # issue #26: reachable from other devices - say at which address, and what can still block it - ips = lan_addresses() + ips = [f"[{a.host}]"] if ":" in a.host and a.host != "::" else [] if a.host == "::" else lan_addresses() for ip in ips: print(f" from other devices: http://{ip}:{bound_port}/ (API: http://{ip}:{bound_port}/v1)", flush=True) if not ips: - print(" from other devices: http://:" + str(bound_port) + "/", flush=True) + address = "[]" if a.host == "::" else "" + print(f" from other devices: http://{address}:{bound_port}/", flush=True) if not svc.api_key: print(" WARNING: " + open_server_warning(bound_port, tools=svc.mcp is not None), flush=True) @@ -8642,7 +8648,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in # on its own thread: webbrowser.open waits for the browser launcher, which on Linux can run for as long as # the browser does, and the main thread must be free to take Ctrl+C and SIGTERM (#1872) threading.Thread(target=webbrowser.open, daemon=True, name="strata-open-browser", - args=(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{bound_port}/",)).start() + args=(f"http://{here}:{bound_port}/",)).start() if ready_path is not None or event_sink is not None: ready_host = f"[{here}]" if ":" in here and not here.startswith("[") else here record = {"schema_version": 1, "instance_id": svc.instance_id, "pid": os.getpid(), diff --git a/serve/test_security.py b/serve/test_security.py index 4b00f440..0fb695e7 100644 --- a/serve/test_security.py +++ b/serve/test_security.py @@ -12,12 +12,13 @@ import json import socket import sys import unittest +from http.server import BaseHTTPRequestHandler from pathlib import Path from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve.frontend import ChatTemplate # noqa: E402 -from serve.server import (ByteTokenizer, MockEngine, Service, allowed_hosts_of, host_allowed, # noqa: E402 +from serve.server import (ByteTokenizer, MockEngine, Server, Service, allowed_hosts_of, host_allowed, # noqa: E402 host_name, host_names_for, origin_allowed, serve) ROOT = Path(__file__).resolve().parents[1] @@ -57,6 +58,41 @@ class HostNames(unittest.TestCase): self.assertNotIn("*", names) +class ListenAddress(unittest.TestCase): + def test_ipv4_address_family(self): + with Server(("127.0.0.1", 0), BaseHTTPRequestHandler, bind_and_activate=False) as s: + self.assertEqual(s.address_family, socket.AF_INET) + + @unittest.skipUnless(socket.has_ipv6, "IPv6 is not available") + def test_ipv6_loopback(self): + for host in ("::1", "2001:db8::7"): + try: + with Server((host, 0), BaseHTTPRequestHandler, bind_and_activate=False) as s: + self.assertEqual(s.address_family, socket.AF_INET6) + except OSError as e: + self.skipTest(f"IPv6 socket is not available: {e}") + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "\n\nok", max_context=4096), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + try: + httpd = serve(svc, host="::", port=0) + except OSError as e: + self.skipTest(f"IPv6 loopback is not available: {e}") + try: + self.assertEqual(httpd.address_family, socket.AF_INET6) + c = http.client.HTTPConnection("::1", httpd.server_address[1], timeout=10) + try: + c.request("GET", "/health") + r = c.getresponse() + self.assertEqual(r.status, 200) + r.read() + finally: + c.close() + finally: + httpd.shutdown() + httpd.server_close() + + class HostCheck(unittest.TestCase): def test_accepted(self): for host in ("localhost:8095", "LOCALHOST", "127.0.0.1:1", "[::1]:8095", "192.168.1.20:8095", "[fe80::1]", diff --git a/setup.py b/setup.py index 7f3193a9..c32c6db4 100644 --- a/setup.py +++ b/setup.py @@ -25,7 +25,7 @@ Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768 at least 1 - an explicit --rope-scaling none is refused for such a context), --vision yes|no|gpu|cpu, --port 8080, --yes (recommended answers, no questions), --setup (install another model / change settings instead of starting), --no-start, ---host 0.0.0.0 --api-key KEY (reach it from other devices on your network), --experimental-speed-projection on|off +--host 0.0.0.0 --api-key KEY (reach it over IPv4; use --host :: for IPv6), --experimental-speed-projection on|off (EXPERIMENTAL, off by default), --models-dir DIR, --gguf-dir DIR (use GGUF files you already have), --build (compile instead of the ready-made engine), --check (only check this PC), --resident-budget-gib N (UD-Q4_K_XL's or UD-IQ4_XS's experts in RAM), @@ -8685,9 +8685,10 @@ def main() -> int: "auto, placed from each GPU's free VRAM") ap.add_argument("--no-remote-expert-opt", action="store_true", help="with two or more GPUs: leave out --remote-expert-opt, which setup adds there (#578)") - ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " - "devices on your network (issue #26; an --api-key is recommended)") - ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0); several keys: key1,key2") + ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = all IPv4 " + "interfaces, :: = all IPv6 interfaces (issue #26; an --api-key is recommended)") + ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0 or --host ::); " + "several keys: key1,key2") ap.add_argument("--no-browser", dest="browser", action="store_false", default=None, help="do not open the chat page in the browser when the model is ready (for a harness or an app " "that uses the API; remembered for this model, also in run-.bat/.sh)") From 092c7d1ef45db1deb6a668de7801ed5715c8decd Mon Sep 17 00:00:00 2001 From: i-Vladimir-i <291339861+i-Vladimir-i@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:51:44 +0100 Subject: [PATCH 26/45] serve: return 503 when the elastic image encoder cannot start (#2435) When the elastic image encoder failed to restart, its exception left request preparation and the client got a closed connection. It now goes through the EngineDied path: HTTP 503 with the reason, a later picture tries again, text requests and a later good start are unaffected. An idle encoder stop is logged even when the cache shrink was refused, and a layer split gets a line saying its encoder VRAM has to be kept free with --vram-reserve-mib. Ported from PR #2435 by i-Vladimir-i with its tests (chat, messages and responses, streamed and not, plus a real encoder that exits with code 71 on Linux) and the docs/VRAM_ELASTIC.md text. --- docs/VRAM_ELASTIC.md | 4 +- serve/server.py | 20 ++++- serve/test_vision_elastic.py | 25 +++++- serve/test_vision_elastic_http.py | 140 ++++++++++++++++++++++++++++++ 4 files changed, 183 insertions(+), 6 deletions(-) create mode 100644 serve/test_vision_elastic_http.py diff --git a/docs/VRAM_ELASTIC.md b/docs/VRAM_ELASTIC.md index 64ea795e..94945094 100644 --- a/docs/VRAM_ELASTIC.md +++ b/docs/VRAM_ELASTIC.md @@ -113,7 +113,9 @@ and starts the encoder with the model, as before) the GPU encoder is not started - **A picture's turn** (the same FIFO turn an encode always takes): if the encoder is not running, the engine's `VRAM` command first keeps `"elastic_mib"` (default 2048) free on top of the reserve - the last `POST /v1/vram`, or 0 when none was made - and then the encoder starts. If the cache cannot shrink (the resident low-RAM mode, an engine - without `--vram-elastic`) it starts anyway, as a non-elastic encoder would, and the log says why. + without `--vram-elastic`, a layer split) it starts anyway, as a non-elastic encoder would, and the log says why; on a + layer split the server says at start that the encoder's VRAM has to be kept free with `--vram-reserve-mib`. An + encoder that fails to start (out of VRAM) ends the request with a `503`; the next picture tries again. - **Idle** for `"elastic_idle_s"` (default 120) without a picture: a thread stops the encoder between requests and sends `VRAM` with that reserve again, so the cache grows back to the size it had (0, not the start's reserve: that would leave it a segment or more smaller). diff --git a/serve/server.py b/serve/server.py index 8a51e2e9..adf9f552 100644 --- a/serve/server.py +++ b/serve/server.py @@ -4202,7 +4202,10 @@ class Service: if self.vision_held: time.sleep(0.2) # the driver's free-VRAM counter shows the cache's release a moment later free0, t0 = self.free_vram_mib(), time.time() - v.restart() + try: + v.restart() + except Exception as e: # a 503 as for a non-elastic encoder at a load, not a dropped connection + raise EngineDied(f"the image encoder failed to start: {e}") from e free1 = self.free_vram_mib() took = f", {free0 - free1} MiB of VRAM" if free0 is not None and free1 is not None else "" print(f"[strata] images: the image encoder started in {time.time() - t0:.1f} s{took}", flush=True) @@ -4220,11 +4223,14 @@ class Service: return "busy" try: v.unload() + back = "" if self.vision_held and hasattr(self.engine, "vram") and self.loaded(): out = self.engine.vram(self._engine_reserve()) - print(f"[strata] images: the image encoder stopped after {v.elastic_idle_s:g} s without a picture; " - f"the expert cache took its VRAM back ({out.get('expert_cache_mib')} of " - f"{out.get('expert_cache_full_mib')} MiB)", flush=True) + back = (f"; the expert cache took its VRAM back ({out.get('expert_cache_mib')} of " + f"{out.get('expert_cache_full_mib')} MiB)") + # also when the cache never made room (a layer split, an engine without --vram-elastic): the stop happened + print(f"[strata] images: the image encoder stopped after {v.elastic_idle_s:g} s without a picture{back}", + flush=True) self.vision_held = False return "down" finally: @@ -8377,6 +8383,12 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in print('[strata] the vision section\'s "elastic" needs "vram_elastic": true (the expert cache gives the ' "encoder its VRAM): the encoder starts with the model instead", flush=True) vcfg["elastic"] = False + elif vcfg.get("elastic") is True and layer_split_of(cfg): + # the engine turns --vram-elastic off on a layer split (a cache per GPU): the encoder still starts + # with the first picture and stops when idle, but its VRAM has to be free already + print('[strata] images: on a layer split the expert cache cannot make room for the image encoder (the ' + 'engine turns --vram-elastic off); keep its VRAM free with "--vram-reserve-mib" on the ' + "encoder's GPU, or the first picture may not get it", flush=True) vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, env=vision_env(cfg, env), lazy=lazy) print("model unloaded; the first request loads it ..." if lazy else diff --git a/serve/test_vision_elastic.py b/serve/test_vision_elastic.py index b8516b1a..fa16426c 100644 --- a/serve/test_vision_elastic.py +++ b/serve/test_vision_elastic.py @@ -2,13 +2,15 @@ expert cache keep the encoder's VRAM free and then starts it, later pictures use it as it is, an idle encoder stops and the cache takes its VRAM back, a POST /v1/vram reserve stacks on the encoder's share, and the engine's load never starts it on its own.""" +import contextlib +import io import tempfile import time import unittest from pathlib import Path from serve.frontend import ChatTemplate -from serve.server import ByteTokenizer, Service, Vision +from serve.server import ByteTokenizer, EngineDied, Service, Vision from serve.test_vram import VramEngine ROOT = Path(__file__).resolve().parents[1] @@ -99,6 +101,27 @@ class Elastic(unittest.TestCase): self.assertEqual(self.svc._vision_idle_down(), "down") self.assertEqual(self.engine.calls, [2048]) # the refused shrink only: nothing to give back + def test_an_encoder_that_fails_to_start_is_a_503_not_a_dropped_connection(self): + def fail(): + raise RuntimeError("the vision encoder did not start: cudaMalloc failed: out of memory") + self.vision.restart = fail + with self.assertRaises(EngineDied) as e: # the handlers answer EngineDied with a 503 + self.picture() + self.assertIn("the image encoder failed to start", str(e.exception)) + self.svc.last_image_at = 0 + self.assertEqual(self.svc._vision_idle_down(), "down") + self.assertEqual(self.engine.calls, [2048, 0]) # the share made for it goes back + + def test_the_stop_is_logged_when_the_cache_never_made_room(self): + self.engine.elastic = False # a layer split: the engine refuses --vram-elastic + self.picture() + self.svc.last_image_at = 0 + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(self.svc._vision_idle_down(), "down") + self.assertIn("the image encoder stopped after 60 s without a picture", out.getvalue()) + self.assertNotIn("expert cache", out.getvalue()) + def test_the_load_never_starts_an_elastic_encoder(self): self.assertFalse(self.svc._vision_down()) self.svc.vision = ElasticVision(tempfile.mkdtemp(), elastic=False) diff --git a/serve/test_vision_elastic_http.py b/serve/test_vision_elastic_http.py new file mode 100644 index 00000000..78b6df73 --- /dev/null +++ b/serve/test_vision_elastic_http.py @@ -0,0 +1,140 @@ +"""Elastic encoder failures reach clients, can be retried, and do not prevent recovery.""" +import json +from pathlib import Path +import sys +import tempfile +import unittest +import urllib.error +import urllib.request + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, Service, Vision, serve +from serve.test_vision_elastic import ElasticVision +from serve.test_vram import VramEngine + + +class EncoderFailureHTTP(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + tok = ByteTokenizer() + self.engine = VramEngine(tok) + self.engine.loaded = True + self.engine.elastic = False # as on a layer split: the cache cannot make room + self.vision = ElasticVision(tmp.name) + self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja'), + vision=self.vision) + httpd = serve(self.svc, port=0) + self.addCleanup(httpd.server_close) + self.addCleanup(httpd.shutdown) + self.addCleanup(self.drop_embeddings) + self.base = f'http://127.0.0.1:{httpd.server_address[1]}' + self.attempts = 0 + self.original_restart = self.vision.restart + + def drop_embeddings(self): + path = getattr(getattr(self.svc, 'embeddings', None), 'path', None) + if path is not None: + path.unlink(missing_ok=True) + + def post(self, path, body): + req = urllib.request.Request(self.base + path, json.dumps(body).encode(), + {'Content-Type': 'application/json'}) + return urllib.request.urlopen(req, timeout=10) + + @staticmethod + def chat_picture(): + return {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [ + {'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,eA=='}}]}]} + + def fail_with(self, error_type): + def fail(): + self.attempts += 1 + raise error_type('synthetic encoder startup failure') + self.vision.restart = fail + + def assert_503(self, path, body): + with self.assertRaises(urllib.error.HTTPError) as got: + self.post(path, body) + with got.exception as response: + self.assertEqual(response.code, 503) + payload = json.load(response) + self.assertIn('synthetic encoder startup failure', payload['error']['message']) + + def test_start_failure_and_retry_on_all_three_apis(self): + cases = [ + ('/v1/chat/completions', self.chat_picture()), + ('/v1/messages', {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [ + {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': 'eA=='}}]}]}), + ('/v1/responses', {'model': 'm', 'max_output_tokens': 8, 'input': [{'role': 'user', 'content': [ + {'type': 'input_image', 'image_url': 'data:image/png;base64,eA=='}]}]}), + ] + for error_type in (RuntimeError, OSError): + self.fail_with(error_type) + for path, body in cases: + for stream in (False, True): + for retry in range(2): + with self.subTest(error=error_type.__name__, path=path, stream=stream, retry=retry): + before = self.attempts + self.assert_503(path, {**body, 'stream': stream}) + self.assertEqual(self.attempts, before + 1) + + def test_text_requests_and_image_recovery_after_a_failed_start(self): + self.fail_with(RuntimeError) + text = {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': 'hi'}]} + with self.post('/v1/chat/completions', text) as response: + self.assertEqual(response.status, 200) + response.read() + self.assertEqual(self.attempts, 0) + self.assert_503('/v1/chat/completions', self.chat_picture()) + self.assertEqual(self.attempts, 1) + self.vision.restart = self.original_restart + with self.post('/v1/chat/completions', self.chat_picture()) as response: + self.assertEqual(response.status, 200) + response.read() + self.assertEqual(self.vision.starts, 1) + with self.post('/v1/chat/completions', text) as response: + self.assertEqual(response.status, 200) + response.read() + self.assertEqual(self.vision.starts, 1) + + @unittest.skipUnless(sys.platform.startswith('linux'), 'child reaping is checked through /proc') + def test_real_encoder_failure_retries_and_reaps_each_child(self): + with tempfile.TemporaryDirectory() as directory: + started = Path(directory) / 'started-pids' + executable = Path(directory) / 'encoder-exits' + executable.write_text( + '#!' + sys.executable + '\nimport os\n' + 'with open(' + repr(str(started)) + ', "a") as output:\n' + ' output.write(str(os.getpid()) + "\\n")\n' + 'raise SystemExit(71)\n') + executable.chmod(0o700) + vision = Vision({'exe': str(executable), 'mmproj': 'unused', 'model': 'unused', + 'elastic': True}, lazy=True) + self.addCleanup(vision.unload) + self.svc.vision = vision + cases = [ + ('/v1/chat/completions', self.chat_picture()), + ('/v1/messages', {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [ + {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': 'eA=='}}]}]}), + ('/v1/responses', {'model': 'm', 'max_output_tokens': 8, 'input': [{'role': 'user', 'content': [ + {'type': 'input_image', 'image_url': 'data:image/png;base64,eA=='}]}]}), + ] + for path, body in cases: + for stream in (False, True): + for retry in range(2): + with self.subTest(path=path, stream=stream, retry=retry): + previous = started.read_text().splitlines() if started.exists() else [] + with self.assertRaises(urllib.error.HTTPError) as got: + self.post(path, {**body, 'stream': stream}) + with got.exception as response: + self.assertEqual(response.code, 503) + self.assertIn('the image encoder failed to start', json.load(response)['error']['message']) + children = started.read_text().splitlines() + self.assertEqual(len(children), len(previous) + 1) + self.assertFalse(vision.alive()) + self.assertFalse(Path('/proc', children[-1]).exists()) + + +if __name__ == '__main__': + unittest.main() From 11237f831f3cc4691369186d3c51e90ac4b59a6d Mon Sep 17 00:00:00 2001 From: Jakub Luwierski <91573380+j-luwierski@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:54:34 +0100 Subject: [PATCH 27/45] serve: Chat Completions tool results keep the order of the calls they answer (#3395) When one assistant message made several tool calls and the client returned the results in another order, the call ids were dropped before the prompt was rendered, so the model saw anonymous results in the wrong order. The ids are now kept while the request is normalized; a run of results is reordered to the call order only when the call ids and result ids are non-empty unique strings with matching sets. Anything else (missing, duplicate, unknown or incomplete ids) keeps the received order, and the ids never reach the template. Ported from PR #3395 by j-luwierski with its seven tests (serve/test_chat_tool_results.py); the hunk was merged by hand beside require_messages. --- serve/frontend.py | 34 +++++++- serve/test_chat_tool_results.py | 133 ++++++++++++++++++++++++++++++++ 2 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 serve/test_chat_tool_results.py diff --git a/serve/frontend.py b/serve/frontend.py index a70494f0..5911054e 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -546,6 +546,34 @@ def require_messages(messages: list) -> None: raise ValueError("messages must be a non-empty list: send at least one message") +def _order_chat_tool_results(messages: list[dict]) -> None: + """The template pairs results by position, so restore call order while IDs are still available. + + Only a complete, unambiguous run of results is reordered. Legacy or incomplete histories keep their + received order. IDs are private to this conversion and never reach the template. + """ + i = 0 + while i < len(messages): + if messages[i]["role"] != "tool": + i += 1 + continue + j = i + 1 + while j < len(messages) and messages[j]["role"] == "tool": + j += 1 + prev = messages[i - 1] if i else {} + calls = [c.get("_call_id") for c in prev.get("tool_calls") or []] if prev.get("role") == "assistant" else [] + results = [m.get("_call_id") for m in messages[i:j]] + if len(calls) == len(results) and all(isinstance(cid, str) and cid for cid in calls + results): + if len(set(calls)) == len(calls) and len(set(results)) == len(results) and set(calls) == set(results): + rank = {cid: n for n, cid in enumerate(calls)} + messages[i:j] = sorted(messages[i:j], key=lambda m: rank[m["_call_id"]]) + i = j + for message in messages: + message.pop("_call_id", None) + for call in message.get("tool_calls") or []: + call.pop("_call_id", None) + + def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" messages = [] @@ -558,6 +586,8 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: content = _check_parts(m.get("content"), f"messages[{i}].content", TEXT_PARTS + IMAGE_PARTS if images else TEXT_PARTS) out = {"role": role, "content": _parts_of(content) if images else _text_of(content)} + if role == "tool": + out["_call_id"] = m.get("tool_call_id") if m.get("reasoning_content"): out["reasoning_content"] = m["reasoning_content"] if m.get("tool_calls"): @@ -566,9 +596,11 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: fn = c.get("function", c) if not isinstance(fn, dict): raise ValueError("tool_calls must be a list of objects (each with a \"function\" object)") - calls.append({"function": {"name": fn.get("name"), "arguments": tool_arguments(fn.get("arguments"))}}) + calls.append({"function": {"name": fn.get("name"), "arguments": tool_arguments(fn.get("arguments"))}, + "_call_id": c.get("id")}) out["tool_calls"] = calls messages.append(out) + _order_chat_tool_results(messages) tools = [t.get("function", t) if t.get("type") == "function" else t for t in _tool_list(req.get("tools"), "function")] or None kwargs = {} diff --git a/serve/test_chat_tool_results.py b/serve/test_chat_tool_results.py new file mode 100644 index 00000000..9c99b2ee --- /dev/null +++ b/serve/test_chat_tool_results.py @@ -0,0 +1,133 @@ +"""Chat Completions tool results must follow call IDs before the template drops them.""" +import copy +import http.client +import json +from pathlib import Path +import unittest + +from serve.frontend import ChatTemplate, openai_to_messages +from serve.server import ByteTokenizer, MockEngine, Service, serve + + +TEMPLATE = ChatTemplate(Path(__file__).with_name("chat_template.jinja")) + + +def history(): + return [ + {"role": "user", "content": "Read a.txt and b.txt."}, + {"role": "assistant", "content": "", "tool_calls": [ + {"id": "call_a", "type": "function", "function": { + "name": "read_file", "arguments": '{"path":"a.txt"}'}}, + {"id": "call_b", "type": "function", "function": { + "name": "read_file", "arguments": '{"path":"b.txt"}'}}]}, + {"role": "tool", "tool_call_id": "call_b", "content": "RESULT_FROM_B"}, + {"role": "tool", "tool_call_id": "call_a", "content": "RESULT_FROM_A"}, + ] + + +def normalized(messages): + return openai_to_messages({"messages": messages})[0] + + +def rendered(messages): + return TEMPLATE.render(normalized(messages), enable_thinking=False) + + +class ChatToolResults(unittest.TestCase): + def test_reversed_results_of_the_same_function_follow_call_ids(self): + raw = history() + before = copy.deepcopy(raw) + ordered = raw[:2] + list(reversed(raw[2:])) + self.assertEqual(rendered(raw), rendered(ordered)) + self.assertLess(rendered(raw).index("RESULT_FROM_A"), rendered(raw).index("RESULT_FROM_B")) + self.assertEqual(raw, before) + messages = normalized(raw) + self.assertEqual([m["content"] for m in messages[2:]], ["RESULT_FROM_A", "RESULT_FROM_B"]) + self.assertTrue(all(set(m) == {"role", "content"} for m in messages[2:])) + self.assertTrue(all(set(c) == {"function"} for c in messages[1]["tool_calls"])) + + def test_already_ordered_and_legacy_prompts_are_identical(self): + ordered = history() + ordered[2:] = reversed(ordered[2:]) + legacy = copy.deepcopy(ordered) + for call in legacy[1]["tool_calls"]: + call.pop("id") + for result in legacy[2:]: + result.pop("tool_call_id") + self.assertEqual(normalized(ordered), normalized(legacy)) + self.assertEqual(rendered(ordered), rendered(legacy)) + + def test_ambiguous_or_incomplete_ids_preserve_received_order(self): + for case in ("missing_call", "missing_result", "duplicate_call", "duplicate_result", "unknown", + "list_call", "list_result", "empty_call", "empty_result", "partial"): + raw = history() + if case == "missing_call": + raw[1]["tool_calls"][0].pop("id") + elif case == "missing_result": + raw[2].pop("tool_call_id") + elif case == "duplicate_call": + raw[1]["tool_calls"][1]["id"] = "call_a" + elif case == "duplicate_result": + raw[3]["tool_call_id"] = "call_b" + elif case == "unknown": + raw[2]["tool_call_id"] = "unknown" + elif case == "list_call": + raw[1]["tool_calls"][0]["id"] = [] + elif case == "list_result": + raw[2]["tool_call_id"] = [] + elif case == "empty_call": + raw[1]["tool_calls"][0]["id"] = "" + elif case == "empty_result": + raw[2]["tool_call_id"] = "" + else: + raw.pop() + with self.subTest(case=case): + self.assertEqual([m["content"] for m in normalized(raw)[2:]], + [m["content"] for m in raw[2:]]) + + def test_each_tool_run_is_scoped_to_its_assistant_turn(self): + raw = history() + history() + self.assertEqual([m["content"] for m in normalized(raw) if m["role"] == "tool"], + ["RESULT_FROM_A", "RESULT_FROM_B"] * 2) + raw = history() + raw.insert(2, {"role": "user", "content": "intervening message"}) + self.assertEqual([m["content"] for m in normalized(raw) if m["role"] == "tool"], + ["RESULT_FROM_B", "RESULT_FROM_A"]) + + def test_json_encoded_history_and_calls(self): + raw = history() + raw[1]["tool_calls"] = json.dumps(raw[1]["tool_calls"]) + self.assertEqual(normalized(json.dumps(raw)), normalized(history())) + + def test_multimodal_result_moves_with_its_call(self): + raw = history() + raw[2]["content"] = [{"type": "text", "text": "RESULT_FROM_B"}, + {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}] + messages = normalized(raw) + self.assertEqual(messages[2]["content"], "RESULT_FROM_A") + self.assertEqual(messages[3]["content"], [{"type": "text", "text": "RESULT_FROM_B"}, + {"type": "image", "source": "data:image/png;base64,AA=="}]) + + def test_http_engine_receives_the_ordered_prompt(self): + tok = ByteTokenizer() + engine = MockEngine(tok, "ok", max_context=4096) + service = Service(engine, tok, TEMPLATE) + httpd = serve(service, port=0) + connection = http.client.HTTPConnection("127.0.0.1", httpd.server_address[1], timeout=10) + try: + connection.request("POST", "/v1/chat/completions", json.dumps({ + "messages": history(), "max_tokens": 16, "reasoning_effort": "none"}), + {"Content-Type": "application/json"}) + response = connection.getresponse() + body = response.read() + self.assertEqual(response.status, 200, body) + prompt = tok.decode(engine.last_prompt) + self.assertLess(prompt.index("RESULT_FROM_A"), prompt.index("RESULT_FROM_B")) + finally: + connection.close() + httpd.shutdown() + httpd.server_close() + + +if __name__ == "__main__": + unittest.main() From 409f2466ad2a589d8d9af711c960184e3f5de67f Mon Sep 17 00:00:00 2001 From: Keyan Hu <177766066+KeyanHu-git@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:55:57 +0100 Subject: [PATCH 28/45] tools/gguf_reader.py: bound the header reads and report malformed metadata as ValueError (#2288, #1919) A GGUF header with an unknown metadata type or an impossible length raised KeyError or OverflowError inside the reader, and setup, which expects a ValueError, printed a traceback instead of its diagnostic naming the broken shard. Strings, scalars, arrays and tensor dimensions now share one bounded read; counts are checked against the bytes left in the file before anything is constructed; type ids are checked before their values are decoded; nested arrays are reported as unsupported; general.alignment must be a positive multiple of 8. The file name is added once to the message. Ported from PR #2288 by KeyanHu-git with its tests (tools/test_gguf_reader_malformed.py). Checked against the old reader on the 18 GGUF v3 vocabulary files of the pinned llama.cpp: same metadata, tensors and data start. --- tools/gguf_reader.py | 86 +++++++++----- tools/test_gguf_reader_malformed.py | 176 ++++++++++++++++++++++++++++ 2 files changed, 235 insertions(+), 27 deletions(-) create mode 100644 tools/test_gguf_reader_malformed.py diff --git a/tools/gguf_reader.py b/tools/gguf_reader.py index 4da9d2d2..de30d3b9 100644 --- a/tools/gguf_reader.py +++ b/tools/gguf_reader.py @@ -10,6 +10,7 @@ no ggml dependency)"). It parses the header only; tensor data is never read. from __future__ import annotations import dataclasses +import os import pathlib import struct from typing import Any @@ -77,6 +78,10 @@ class TensorInfo: return self.elements // block_elems * block_bytes +_META_FMT = {"u8": "B", "i8": "b", "u16": "H", "i16": "h", "u32": "I", "i32": "i", + "f32": "f", "bool": "?", "u64": "Q", "i64": "q", "f64": "d"} + + class GGUFFile: def __init__(self, path: pathlib.Path): self.path = pathlib.Path(path) @@ -85,55 +90,82 @@ class GGUFFile: self.version = 0 self.alignment = 32 with self.path.open("rb") as fh: - self._parse(fh) + self._size = os.fstat(fh.fileno()).st_size + self._pos = 0 + try: + self._parse(fh) + except ValueError as e: + raise ValueError(f"{self.path.name}: {e}") from None self.data_start = self._data_start # ------------------------------------------------------------------ internals + def _read(self, fh, n: int) -> bytes: + left = self._size - self._pos + if n < 0 or n > left: + raise ValueError(f"header ends early: {n:,} bytes needed at offset {self._pos:,}, {left:,} left") + raw = fh.read(n) + self._pos += len(raw) + if len(raw) != n: + raise ValueError(f"header ends early at offset {self._pos:,}") + return raw + + def _unpack(self, fh, fmt: str) -> tuple: + return struct.unpack(fmt, self._read(fh, struct.calcsize(fmt))) + + def _count(self, fh, count: int, min_bytes: int, what: str) -> int: + if count * min_bytes > self._size - self._pos: + raise ValueError(f"{count:,} {what} cannot fit in the {self._size - self._pos:,} bytes left") + return count + def _parse(self, fh) -> None: - magic = struct.unpack(" str: - (n,) = struct.unpack(" tuple[str, int | None]: + if t not in GGUF_META: + raise ValueError(f"unknown metadata value type {t}") + return GGUF_META[t] def _value(self, fh): - (t,) = struct.unpack(" dict[str, int]: diff --git a/tools/test_gguf_reader_malformed.py b/tools/test_gguf_reader_malformed.py new file mode 100644 index 00000000..98358f02 --- /dev/null +++ b/tools/test_gguf_reader_malformed.py @@ -0,0 +1,176 @@ +"""A malformed GGUF header is refused with a ValueError that names the file, never a KeyError, OverflowError +or struct.error (#1919). Tensor-size support and setup compatibility policy are unchanged. +Over minimal GGUF v3 files written here (no download, no model, no GPU). + + python -m unittest tools.test_gguf_reader_malformed +""" +from __future__ import annotations + +import contextlib +import io +import struct +import sys +import tempfile +import unittest +from unittest import mock +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) +import setup as S # noqa: E402 +from gguf_reader import GGUFFile # noqa: E402 + + +class Stop(Exception): + """setup.fail(), caught instead of exiting.""" + + +def gstr(s: bytes) -> bytes: + return struct.pack(" bytes: + return struct.pack(" bytes: + return gstr(name) + struct.pack(" bytes: + return b + bytes(-len(b) % 32 + data) + + +class MalformedHeader(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.path = Path(self.tmp.name) / "m-00001-of-00002.gguf" + + def tearDown(self): + self.tmp.cleanup() + + def refused(self, raw: bytes) -> str: + self.path.write_bytes(raw) + with self.assertRaises(ValueError) as cm: + GGUFFile(self.path) + self.assertIn(self.path.name, str(cm.exception)) + return str(cm.exception) + + def test_unknown_metadata_value_type(self): + self.refused(pad(header(0, gstr(b"k") + struct.pack(" Date: Mon, 26 Oct 2026 18:56:54 +0100 Subject: [PATCH 29/45] nvfp4 local pack: read the checkpoint with cached sequential reads, not a process-lifetime np.memmap (#3377, #3378) Checkpoint.raw mapped every shard for the life of the process. On Windows each faulted page of the ~64 GB of expert bytes is charged to the process working set, so the pack step looked like a 64 GB RAM demand and was killed by free-RAM watchers on a PC with a model loaded (nothing leaked: it all came back at once). raw() now reads the tensor's byte range into a fresh buffer through one cached file handle per shard; the pages go to the system file cache, which counts as available. The author measured the same bytes, 1.2x faster, flat working set, and a byte-identical pack. raw() is no longer thread-safe (this file uses no threads). Ported from PR #3378 by jerry78424 (the fix for his issue #3377) with its two tests; I ran the tests (13 pass); the full 102 GB pack was not run. --- tools/nvfp4_local_pack.py | 27 +++++++++++++++++----- tools/test_nvfp4_local_pack.py | 41 ++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/tools/nvfp4_local_pack.py b/tools/nvfp4_local_pack.py index 03f5c884..a9752e4a 100644 --- a/tools/nvfp4_local_pack.py +++ b/tools/nvfp4_local_pack.py @@ -63,7 +63,19 @@ PLE_ROW_BYTES = 90 # 80 B of E2M1 codes + 10 E4M3 block scales, per 160 # --------------------------------------------------------------------------------------------- safetensors access class Checkpoint: - """Header-indexed, memory-mapped access to a checkpoint's safetensors shards (raw bytes, any dtype).""" + """Header-indexed, buffered access to a checkpoint's safetensors shards (raw bytes, any dtype). + + Reads go through a cached file handle into a fresh buffer instead of a process-lifetime np.memmap: + a memmap sweep of the ~64 GB of expert bytes charges every faulted page to the PROCESS WORKING + SET, which Windows (and every free-RAM observer reading GlobalMemoryStatusEx) counts as used + until the OS trims it - the pack step then looks like a ~64 GB RAM demand while its real + committed need is a few GB, and under memory pressure it is the pack run itself that pays + (issue: the silent exit-1 mid-pack failure). + A cached sequential read puts the same pages in the system file cache (standby: counted as + available). The returned array is a fresh WRITABLE buffer - no consumer writes (a mutator would + previously have hit the read-only memmap) - and reads share one handle per shard, so raw() is + not thread-safe, unlike the memmap it replaces. Each shard is read as three ascending streams + (exceptions, weights, CSF-fixed) walked expert-ascending.""" def __init__(self, folder, partial_ok=False): self.dir = pathlib.Path(folder) @@ -76,7 +88,7 @@ class Checkpoint: if not files: raise FileNotFoundError("no .safetensors files in " + str(self.dir)) self.meta: dict[str, tuple[str, str, list[int], int, int]] = {} - self._mm: dict[str, np.memmap] = {} + self._fh: dict[str, "object"] = {} for fn in files: path = self.dir / fn if not path.exists() and partial_ok: @@ -100,9 +112,14 @@ class Checkpoint: def raw(self, name) -> np.ndarray: fn, _, _, a, b = self.meta[name] - if fn not in self._mm: - self._mm[fn] = np.memmap(self.dir / fn, dtype=np.uint8, mode="r") - return self._mm[fn][a:b] + f = self._fh.get(fn) + if f is None: + f = self._fh[fn] = open(self.dir / fn, "rb") + buf = np.empty(b - a, dtype=np.uint8) + f.seek(a) + if f.readinto(buf) != b - a: + raise EOFError("%s: shard %s ended early at %d" % (name, fn, a)) + return buf def array(self, name, np_dtype) -> np.ndarray: return self.raw(name).view(np_dtype).reshape(self.shape(name)) diff --git a/tools/test_nvfp4_local_pack.py b/tools/test_nvfp4_local_pack.py index dd6fbe32..b32c50e1 100644 --- a/tools/test_nvfp4_local_pack.py +++ b/tools/test_nvfp4_local_pack.py @@ -1,5 +1,7 @@ """Tests for tools/nvfp4_local_pack.py: the CSF scale decode, the MXFP8 dequantization, the PLE rows.""" +import json import pathlib +import struct import sys import numpy as np @@ -114,3 +116,42 @@ def test_nvfp4_blocks_layout_by_hand(): # within a 16-block: element j in the low nibble, element j+8 in the high one blk0 = out[0, 4:12] assert [int(b & 15) for b in blk0] == list(range(8)) and [int(b >> 4) for b in blk0] == list(range(8, 16)) + + +def _write_shard(path, tensors): + """tensors: name -> (dtype, shape, uint8 bytes), written safetensors-style (data after the header).""" + hdr, data, off = {}, bytearray(), 0 + for name, (dt, shape, buf) in tensors.items(): + hdr[name] = {"dtype": dt, "shape": shape, "data_offsets": [off, off + len(buf)]} + data += buf + off += len(buf) + hj = json.dumps(hdr).encode("utf-8") + hj += b" " * (-len(hj) % 8) + with open(path, "wb") as f: + f.write(struct.pack(" Date: Mon, 26 Oct 2026 18:57:13 +0100 Subject: [PATCH 30/45] kq_cpu_bench: i-quant pairs no longer crash, and Q2_0 is timed on the CPU pool's path (#3871) make_blob quantized its random test rows with ggml-cpu's type traits from_float, which the i-quants do not have: an IQ3_S pair called a null pointer (an access violation on Windows, SIGSEGV on Linux) before the first timing. It now uses ggml_quantize_chunk, with a flat importance matrix where the type needs one. A Q2_0 gate/up or down is timed as pool.cpp runs it (activations as an ActQ, Strata's own Q2_0 rows, SwiGLU in between) instead of with ggml-cpu's Q2_0 dot, and the pair's header line says so. Other formats are timed as before. Ported from PR #3871 by Licenser. Built on this PC (MSVC, CPU only) and run: iq3_s/q2_0 0.531, iq2_xs/q2_0 0.336 and q2_0/q2_0 0.214 ms per expert per thread (--mb 512, 1 thread). --- src/kernels/cpu/kq_cpu_bench.cpp | 60 ++++++++++++++++++++++++++------ 1 file changed, 50 insertions(+), 10 deletions(-) diff --git a/src/kernels/cpu/kq_cpu_bench.cpp b/src/kernels/cpu/kq_cpu_bench.cpp index 0655bc0e..3a2f9b8d 100644 --- a/src/kernels/cpu/kq_cpu_bench.cpp +++ b/src/kernels/cpu/kq_cpu_bench.cpp @@ -53,19 +53,23 @@ std::vector split(const std::string& s) { } // one expert blob in the GGUF form: gate rows, up rows (n_ff x n_embd each), down rows (n_embd x n_ff), from random -// weights quantized by ggml-cpu (valid scales, as a real file has) +// weights quantized by ggml (valid scales, as a real file has). ggml_quantize_chunk, not the CPU traits' from_float: +// ggml-cpu has no from_float for the i-quants (IQ3_S called a null pointer: an access violation on Windows) void make_blob(const cpu::NativeFmt& f, uint8_t* blob, std::mt19937& rng) { std::normal_distribution nd(0.f, 0.02f); std::vector row((size_t) std::max(kH, kFF)); - const auto* tg = ggml_get_type_traits_cpu((ggml_type) f.gu_type); - const auto* td = ggml_get_type_traits_cpu((ggml_type) f.d_type); + const std::vector imatrix((size_t) std::max(kH, kFF), 1.0f); + auto quant = [&](int type, uint8_t* dst, int64_t n) { + ggml_quantize_chunk((ggml_type) type, row.data(), dst, 0, 1, n, + ggml_quantize_requires_imatrix((ggml_type) type) ? imatrix.data() : nullptr); + }; for (int64_t r = 0; r < 2 * kFF; ++r) { for (int64_t i = 0; i < kH; ++i) row[(size_t) i] = nd(rng); - tg->from_float(row.data(), blob + (size_t) r * f.gu_row, kH); + quant(f.gu_type, blob + (size_t) r * f.gu_row, kH); } for (int64_t r = 0; r < kH; ++r) { for (int64_t i = 0; i < kFF; ++i) row[(size_t) i] = nd(rng); - td->from_float(row.data(), blob + f.down_off + (size_t) r * f.d_row, kFF); + quant(f.d_type, blob + f.down_off + (size_t) r * f.d_row, kFF); } } @@ -123,16 +127,36 @@ int main(int argc, char** argv) { ha(kMaxT, std::vector(cpu::kNativeHBytes)); const void* act[kMaxT]; const void* hq[kMaxT]; + // a Q2_0 down takes the pool's own path (pool.cpp, run_split_multi_native and drain mode 6): the activation + // as an ActQ (act_quant_any) and Strata's Q2_0 rows (q2_rows_any), not ggml-cpu's Q2_0 dot + const bool q2_down = cpu::q2_native_kernels(f.d_type); + std::vector h2(q2_down ? kMaxT : 0); + const cpu::ActQ* a2[kMaxT] = {}; + // a Q2_0 gate/up the same (pool.cpp mode 5): x as an ActQ, gate and up on q2_rows_any, then SwiGLU + const bool q2_gu = cpu::q2_native_kernels(f.gu_type); + std::vector x2(q2_gu ? kMaxT : 0); + const cpu::ActQ* ax[kMaxT] = {}; for (int t = 0; t < kMaxT; ++t) { std::vector x(kH), h(kFF); for (auto& v : x) v = nd(rng); for (auto& v : h) v = 0.1f * nd(rng); - cpu::native_quant_act(f, x.data(), xa[t].data()); - cpu::native_quant_h(f, h.data(), ha[t].data()); + if (q2_gu) { + cpu::act_quant_any(x.data(), (int) kH, x2[(size_t) t]); + ax[t] = &x2[(size_t) t]; + } else { + cpu::native_quant_act(f, x.data(), xa[t].data()); + } + if (q2_down) { + cpu::act_quant_any(h.data(), (int) kFF, h2[(size_t) t]); + a2[t] = &h2[(size_t) t]; + } else { + cpu::native_quant_h(f, h.data(), ha[t].data()); + } act[t] = xa[t].data(); hq[t] = ha[t].data(); } - std::printf("\n%s: %zu experts of %.3f MB (%.0f MB)\n", pair.c_str(), E, f.bytes / 1e6, E * (double) f.bytes / 1e6); + std::printf("\n%s: %zu experts of %.3f MB (%.0f MB)%s%s\n", pair.c_str(), E, f.bytes / 1e6, E * (double) f.bytes / 1e6, + q2_gu ? ", Q2_0 gate/up" : "", q2_down ? ", Q2_0 down on Strata's rows (the pool's path)" : ""); for (int nt : nts) { for (int T : threads) { if (T < 1) continue; @@ -141,6 +165,11 @@ int main(int argc, char** argv) { std::atomic next{0}; auto work = [&] { std::vector ffb((size_t) kMaxT * kFF), outb((size_t) kMaxT * kH); + std::vector gb(q2_gu ? (size_t) kMaxT * kFF : 0), ub(q2_gu ? (size_t) kMaxT * kFF : 0); + float* gp[kMaxT] = {}; + float* up[kMaxT] = {}; + if (q2_gu) + for (int t = 0; t < kMaxT; ++t) { gp[t] = &gb[(size_t) t * kFF]; up[t] = &ub[(size_t) t * kFF]; } float* ff[kMaxT]; float* out[kMaxT]; for (int t = 0; t < kMaxT; ++t) { ff[t] = &ffb[(size_t) t * kFF]; out[t] = &outb[(size_t) t * kH]; } @@ -149,8 +178,19 @@ int main(int argc, char** argv) { const size_t e = next.fetch_add(1); if (e >= E) break; const uint8_t* blob = blobs + e * f.bytes; - cpu::native_gu_rows(f, blob, act, nt, ff, 0, (int) kFF); - cpu::native_down_rows(f, blob, hq, nt, out, 0, (int) kH); + if (q2_gu) { + cpu::q2_rows_any(blob, f.gu_row, (int) (kH / 64), ax, nt, gp, 0, (int) kFF); + cpu::q2_rows_any(blob + f.up_off, f.gu_row, (int) (kH / 64), ax, nt, up, 0, (int) kFF); + for (int t = 0; t < nt; ++t) + for (int64_t r = 0; r < kFF; ++r) + ff[t][r] = (gp[t][r] / (1.f + std::exp(-gp[t][r]))) * up[t][r]; + } else { + cpu::native_gu_rows(f, blob, act, nt, ff, 0, (int) kFF); + } + if (q2_down) + cpu::q2_rows_any(blob + f.down_off, f.d_row, (int) (f.n_ff / 64), a2, nt, out, 0, (int) kH); + else + cpu::native_down_rows(f, blob, hq, nt, out, 0, (int) kH); } volatile float sink = outb[0] + ffb[0]; (void) sink; From 6c09a1929c745b46c235ffb59c80b7323ef9d813 Mon Sep 17 00:00:00 2001 From: stuchapin909 <178119976+stuchapin909@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:57:30 +0100 Subject: [PATCH 31/45] CI: build the Metal engine on macos-26 (#3870, #3824) metal/src/mtl_rt.mm names MTLGPUFamilyMetal4 (macOS 26 SDK) and MTLCompileOptions.mathMode (macOS 15 SDK) behind @available, a run-time check; the names must still exist in the SDK the engine is compiled against, so the metal-link job failed on the macOS 14 SDK on every pull request that touched src/, include/ or metal/. The job now runs on macos-26 (the runner-images repository lists a macos-26 image). Ported from PR #3870 by stuchapin909. A GitHub Actions run cannot be made here: the author ran this workflow on his fork; the first run after the merge proves it. #3824 changes the same line with macos-15 and an Xcode 26.0.1 path pin, and is not taken. --- .github/workflows/metal-build.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/metal-build.yml b/.github/workflows/metal-build.yml index 7a69696f..a4f7d997 100644 --- a/.github/workflows/metal-build.yml +++ b/.github/workflows/metal-build.yml @@ -20,7 +20,9 @@ permissions: jobs: metal-link: - runs-on: macos-14 + # the macOS 26 SDK: metal/src/mtl_rt.mm names MTLGPUFamilyMetal4 (and MTLCompileOptions.mathMode, macOS 15) behind @available, + # which is a run-time check; the names must still be in the SDK the engine is compiled against + runs-on: macos-26 timeout-minutes: 45 env: # setup.py's LLAMA_CPP_COMMIT and metal/setup_mac.py's metal-cpp pin From e21a1872f7c5543bb00a588717dfc2e186acbf6d Mon Sep 17 00:00:00 2001 From: oscarlius <43489660+oscarlius@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:57:53 +0100 Subject: [PATCH 32/45] docs/BATCHING.md: the cache settings that let a long solo request move into a batch slot without reading its prompt again (#3334) Adds a minimal handoff configuration (--prompt-cache 1, --prompt-cache-every 0, --prompt-cache-root 0, --conversation-cache-mib 0), what each option does, that it costs RAM, that it does not make cold prompts prefill in parallel, and how to look for the handoff in the engine log, /metrics and /v1/status. Ported from PR #3334 by oscarlius (continuing #3035). The four options exist in src/program/generate.cpp and the o.prompt_cache > 0 gate matches the text; the log evidence was not reproduced here (no model run). --- docs/BATCHING.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 6e7b58d3..49abbb6e 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -188,6 +188,40 @@ about 10-25% speed per request on this card". `--parallel N` is honoured as aske - Slots are assigned so that consecutive requests land in different pipeline groups (`--batch-groups`). - A client that disconnects stops its slot (`BSTOP`); the others go on. +### Long prompts that move from solo to a batch slot + +The handoff above needs prompt-cache state. With `--prompt-cache 0`, moving a long request from the solo path into +a slot can read the whole prompt again. This minimal example enables handoff reuse without parking completed +conversations. Set these options in the model config's `args`, keeping the other arguments unchanged: + +``` +"args": [ ..., "--prompt-cache", "1", "--prompt-cache-every", "0", + "--prompt-cache-root", "0", "--conversation-cache-mib", "0" ] +``` + +`--prompt-cache 1` keeps the latest turn-boundary checkpoint so the `GEN` to `BGEN` handoff can reuse the live +prefix. `--prompt-cache-every 0` disables periodic checkpoints and `--prompt-cache-root 0` disables an extra root +checkpoint. The limit is per cache set: a slot can keep its own live state, so it is not one checkpoint shared by +every slot. `--conversation-cache-mib 0` still disables parking independent completed conversations in RAM; it does +not remove the prompt checkpoint or the state held by an active slot. +If conversation parking is already enabled, keep its existing budget instead of setting it to zero: that budget is +independent of the handoff configuration. + +This setting has RAM costs. The checkpoint and every slot's normal context state still consume memory, even with the +conversation cache off. Check the engine's free-memory report and the slot count that it actually accepts before +raising the context length or `"parallel"` value. + +It does not make independent cold prompts prefill in parallel. The server admits them one at a time; a running value +of four can mean four requests are in flight, not four slots decoding together. A slot already decoding may make +progress while the next prompt is read, but long independent prompts can finish before enough admissions overlap to +fill every configured slot. + +After changing the setting, send a long request alone and add a second request while it is decoding. In the engine +log, the first request's `GEN` to `BGEN` transfer should report a large reused prefix and only the new token(s) read. +Then check `/metrics` for the slots that were actually reading or decoding, and `/v1/status` for the effective +serving count. Treat this as handoff evidence only: it does not prove that every configured slot can stay resident or +that cold prompts have concurrent prefill. + ## Reading a prompt beside pipelined groups (experimental, opt-in) With a layer split and `--batch-groups` above 1 a prompt is read in one run: every decoding slot stops until it is From 05c1dabf1aab983d7f0dc06e2b01044ab0d4aceb Mon Sep 17 00:00:00 2001 From: Yuu <206304251+nekomario28@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:59:27 +0100 Subject: [PATCH 33/45] docs: the xe expert tier has no SSD fallback under the wrapper default, and a native pack needs --spec 2 or more (#2153, #1796) docs/INTEL.md and docs/INTEL_ARC.md described an SSD expert tier that strata-sycl.sh's default (STRATA_VERIFY_NO_HOST=1) does not have: every expert must be in VRAM or in the pinned RAM mirror, and the engine refuses to start otherwise (sycl/src/program/generate.cpp, 'REFUSED: ... are neither in VRAM nor mirrored'). A native (IQ) pack refuses --spec 0 and 1 (sycl/src/program/generate.cpp and src/program/generate.cpp). Ported by hand from PR #2153 by nekomario28 onto the rewritten pages, each sentence checked against those two messages. The hunk for docs/TROUBLESHOOTING.md is left out: the entry it changed is no longer on that page. --- docs/INTEL.md | 10 +++++++--- docs/INTEL_ARC.md | 3 +++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/INTEL.md b/docs/INTEL.md index 15615039..85b501da 100644 --- a/docs/INTEL.md +++ b/docs/INTEL.md @@ -127,9 +127,13 @@ the oneAPI runtime image with the serve pipes attached. Paths in the config's `a "sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "repetition_penalty": 1.05}} ``` -With `--stream-experts` any expert left out of VRAM is read from the SSD and computed on the CPU when routed, so the reserve -matters: on the B70 with Coder IQ1_M a 1,536 MiB reserve left the cache 128 experts short and decode fell to 5-10 tok/s, while -1,024 MiB fits all 12,288 with 2 GB of VRAM free. +A native (IQ) pack takes `--spec` 2 at the smallest: the engine refuses `--spec 0` and `--spec 1` on one (it needs `--native SHARD1`, `--spec T` +with T >= 2 and `--prefill CHUNK`), so speculative decoding cannot be turned off for these packs. + +With `--stream-experts` under `STRATA_VERIFY_NO_HOST=1` (the `strata-sycl.sh` default) there is no SSD expert tier: every expert +must be in VRAM or in the pinned RAM mirror (`STRATA_MIRROR_MIB`), and the engine refuses to start when the two do not cover the model +("REFUSED: N experts are neither in VRAM nor mirrored"). Raise the mirror or lower `--max-context`. So the reserve matters: on the B70 +with Coder IQ1_M 1,024 MiB fits all 12,288 experts with 2 GB of VRAM free. ## Things that matter on this GPU diff --git a/docs/INTEL_ARC.md b/docs/INTEL_ARC.md index 4adf07a3..a38fab0d 100644 --- a/docs/INTEL_ARC.md +++ b/docs/INTEL_ARC.md @@ -47,6 +47,9 @@ engine package. Otherwise [build the image yourself](DOCKER.md#build-it-yourself `sudo apt install docker.io git`, then `sudo usermod -aG docker,render $USER` and log in again. - VRAM: the port keeps the experts on the card (`--stream-experts`). A 32 GB card holds the Coder IQ1_M or IQ2_XS. Smaller cards mirror part of the experts in RAM and are slower. + Under the wrapper's `STRATA_VERIFY_NO_HOST=1` there is no SSD expert tier on `xe`: every expert must + be in VRAM or in the pinned RAM mirror (`STRATA_MIRROR_MIB`), and the engine refuses to start when + the two do not cover the model. Size the RAM accordingly, or lower `--max-context`. ## Build with Docker (what `setup --backend sycl` uses) From 7783b1c18eea95d05478836c0d2f45826bd91b69 Mon Sep 17 00:00:00 2001 From: Norm <304706238+Buddychek@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:00:14 +0100 Subject: [PATCH 34/45] docs: a crashed engine start names itself, and a setup run again keeps the installed size (#3243) Two 0.1.44.1 changes no page told. TROUBLESHOOTING.md gets the start error 'the engine process ended: ...' (serve/server.py start_exit_note: the signal or Windows exit code, and for an illegal instruction the AVX, AVX2, FMA and F16C flags the CPU lacks). SOURCE_INSTALL.md says a setup run again pre-selects the installed size, marked '(installed)', and --yes takes it (setup.py size_tag, installed_size). Written by hand from PR #3243 by Buddychek, whose hunks no longer fit the rewritten pages; each sentence checked against the two functions. --- docs/SOURCE_INSTALL.md | 2 ++ docs/TROUBLESHOOTING.md | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/docs/SOURCE_INSTALL.md b/docs/SOURCE_INSTALL.md index 1db38150..692891de 100644 --- a/docs/SOURCE_INSTALL.md +++ b/docs/SOURCE_INSTALL.md @@ -33,6 +33,8 @@ Choose a pack that fits your machine; Q2_0 is an example, not a universal minimu In PowerShell, prefix the wrapper with `.\`, for example `.\START-HERE.bat`. `SETUP.bat` opens setup again to add a model or change settings. The wrapper can reuse an existing install; first-start and later load times depend on the pack, disk, RAM and backend. A model can take several minutes to load. +Run again over an installed model, setup pre-selects the size that is installed and marks it "(installed)", and `--yes` takes it: a repeat run +does not move the model to the recommended size. When no ready-made engine fits the PC, setup compiles one. That needs the Visual Studio 2022 Build Tools with the C++ workload; Visual Studio 2019 is too old (the sources are C++20). With a CUDA toolkit, CUDA 13.0 to 13.2 accept Visual Studio 2022 only, and diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index f55fba05..37c97734 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -63,6 +63,12 @@ Retry it in the app, or rerun the same `strata launch` command. Completed model- free space and the error message. For an interrupted Terminal installer, rerun the install command. Only a source checkout uses `START-HERE.bat` / `./setup.sh` to resume source setup. +**The engine stops at the start with no line in its log, and the error says `the engine process ended: ...`.** +The error names how the system ended the engine process, because the engine log is silent then: for example `killed by signal 4 (SIGILL, Illegal +instruction)` on Linux and Mac, or `exit code 0xC000001D: illegal instruction` on Windows. An illegal instruction means the engine ran an instruction +the CPU cannot execute; the error lists the AVX, AVX2, FMA and F16C flags the CPU lacks, or says the CPU has them all, which is a bug in the engine. +Report it with the CPU model. + **Startup takes a long time or the computer becomes slow.** Large models need time to check files, prepare packs and fill memory. A first launch can take many minutes; there is no fixed startup time. Watch progress and the engine log. If memory pressure is high, close memory-heavy programs and try a From c0845b7fc513b61f29fd94c1ddbb358c97a83a82 Mon Sep 17 00:00:00 2001 From: JoShMiQueL <26714939+JoShMiQueL@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:01:17 +0100 Subject: [PATCH 35/45] bench: tools/strata_bench.py reads the CUDA UMD version, the storage, the engine's build toolkit and GPU power and PCIe detail (#3250, #2111) The report written by BENCH.bat and bench.sh had fields missing or wrong: nvidia-smi's 'CUDA UMD Version:' (current drivers) was not read, the value was the newest CUDA the driver supports but was labelled like the engine's toolkit, storage always said 'not measured', and Windows 11 showed as Windows 10. Now the report says 'CUDA (driver supports up to): X; engine built for CUDA Y' (BUILD.json beside the engine), names the storage device (Get-PhysicalDisk, system_profiler, lsblk -e 7 to skip snap loop devices), adds a 'GPU detail (after the run, near idle)' line with power limit and draw, PCIe generation and width, pstate and temperature, and recognises Windows 11. The standard report (strata bench run, strata_cli/bench_facts.py) already read the UMD version, storage and power limit; this brings the legacy tool to the same. Ported from PR #3250 by JoShMiQueL with its tests. --- tools/strata_bench.py | 70 ++++++++++++++++++++++++++++++++------ tools/test_strata_bench.py | 48 ++++++++++++++++++++++++++ 2 files changed, 108 insertions(+), 10 deletions(-) diff --git a/tools/strata_bench.py b/tools/strata_bench.py index 36d919e7..806273db 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -483,15 +483,26 @@ def cpu_name() -> str | None: def gpu_info_local() -> dict: - out = run_cmd(["nvidia-smi", "--query-gpu=name,memory.total,driver_version", "--format=csv,noheader,nounits"]) + out = run_cmd(["nvidia-smi", "--query-gpu=name,memory.total,driver_version,power.limit,power.draw,pcie.link.gen.current,pcie.link.width.current,pstate,temperature.gpu", + "--format=csv,noheader,nounits"]) gpus = [] for line in out.splitlines(): p = [x.strip() for x in line.split(",")] if len(p) >= 3: - gpus.append({"name": p[0], "vram_mib": int(float(p[1])) if p[1].replace(".", "").isdigit() else None, "driver": p[2]}) + g = {"name": p[0], "vram_mib": int(float(p[1])) if p[1].replace(".", "").isdigit() else None, "driver": p[2]} + if len(p) >= 9: + g.update({"power_limit_w": p[3], "power_draw_w": p[4], "pcie": f"gen{p[5]} x{p[6]}", + "pstate": p[7], "temp_c": p[8]}) + gpus.append(g) + if not gpus: + out = run_cmd(["nvidia-smi", "--query-gpu=name,memory.total,driver_version", "--format=csv,noheader,nounits"]) + for line in out.splitlines(): + p = [x.strip() for x in line.split(",")] + if len(p) >= 3: + gpus.append({"name": p[0], "vram_mib": int(float(p[1])) if p[1].replace(".", "").isdigit() else None, "driver": p[2]}) info = {"gpus": gpus} head = run_cmd(["nvidia-smi"]) - m = re.search(r"CUDA Version:\s*([\d.]+)", head) + m = re.search(r"CUDA(?: UMD)? Version:\s*([\d.]+)", head) if m: info["cuda"] = m.group(1) if not gpus: @@ -549,6 +560,37 @@ def gpu_info_local() -> dict: return info +def storage_info() -> str | None: + if os.name == "nt": + out = run_cmd(["powershell", "-NoProfile", "-Command", + "Get-PhysicalDisk | Select-Object -First 4 FriendlyName,MediaType,BusType | " + "ForEach-Object { $_.FriendlyName + ' ' + $_.MediaType + '/' + $_.BusType }"]) + names = [x.strip() for x in out.splitlines() if x.strip() and "FriendlyName" not in x] + return "; ".join(names) or None + if sys.platform == "darwin": + out = run_cmd(["system_profiler", "SPNVMeDataType", "SPSerialATADataType"]) + names = re.findall(r"Model:\s*(.+)", out) + if names: + return "; ".join(n.strip() for n in names) + return None + out = run_cmd(["lsblk", "-d", "-o", "NAME,MODEL,TRAN", "-n", "-e", "7"]) # -e 7: skip loop devices (snap mounts) + if out.strip(): + return "; ".join(x.strip() for x in out.splitlines() if x.strip()) or None + return None + + +def engine_build(cfg: dict | None) -> dict | None: + """BUILD.json next to the engine exe: the toolkit/archs it was compiled with, unlike nvidia-smi's driver ceiling.""" + exe = (cfg or {}).get("exe") + if not exe: + return None + try: + b = json.loads((Path(exe).parent / "BUILD.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return {k: b[k] for k in ("version", "source", "cuda", "rocm", "archs", "ptx", "portable") if b.get(k) is not None} or None + + QUANT = re.compile(r"(?i)(?:^|[-_.])((?:UD-)?(?:IQ\d_[A-Z]+|Q\d_[A-Z0-9_]+|Q\d_K(?:_[A-Z]+)?|IQ\d_?[A-Z]*|BF16|F16|Q\d))(?=[-_.]|$)") SECRET_KEY = re.compile(r"(?i)key|token|secret|password|auth") @@ -672,9 +714,12 @@ def collect_machine(base: str, key: str, cfg: dict | None, gpu_arg: str | None = n_ctx = n_ctx or (props.get("default_generation_settings") or {}).get("n_ctx") return { "gpu": gpu_names, "gpu_vram_mib": vram_mib, "gpu_driver": (used[0].get("driver") if used else local.get("rocm_driver")), - "cuda": local.get("cuda"), "cpu": static.get("cpu_name") or cpu_name(), "cpu_cores": static.get("cores"), + "gpu_detail": [{k: v for k, v in g.items() if k not in ("name", "vram_mib", "driver")} for g in used] or None, + "cuda": local.get("cuda"), "engine_build": engine_build(cfg), + "cpu": static.get("cpu_name") or cpu_name(), "cpu_cores": static.get("cores"), + "storage": storage_info(), "cpu_threads": static.get("threads") or os.cpu_count(), "ram_gib": total_ram_gib(), - "os": f"{platform.system()} {platform.release()} ({platform.version()})" if os.name == "nt" else f"{platform.system()} {platform.release()}", + "os": f"{platform.system()} {'11' if int(platform.version().split('.')[-1] or 0) >= 22000 else platform.release()} ({platform.version()})" if os.name == "nt" else f"{platform.system()} {platform.release()}", "python": platform.python_version(), "strata_version": project_version(), "strata_commit": git_commit(), "engine_version": (eng.get("version") or status.get("engine") or str(props.get("build_info", "")).replace("Strata ", "") or None), @@ -856,11 +901,16 @@ def render_readme(res: dict) -> str: "## Hardware and software", "", f"- GPU and VRAM: {gpu}, {vram}", f"- CPU: {mc.get('cpu') or 'not read'} ({mc.get('cpu_cores') or '?'} cores, {mc.get('cpu_threads') or '?'} threads); " - f"installed RAM: {mc.get('ram_gib') or '?'} GiB; storage: not measured", - f"- OS: {mc.get('os')}; GPU driver: {mc.get('gpu_driver') or 'not read'}; CUDA: {mc.get('cuda') or 'not read'}", + f"installed RAM: {mc.get('ram_gib') or '?'} GiB; storage: {mc.get('storage') or 'not read'}", + f"- OS: {mc.get('os')}; GPU driver: {mc.get('gpu_driver') or 'not read'}; " + f"CUDA (driver supports up to): {mc.get('cuda') or 'not read'}" + + (f"; engine built for CUDA {(mc.get('engine_build') or {}).get('cuda')}" if (mc.get('engine_build') or {}).get('cuda') else ""), f"- Strata: project {mc.get('strata_version') or '?'}, commit {mc.get('strata_commit') or 'not a git checkout'}; " - f"engine {mc.get('engine_version') or 'not read'}", - "- Background workloads and power limits: not recorded", "", + f"engine {mc.get('engine_version') or 'not read'}"] + for g in (mc.get("gpu_detail") or []): + if g: + L.append("- GPU detail (after the run, near idle): " + ", ".join(f"{k}={v}" for k, v in g.items() if v is not None)) + L += ["- Background workloads: not recorded (GPU power limit/draw read above)", "", "## Model and configuration", "", f"- Model and quantization: {model}", f"- Context: {mc.get('context') or 'not read'} tokens; parallel slots: {mc.get('parallel_slots') or 1}", @@ -909,7 +959,7 @@ def render_readme(res: dict) -> str: L += ["", "Per-request data: `results.json`. Engine log lines from the start: `engine-log-excerpt.txt` (when this run started the server).", "", "## Correctness and limitations", "", "Not measured: this is a speed suite. The conversation uses the model's own replies, so token counts differ a little between runs. " - "Machine details come from the server, `nvidia-smi`/`rocm-smi` and the OS; background load and power limits are not recorded. " + "Machine details come from the server, `nvidia-smi`/`rocm-smi` and the OS; background load is not recorded. " f"Total time of the suite: {res['elapsed_s']:.0f} s.", ""] return "\n".join(L) diff --git a/tools/test_strata_bench.py b/tools/test_strata_bench.py index 80babc65..ec223e59 100644 --- a/tools/test_strata_bench.py +++ b/tools/test_strata_bench.py @@ -322,6 +322,27 @@ class ReportTests(unittest.TestCase): m = B.collect_machine(srv.base, "", {"backend": "sycl"}) self.assertEqual((m["gpu"], m["cuda"]), (["Intel Arc Pro B70"], None)) + def test_the_report_labels_the_driver_s_cuda_and_the_engine_s_build(self): + """#2111: the CUDA line was the driver's ceiling read as the engine's toolkit, and storage said "not measured".""" + srv = FakeStrata() + self.addCleanup(srv.stop) + nv = {"gpus": [{"name": "NVIDIA GeForce RTX 9999", "vram_mib": 16384, "driver": "616.92", + "power_limit_w": "165.00", "power_draw_w": "20.25", "pcie": "gen4 x8", + "pstate": "P3", "temp_c": "45"}], "cuda": "13.4"} + with mock.patch.object(B, "gpu_info_local", return_value=nv), mock.patch.object( + B, "storage_info", return_value="Samsung SSD 990 EVO Plus 2TB SSD/NVMe"), mock.patch.object( + B, "engine_build", return_value={"version": "0.1.43", "cuda": "13.0"}): + with tempfile.TemporaryDirectory() as d: + self.assertEqual(self.run_main(srv, d), 0) + readme = next(Path(d).iterdir()).joinpath("README.md").read_text(encoding="utf-8") + for part in ("CUDA (driver supports up to): 13.4; engine built for CUDA 13.0", + "storage: Samsung SSD 990 EVO Plus 2TB SSD/NVMe", + "GPU detail (after the run, near idle): power_limit_w=165.00, power_draw_w=20.25, " + "pcie=gen4 x8, pstate=P3, temp_c=45", + "Background workloads: not recorded (GPU power limit/draw read above)"): + self.assertIn(part, readme) + self.assertNotIn("storage: not measured", readme) + def test_a_bench_server_never_saves_over_the_users_profile(self): """#2088: --expert-profile-save writes the profile at quit; the bench's own server runs without it.""" cfg = {"args": ["--expert-profile", "p.bin", "--expert-profile-save", "p.bin", "--spec", "4"]} @@ -382,5 +403,32 @@ class ReportTests(unittest.TestCase): self.assertEqual(B.project_version(), "9.8.7") +class MachineDetailTests(unittest.TestCase): + """#2111: what the report reads straight from nvidia-smi on the PC.""" + + ROW = "NVIDIA GeForce RTX 4060 Ti, 16380, 616.92, 165.00, 20.25, 4, 8, P3, 45" + + @staticmethod + def queries(cmd) -> bool: + return any(str(c).startswith("--query-gpu") for c in cmd) + + def test_cuda_header_in_both_forms(self): + """Current drivers print "CUDA UMD Version: 13.4"; the old "CUDA Version:" line still has to be read.""" + for head, want in (("Some header\n\nCUDA UMD Version: 13.4\n", "13.4"), + ("Some header\n\nCUDA Version: 12.6\n", "12.6")): + def fake(cmd, *a, _head=head, **k): + return self.ROW if self.queries(cmd) else _head + with mock.patch.object(B, "run_cmd", side_effect=fake): + info = B.gpu_info_local() + self.assertEqual((info["cuda"], info["gpus"][0]["power_limit_w"]), (want, "165.00")) + + def test_power_pcie_pstate_and_temperature_are_read(self): + with mock.patch.object(B, "run_cmd", + side_effect=lambda cmd, *a, **k: self.ROW if self.queries(cmd) else ""): + g = B.gpu_info_local()["gpus"][0] + self.assertEqual((g["name"], g["vram_mib"], g["driver"]), ("NVIDIA GeForce RTX 4060 Ti", 16380, "616.92")) + self.assertEqual((g["power_limit_w"], g["pcie"], g["pstate"], g["temp_c"]), ("165.00", "gen4 x8", "P3", "45")) + + if __name__ == "__main__": unittest.main() From a3b7d9de3fc16d733f804d001650f494ebb4b753 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:01:50 +0100 Subject: [PATCH 36/45] docs/AMD_HIP.md: a hand-built engine has no hipBLASLt tuning table unless it is pointed at one (#4034) The Build section said nothing about it. gemm.cu (create_hipblaslt_state, own_tuning_dir) takes STRATA_HIPBLASLT_TUNING, else the file /tuning/-hipblaslt-.txt, else plain hipBLAS. The report measured 826 against 1,043 tok/s at 8K prompts on a gfx1151 (one run per arm, stated as such) and the log line that tells whether a table was taken. The extra log line the issue suggests for the no-table case is a small engine change and is not part of this commit. --- docs/AMD_HIP.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 2ff7549e..d858002f 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -193,6 +193,13 @@ the card's name, its architecture and the build's list. - CMake fetches the pinned llama.cpp revision. For an offline build, point `STRATA_GGML_DIR` at a checkout of that exact revision. - Linux engine packages: `VARIANT=rx6000 packaging/build_hip_linux.sh`. +- **A hand-built engine has no tuning table.** The packaged engines carry `tuning/-hipblaslt-.txt` beside the binary + ([Ready-made packages](#ready-made-packages) lists which); a build made with plain `cmake` and started + through `serve/server.py` has none, and the prompt GEMMs fall back to plain hipBLAS. On Strix Halo (gfx1151) that read prompts + 20-25% slower in one report (1,043 against 826 tok/s at 8K, hipBLASLt 1.4.1, a single run per arm, not a paired A/B). Point + `STRATA_HIPBLASLT_TUNING` at the file in `tools/hip/` (`gfx1151-hipblaslt-100401.txt` for hipBLASLt 1.4.1), or copy it into a + `tuning/` folder next to the `strata` binary. The start log then has the line `prefill gemm: hipBLASLt tuning enabled (N rows, + gfx1151, version 100401)`; without it, no table was taken. Run the registered checks with: From 557aad026554ba3d7005c0518eaae292e9a3af7f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:03:30 +0100 Subject: [PATCH 37/45] hip- is accepted wherever the backend is named (#4013) STRATA_ENGINE_BACKEND=hip-rdna2 worked for strata update (updater.detect_hardware), but strata update --backend hip-rdna2 offered no package and strata launch stopped with "STRATA_ENGINE_BACKEND='hip-rdna2' is not one of cpu, cuda, hip, metal, sycl". engine_component.split_backend reads hip- as the hip family and its package; detect_backend (the start path), detect_hardware and update --backend all use it. Any other name is checked as before. Tests in tests/terminal/test_gfx_selection.py. --- strata_cli/update_cmd.py | 4 ++- strata_control/engine_component.py | 11 +++++++- strata_control/updater.py | 7 ++--- tests/terminal/test_gfx_selection.py | 41 ++++++++++++++++++++++++++++ 4 files changed, 57 insertions(+), 6 deletions(-) diff --git a/strata_cli/update_cmd.py b/strata_cli/update_cmd.py index cfe05e4f..196d5eaa 100644 --- a/strata_cli/update_cmd.py +++ b/strata_cli/update_cmd.py @@ -186,7 +186,9 @@ def run(a) -> int: try: hardware = updater.detect_hardware() if a.backend: - hardware["backend"] = a.backend + hardware["backend"], variant = ec.split_backend(a.backend) # --backend hip-rdna2 = the hip family, the rdna2 package (#4013) + if variant: + hardware["variant_wanted"] = variant hardware["backend_source"] = "requested" # the person's own decision: the make guard lets it through lines: list = [] cancel = threading.Event() diff --git a/strata_control/engine_component.py b/strata_control/engine_component.py index c7f60e0b..94f8d0f7 100644 --- a/strata_control/engine_component.py +++ b/strata_control/engine_component.py @@ -436,11 +436,20 @@ def runtime_version() -> str | None: # ----------------------------------------------------------------------------------------------- the GPU +def split_backend(value) -> tuple[str, str]: + """(backend, variant) for a name the person typed: "hip-rdna2" is the hip family and its rdna2 package (the way the feed labels an AMD + package, #4013), "hip" is the family alone, any other name is returned as it is with no variant.""" + name = str(value or "").strip().lower() + if name not in BACKEND_MATRIX and name.startswith("hip-") and len(name) > 4: + return "hip", name[4:] + return name, "" + + def detect_backend(environ=None) -> tuple[str | None, str]: """(backend, how) for this machine: the engine family its GPU needs. Bounded, read-only probes of tools that are already installed; ``STRATA_ENGINE_BACKEND`` overrides (the tests and the support desk use it).""" environ = os.environ if environ is None else environ - forced = environ.get(ENV_BACKEND, "").strip().lower() + forced = split_backend(environ.get(ENV_BACKEND, ""))[0] # "hip-rdna2" starts the hip family (the package choice reads the variant) if forced: if forced not in BACKEND_MATRIX: raise ComponentProblem(f"{ENV_BACKEND}={forced!r} is not one of {', '.join(sorted(BACKEND_MATRIX))}") diff --git a/strata_control/updater.py b/strata_control/updater.py index 30f226ac..995e0c64 100644 --- a/strata_control/updater.py +++ b/strata_control/updater.py @@ -258,11 +258,10 @@ def detect_hardware(environ=None) -> dict: selection treats as "cannot tell", never as a refusal.""" environ = os.environ if environ is None else environ prefer = "" - forced = str(environ.get(ec.ENV_BACKEND, "")).strip().lower() - if forced.startswith("hip-") and forced not in ec.BACKEND_MATRIX: + family, prefer = ec.split_backend(environ.get(ec.ENV_BACKEND, "")) + if prefer: # "hip-rx9070" is how the feed labels a package; accept it as "the hip family, this variant" - prefer = forced[4:] - environ = {**environ, ec.ENV_BACKEND: "hip"} + environ = {**environ, ec.ENV_BACKEND: family} backend, how = ec.detect_backend(environ) hw = {"platform": host_platform(), "backend": backend, "backend_source": how, "runtime": ec.runtime_version(), "nvidia_driver": None, "cuda_archs": [], "gfx": [], "gpu_names": [], "variant_wanted": prefer, diff --git a/tests/terminal/test_gfx_selection.py b/tests/terminal/test_gfx_selection.py index e02ef41f..451ec42f 100644 --- a/tests/terminal/test_gfx_selection.py +++ b/tests/terminal/test_gfx_selection.py @@ -91,5 +91,46 @@ class Detection(unittest.TestCase): self.assertEqual((got["backend"], got["variant_wanted"]), ("hip", "rx9070")) +class FeedStyleBackendName(unittest.TestCase): + """#4013: `hip-` named the AMD package for `strata update` through STRATA_ENGINE_BACKEND only. As `--backend` it offered nothing, + and `strata launch` stopped with "STRATA_ENGINE_BACKEND='hip-rdna2' is not one of cpu, cuda, hip, metal, sycl".""" + + def test_split_backend(self): + self.assertEqual(ec.split_backend("hip-rdna2"), ("hip", "rdna2")) + self.assertEqual(ec.split_backend(" HIP-RX9070 "), ("hip", "rx9070")) + self.assertEqual(ec.split_backend("hip"), ("hip", "")) + self.assertEqual(ec.split_backend("cuda"), ("cuda", "")) + self.assertEqual(ec.split_backend("hip-"), ("hip-", "")) + self.assertEqual(ec.split_backend("cuda-13"), ("cuda-13", "")) # only the AMD family has package names + self.assertEqual(ec.split_backend(None), ("", "")) + + def test_the_engine_start_takes_the_package_name_as_the_hip_family(self): + self.assertEqual(ec.detect_backend({ec.ENV_BACKEND: "hip-rdna2"}), ("hip", "environment")) + with self.assertRaisesRegex(ec.ComponentProblem, "is not one of"): + ec.detect_backend({ec.ENV_BACKEND: "cuda-13"}) + + def test_update_backend_option_takes_it_too(self): + import argparse + from strata_cli import update_cmd + seen = {} + + class Stop(Exception): + pass + + def context(**kw): + seen.update(kw["hardware"]) + raise Stop + + args = argparse.Namespace(components_dir="C:/nowhere", backend="hip-rdna2", output="json", model_config=None, wait=0, force=False, + app_version=None, check=True, feed=None, no_control=True, yes=True, components_command=None) + base = {"platform": WIN, "backend": "hip", "backend_source": "display adapters", "variant_wanted": ""} + with mock.patch.object(updater, "detect_hardware", return_value=dict(base)), mock.patch.object(updater, "Context", context): + try: + update_cmd.run(args) + except Stop: + pass + self.assertEqual((seen.get("backend"), seen.get("variant_wanted"), seen.get("backend_source")), ("hip", "rdna2", "requested")) + + if __name__ == "__main__": unittest.main() From d98d8f977f9cd00224d6eb8ec1cb1319d032740c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:36:15 +0100 Subject: [PATCH 38/45] docs/TROUBLESHOOTING.md: every entry of v0.2.4.2 is back, updated for 0.2.7 The 0.2.5 rewrite dropped about 25 entries: the Mac quarantine steps, strata doctor, sending logs, the first-start freeze, the graphics memory the app keeps free, Smart App Control, UPDATE.bat and git pull (#1276), the build tools and the gcc/glibc compile problems, the engine checksum, the engine stopped unexpectedly, slower than the tables, the empty-reply and Turing switches, --expert-cache and --resident-budget-gib, the page-locked OOM, the NVIDIA 0x141 reset, CUDA 13.2 on RTX 50, the AMD section (KFD, the build list, 0xC0000005, the driver reset, pinned allocations, verify timeouts) and the body of the verify-timeout entry, which the rewrite had left empty. Each is back with the 0.2.7 facts: the app's reserve defaults (native-resources.mjs), the Drafting setting, --vision on|off|gpu|cpu in the Terminal and --vision no in a source checkout, Intel Arc's CPU reader, and the Terminal route next to the source-checkout one. Every pointer resolves: setup.py's driver-reset pointer, the server's Smart App Control message, DETAILS.md's STRATA_KEEP_EMPTY_TURNS / STRATA_TOPK_STREAM line, OLDER_GPUS.md and MAC.md. tests/terminal/test_troubleshooting_page.py checks the entries, those pointers and the page's own links and anchors. --- docs/TROUBLESHOOTING.md | 319 ++++++++++++++++---- tests/terminal/test_troubleshooting_page.py | 77 +++++ 2 files changed, 332 insertions(+), 64 deletions(-) create mode 100644 tests/terminal/test_troubleshooting_page.py diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 37c97734..23ca9934 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -1,6 +1,6 @@ # Troubleshooting -This page is for anyone whose install or startup fails. Find your symptom below. Each entry gives one fix. +This page is for anyone whose install or startup fails, or whose answers go wrong. Find your symptom below. Each entry gives one fix. Start from the route you installed: [desktop app or Terminal](INSTALL.md), or [source checkout](SOURCE_INSTALL.md). The normal release uses the app or `strata launch` and needs no `.bat` file. Detailed engine errors are in the [engine reference](DETAILS.md#troubleshooting). @@ -25,16 +25,25 @@ startup path for the app. For a fresh desktop install, download the one installe On Windows, open a new PowerShell window after installing. On Linux or Mac, use the full path the installer printed, normally `~/.local/bin/strata`, and add `~/.local/bin` to PATH if needed. Check `strata --version`. -**Strata could not find an engine for this computer.** -Run `strata doctor --live` and `strata update --check`. Check the selected GPU, driver and -[backend guide](INSTALL.md#what-you-need). Supported paths include Apple Silicon and Intel Arc on Linux; do not -assume every machine without an NVIDIA/AMD discrete card is unsupported. A model download can finish even when -no engine starts. Verify `strata launch --status` and `/health` before calling the installation successful. +**A warning says Strata "couldn't find an engine for this computer".** +The engine is the part that talks to your graphics card. Strata only warns and still downloads the model, and the model +files stay on your computer, but the model may not run until the right engine is installed. The usual reasons are that +no engine is installed yet and the update source has none for your card, that the engine found is for another make of +card, or that the graphics driver is too old. In the app, open Settings, then Engine. In the Terminal, the message names +the next step: run `strata update` and start again. Run `strata doctor --live` and `strata update --check` to see the +selected GPU and driver, and check the [backend guide](INSTALL.md#what-you-need). Supported paths include Apple Silicon and +Intel Arc on Linux, so do not assume every machine without an NVIDIA or AMD discrete card is unsupported. If the computer +has no graphics card Strata can use (only an Intel UHD or Iris chip, a virtual machine, or Windows on ARM), Strata says so +and there is nothing to install. Verify `strata launch --status` and `/health` before calling the installation successful. -**This model needs a newer engine.** -Unload running models, then use the app's engine update or `strata update`. Minimum engine versions vary by model and -backend. Check the model guide and the installed engine, not only the app version. If the feed has no compatible engine, -report the missing combination. +**"This model needs a newer engine." (the app), or a button called Update engine.** +Some models need an engine newer than the one installed: Gyro needs 0.1.45.1 or newer, NVFP4 needs 0.1.44, and NVFP4 +(NVIDIA, trained for FP4) needs 0.1.45. Minimum versions vary by model and backend, so check the model guide and the +installed engine, not only the app version. In the app, open Settings, then Engine, and press Update engine. It asks +first, keeps your model files and settings, and wants running models unloaded. In the Terminal: `strata update --check` +says what would change, `strata update` installs it (it switches to the new engine only after a test start). If the engine +you installed is the newest and the message stays, the update source has no newer engine for your card yet; report the +missing combination. **An update says it succeeded but `strata --version` is still old.** The Terminal switches to the updated Control on the next command, so run `strata --version` again. If it is still old, @@ -42,26 +51,58 @@ run the one-line installer once more; it keeps models and settings. The app, Con numbers; see [updating](INSTALL.md#updating) and the [release notes](https://github.com/Niko1221/Strata/releases). **A new engine misbehaves after an update.** -Stop the model, then use the app's rollback control or `strata components rollback`. Source-checkout engines use a -separate rollback workflow, `python setup.py --rollback-engine`, described in [source setup](SOURCE_INSTALL.md). +Stop the model, then use the app's rollback control or `strata components rollback`. An update keeps the engine it +replaced (one generation, about 210 MiB). Source-checkout engines use a separate rollback workflow, in `engine\.previous`: +`python setup.py --rollback-engine` puts the old one back and keeps the newer one there, so run it again to go forward +(#670). It is described in [source setup](SOURCE_INSTALL.md). -**The Mac app cannot be opened.** -Check that the download is for Apple Silicon and that macOS is 15 or newer. Follow -[Mac installation](MAC.md#the-desktop-app-and-strata-launch-on-a-mac). A warning alone does not establish that a file -is safe or intact: verify the download source and release before changing quarantine settings. Release signing and -test-build handling are described in [Mac packaging](../packaging/mac/README.md). +**On a Mac: "Strata is damaged and can't be opened", "cannot be opened", or "unidentified developer".** +Check first that the download is for Apple Silicon and that macOS is 15 or newer ([Mac installation](MAC.md#the-desktop-app-and-strata-launch-on-a-mac)). +Nothing is wrong with the file if the message is only about the developer: macOS marks everything a browser downloads, and +only lets a marked program run if Apple has checked it. Strata's release builds are checked by Apple ("notarised"): drag +Strata onto Applications and open it; the first time, macOS asks "Are you sure you want to open it?" and you press Open. A +test build that is not notarised says "damaged". Do not move it to the Trash. Open the Terminal app and remove the mark, +with the line that matches what you have (drag the file from Finder into the Terminal window to type its path): + + xattr -dr com.apple.quarantine ~/Downloads/ # the .dmg, before opening it + xattr -dr com.apple.quarantine /Applications/Strata.app # the app, after dragging it over + xattr -dr com.apple.quarantine # an unzipped Terminal folder + +Then open it again. If macOS says only "the developer cannot be verified", you can instead try to open it once, then open +System Settings > Privacy & Security and press "Open Anyway" next to the message about Strata. Only remove the mark from a +file you downloaded from the official release; a warning alone does not show that a file is safe or intact. Installs made +with `curl ... | sh` carry no mark and need none of this. To see which kind you have: `spctl -a -vv /Applications/Strata.app` +answers "accepted" and "Notarized Developer ID" for a notarised build. How the builds are signed is in +[Mac packaging](../packaging/mac/README.md). **The Linux AppImage does not open.** Make the downloaded file executable. It may need FUSE 2 (`libfuse2` on Ubuntu 22.04, `libfuse2t64` on newer Ubuntu; package names vary by distribution). Without FUSE, run the file with `--appimage-extract-and-run`. For a crash log, -run it with `--save-logs`; see the logs section below. +run it with `--save-logs`; see [Logs and bug reports](#logs-and-bug-reports). + +**Checking what is installed: `strata doctor`.** +It is a read-only check of the installed engine parts (it changes nothing): which engine and helper files a saved model +needs, and whether they are there. `strata doctor --live` also asks the computer which graphics cards it sees and compares +them with the cards the model is set to use; `--output json` prints the same as data. Put its output into a bug report. ## While installing or starting +**My PC froze, or got very slow, the first time Strata started.** +That is normal while it starts, most of all the first time. Strata loads 35-55 GB into your RAM, locks part of it for the +graphics card, and works out how much of the model fits on your GPU. The mouse can freeze for a few minutes. **Wait, and +don't close the window.** The next starts are much faster. Still frozen after 10 minutes? Restart the PC, close other +programs (browsers use a lot of RAM) and try again. If it keeps happening, pick a smaller size (Q2_0 or IQ2_XS). + **A download stopped.** Retry it in the app, or rerun the same `strata launch` command. Completed model-download steps are reused. Check free space and the error message. For an interrupted Terminal installer, rerun the install command. Only a source -checkout uses `START-HERE.bat` / `./setup.sh` to resume source setup. +checkout uses `START-HERE.bat` / `./setup.sh` to resume source setup; it continues where it stopped. + +**Setup says the engine does not match GitHub's checksum.** +Setup checks the downloaded ready-made engine against the SHA-256 GitHub publishes. On a mismatch the file is corrupt or +was changed on the way, so setup deletes it and stops; run setup again to download it afresh. If GitHub gives no checksum +(offline, rate limited, your own mirror), setup warns and installs anyway. `STRATA_SKIP_SHA256=1` skips the check, only if +you insist. **The engine stops at the start with no line in its log, and the error says `the engine process ended: ...`.** The error names how the system ended the engine process, because the engine log is silent then: for example `killed by signal 4 (SIGILL, Illegal @@ -71,56 +112,202 @@ Report it with the CPU model. **Startup takes a long time or the computer becomes slow.** Large models need time to check files, prepare packs and fill memory. A first launch can take many minutes; there is -no fixed startup time. Watch progress and the engine log. If memory pressure is high, close memory-heavy programs and try a +no fixed startup time. The engine reads 34-55 GB into RAM, and the second start is faster while the files are in the OS +cache. Watch progress and the engine log. If memory pressure is high, close memory-heavy programs and try a smaller model or context. DeepSeek V4.1-Flash needs 46 GB of RAM at least ([model page](MODELS.md#deepseek-v41-flash)); `strata launch --plan --family deepseek41 --model ist-das-2.00bpw` shows what your computer is missing. +Started from Task Scheduler, a start can be 24x slower: see [Running it at startup](DETAILS.md#running-it-at-startup-task-scheduler). +On Linux the engine asks the kernel to read the model files ahead (a cold start went from ~920 s to 70 s on one PC); +`STRATA_READ_AHEAD=0` turns that off. With transparent huge pages on `always`, the arena does not ask for `MADV_HUGEPAGE` +on top (a fragmented machine spent minutes compacting memory, #771); `STRATA_NO_ARENA_THP=1` skips that request on any setting. **The NVIDIA driver is too old.** Use the driver required by the engine package. CUDA 13 needs driver 580 or newer; older cards use the -[CUDA 12 route](OLDER_GPUS.md). After updating the driver and restarting if needed, open the app or rerun -`strata launch`. +[CUDA 12 route](OLDER_GPUS.md). Update it (NVIDIA App or [nvidia.com/drivers](https://www.nvidia.com/drivers)), restart the +PC if needed, then open the app or rerun `strata launch`. **Port 8080 is already in use, or I changed a running model's settings.** -Check `strata launch --status`. To replace your existing launch, rerun the intended command with `--restart`; -it stops current answers. To run beside it, choose another port, for example `--port 8081`, if memory permits. -Do not stop an unrelated program just because it holds the port. `--yes` alone does not restart a running model. +Strata may already be running: check `strata launch --status`. To replace your existing launch, rerun the intended command +with `--restart`; it stops current answers. To run beside it, choose another port, for example `--port 8081`, if memory +permits (source checkout: `START-HERE.bat --port 8081`). Only an address that is really taken says "already in use". Any +other reason (Windows keeps the port reserved, or the config's `"host"` is not an address of this PC) is printed as what +the OS said, with what to change (#769). Do not stop an unrelated program just because it holds the port. `--yes` alone +does not restart a running model. -**The engine stops on a small GPU or low-memory computer.** -Try a smaller pack or context. The draft layer also uses memory. In the app, set the model's Draft layer to Off; -in the Terminal, an explicit example is: +**The engine stops on a small GPU or low-memory computer. Can I turn the draft layer off?** +Yes. The draft layer (MTP) is what makes answers faster, and it takes about 1 GB of graphics memory (plus some RAM and a +memory copy that grows with the context). Without it the expert cache gets that memory back and answers are slower. Turn +it off for one model: in the app, the model's Drafting setting in Expert settings; in the Terminal: ```sh strata launch --family qwen --model q2_0 --context 32k --mtp off ``` -Use `--restart` if replacing an active run. Turning MTP off can slow decoding. Keep some VRAM free for the display; -setting the reserve to zero is not a general speed fix. +(older Terminals: `--set mtp=off --set spec-min-p=off`); by hand, add `"mtp": false` to the model's `strata-.json`. +The choice is kept per model and applied on every start. Use `--restart` if replacing an active run. Also try a smaller +pack or context. Keep some VRAM free for the display; setting the reserve to zero is not a general speed fix. -**Pictures do not work.** -The model, backend and installed engine package must include a compatible picture reader. Inspect the startup -error and the model guide. `--vision off` disables reading pictures; it is different from optional -[image generation](IMAGES.md). In the Terminal, use `on|off|gpu|cpu`, not source setup's `yes|no` spelling. +**I changed `strata-.json` by hand and the change came back.** +Engine options you add to `args` by hand (control vectors, `--spec`, `--vram-reserve-mib 0`, anything the app does not offer) +are kept. The file has two helper keys for this. `user_args` lists your options; every start and every setup run puts them +over the ones the app generates, and for the same option your value wins. `args_written` is a copy of `args` as the app last +wrote it, so an option you added or changed in `args` is noticed and moved into `user_args` the next time the app or setup +touches the file. To undo one, delete it from both `args` and `user_args`. A value you save in the app's Expert settings +("GPU memory for other apps") is put in `user_args` for you. Prefer the app's Expert settings or the Terminal `--set` for +supported overrides. -**Windows blocks an executable.** -Verify the official release and the component named in the message. Feed signatures and Windows code-signing are -different checks. If only the picture reader is blocked, `--vision off` may let text requests run. Do not disable -system-wide protection as the routine installation fix; include the blocked file and exact message in a bug report. +Two things the app still chooses itself: the context size, KV type, picture reading and draft layer. Set them in the Models +screen or with the matching `strata launch` flags, or `"mtp": false` (draft layer). The app keeps the earlier file as +`strata-.json.bak`. Inspect the effective config rather than assuming a saved preference was applied. + +**The app keeps more graphics memory free than I want (decode is slower than in 0.1.45).** +Without a value of yours the app keeps graphics memory free for the desktop: 1536 MiB on a card of 16 GB or less that drives +a display (1024 MiB on a larger card), more with a picture reader on the GPU (2048 MiB), and with the "Leave 20% for my work" +profile a fifth of the card (at most 1536 MiB on a card of 16 GB or less). A card that has no display attached, such as a +second GPU with the screen on the integrated one, keeps 512 MiB (700 MiB with pictures on the GPU). It reads that from the +driver (nvidia-smi `display_active`, or the Windows adapter that has the desktop); when it cannot tell, it assumes a display. +A card that shares the PC's memory (Strix Halo) does not keep a fifth. Your own value is never raised or lowered: set "GPU +memory for other apps" in Expert settings, or `--vram-reserve-mib 0` in `args`. The engine's own warning about low free +memory stays; a card that also draws the desktop can freeze or slow to a few tokens a second with a very small reserve. + +**Pictures are refused, or slow.** +"this server was started without the vision encoder": the model was set up for text only (someone chose "No", or the engine +has no picture reader). Switch pictures on in the app or on the Pictures step of `strata launch` (`--vision on|gpu|cpu`); +in a source checkout run setup again with `--vision yes` (or `--vision gpu` / `--vision cpu`). Pictures are on by default +wherever a model can read them, and `--vision off` (source setup: `--vision no`) turns them off; that is different from +optional [image generation](IMAGES.md). The reader runs on the CPU under 24 GB of graphics memory and on the card from +24 GB, on NVIDIA and AMD cards. Pictures that take several seconds (about 3 s at 300 image tokens on 8 cores, more with more +tokens) are read by the encoder on the CPU; `--vision gpu` (NVIDIA and AMD, ~1.4 GB of VRAM) makes it 0.1-0.5 s. On AMD the +card's reader is `strata-vision-hip`; if it cannot start, the server prints "the GPU picture reader did not start (...); +pictures are read on the CPU" and goes on with the CPU reader. On a Mac the reader runs on the GPU; `--vision cpu` takes +about 50 s per picture there. On Intel Arc the CPU reader is the default. The model, backend and installed engine package +must include a compatible picture reader; inspect the startup error and the model guide. + +**"Windows blocked the Strata engine (or the image encoder) ... Smart App Control".** +On a clean Windows 11, Smart App Control refuses programs that are not signed, and Strata's `strata.exe` and +`strata-vision.exe` are not signed yet (#735). Verify that the file is from the official release and that the message names +a Strata component. The choices are to turn Smart App Control off (Windows Security > App & browser control > Smart App +Control settings; it cannot be turned back on without a reset of Windows) or, if only the image encoder is blocked, to run +without pictures: `strata launch --vision off` (source checkout: `START-HERE.bat --setup --vision no`), which lets text +requests run. Do not disable system-wide protection as a routine fix, and include the blocked file and the exact message in +a bug report. Feed signatures and Windows code signing are different checks. + +**UPDATE.bat / update.sh say "git pull did not succeed", or "has no commit in common" (#1276).** +This is for a source checkout. The repository's history was cleaned up on 2026-10-06, so a clone made before that cannot +be updated with `git pull`. The scripts from 0.1.40.2 handle it: when no tracked file is edited they keep your old commits +in the branch `pre-cleanup-backup` and move the clone to the new history; otherwise they print the two commands for you. +Your models, settings and engine are untracked files and are never touched. An older UPDATE.bat / update.sh (before +0.1.40.2) cannot do this itself: back up local work, run these once in the Strata folder, then use UPDATE.bat as usual +(add `git stash` first if `git status` lists edited files): + + git fetch origin + git branch pre-cleanup-backup + git checkout -B main origin/main + +**Python or the build tools could not be installed.** +Install what it names (links are printed), then run it again. Everything already done is kept. The packaged Terminal +carries Python; a missing system Python is not a reason to install a compiler for the normal release. + +**Linux: the engine does not compile (`unsupported GNU version`, or `exception specification is incompatible` for +`cospi`/`sinpi`/`rsqrt`).** This is for a source build. Two known mismatches between the CUDA toolkit and a new Linux (#601): +- gcc newer than 14 (Ubuntu 26.04's default 15): CUDA 12.x and 13.0 refuse it. Install g++-14 and run + `CXX=g++-14 ./setup.sh` (CC, CXX and CUDAHOSTCXX name the build's compilers; setup passes them to CMake itself, + so an already-configured build folder picks them up too, #1645). +- glibc 2.43 with CUDA 12.9: the toolkit's math headers clash with glibc's, already in CMake's first test compile. + Use CUDA 12.8 or 13.x instead. Setup takes the newest toolkit it finds; `STRATA_NVCC=/usr/local/cuda-12.8/bin/nvcc + ./setup.sh` makes it use that one (only that one). ## While it answers -**It is slow and the disk stays busy.** -The chosen model may exceed available RAM/VRAM and be using the file tier. Close other programs, check memory in -the monitor, and choose a smaller model or context. Compare performance only with the same hardware and workload. +**It is slow and the disk light keeps blinking.** +Your PC is out of free RAM, or the chosen model exceeds the available RAM/VRAM and is using the file tier. Close other +programs, check memory in the monitor, and pick a smaller model or size (Q2_0 or IQ2_XS) or context. Compare performance +only with the same hardware and workload. + +**An answer stopped with "the engine stopped unexpectedly".** +Usually not enough RAM (on Linux the system then stops the engine). Just send your message again: Strata starts the +engine by itself. If it keeps happening, close other programs or pick a smaller size. + +**On Linux the engine stops with "exit code -9", but nothing ran out of RAM.** +Check system logs for an out-of-memory kill first. Then check `ulimit -R`. If it prints 0 (or any number), the desktop +session sets a real-time CPU limit: the audio system (PipeWire) does that when rtkit is not installed, and every program +started from the desktop inherits it. The kernel can then end a program with signal 9 and no message. Install `rtkit`, or +start Strata outside the session's limits, for example `systemd-run --user --collect -p LimitRTTIME=infinity -- strata serve ...`. +Strata prints a warning at start when it sees this limit. **The prompt exceeds the context.** -Start a new chat, shorten the input, or use the app's Summarize and continue action. A larger context needs more -memory. In the Terminal, restart your chosen model with an explicit `--context`, such as `64k`; preserve its family, -model and other choices. Do not look for `SETUP.bat` in an app install. +The conversation is longer than the context you chose. Start a new chat, shorten the input, or use the app's Summarize and +continue action. A larger context needs more memory. In the Terminal, restart your chosen model with an explicit +`--context`, such as `64k`; keep its family, model and other choices. In a source checkout, run `SETUP.bat` and pick more +context. Do not look for `SETUP.bat` in an app install. -**On Linux the engine exits with code -9.** -Check system logs for an out-of-memory kill. Also check `ulimit -R`: a desktop-session real-time limit can cause a -kill even when memory is available. The engine prints a warning for that condition; see the -[detailed troubleshooting table](DETAILS.md#troubleshooting) before changing system limits. +**It is slower than the tables.** +The monitor plugged into the graphics card and other GPU programs take VRAM from the expert cache; RAM running below its +rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. + +**An earlier reply that came back empty is gone from the chat history (0.1.40, #843).** +The server leaves out finished assistant turns that have no text, so the next reply does not copy the empty ones. +`STRATA_KEEP_EMPTY_TURNS=1` in the server's environment renders them as before. + +**A Turing card (RTX 20) reads prompts above ~90K tokens differently (0.1.40, #743).** +The prompt's top-k selection takes a wider kernel there, with the same ids. `STRATA_TOPK_STREAM=0` restores the old one. + +**Decode is several times slower with `--expert-cache N` than with `auto` (#781, #831).** +An explicit N is a byte budget that is not checked against the free VRAM once the slots are written. On a card it +fills (the log says `0 MiB of VRAM free with everything loaded - LOW`), Windows pages the GPU's memory and decode drops +from 100 to 14 tok/s with only a few hundred slots too many. Use `--expert-cache auto`, or a smaller N. + +**A low-RAM PC (about 32 GB) stalls with `--resident-budget-gib N` (#649).** +The budget is pinned (locked) in RAM, which leaves the OS and the CPU workers little room. `STRATA_RESIDENT_PIN=0` keeps +it pageable; a smaller budget works too. + +**Decode got slower in 0.1.40 on a 32 GB PC with `--resident-budget-gib N`, and the drive is read hard (#1194, #1116, #1085).** +The start line "the file tier reads unbuffered" means the experts outside the RAM copy are read straight from the drive. +0.1.40 chose that whenever the free RAM could not hold all of them; but the same few come back token after token, and +a cache a twentieth of their size serves most of the repeats. 0.1.40.2 asks for that much (at least 1.5 GiB beside the +4 GiB headroom) and reads through the cache otherwise, which measured 7% to 118% faster decode with a third to a sixth of +the drive traffic on a 20 to 32 GB box. On 0.1.40 / 0.1.40.1: `STRATA_UNBUFFERED_LOAD=0` does the same, `=1` forces the +unbuffered reads. + +**Linux: the start is OOM-killed while the engine allocates the page-locked expert copy (#1250).** +Page-locked pages come from the driver in one go and cannot wait for the kernel to give back file cache, so with the +model files' cache in the way (little really free RAM, much "available") the host could run out. Since 0.1.40.2 the engine +gives back the cached pages of the model files it mapped before it page-locks the copy; when the really free RAM still +does not cover it, it takes the pages in 1 GiB steps while the RAM available (cgroup limits included) stays above the +headroom, page-locks what it has, and keeps the rest resident but pageable with a warning ("only N of M GiB could be +page-locked"): the answers are the same, only the copies of the pageable part to the GPU go through the CPU. +`STRATA_PIN_GUARD=0` turns this off, `STRATA_PIN_RESERVE_GIB=N` sets the RAM that must stay free (default: +`STRATA_RESIDENT_HEADROOM_GIB`, 4 GiB). + +**The Windows display driver resets, then the PC blue-screens (0x141, then 0x116 in `nvlddmkm`) during an answer (#961).** +This is the NVIDIA driver, not Strata: the report shows the same wedge with other CUDA programs on that driver (610.88, +RTX 4080 SUPER). Try another driver (a Studio one, or an older one) and a lower power limit; if it only happens with +`--spec 4`, `--spec 0` avoids the verify window while you wait for a driver fix (a native (IQ) pack needs `--spec` 2 or +more and cannot turn speculation off). + +**An RTX 50 card (a source build with CUDA 13.2) answers with nonsense, or reads prompts wrongly (#892, #968).** +CUDA 13.2.0 and 13.2.1's compiler (nvcc 13.2.51) miscompile some of the engine's kernels for sm_120: on our RTX 5070 the IQ2_S and IQ3_S +products are wrong (relative error 0.5 to 1.0 in the tests) with 13.2 and right with 13.0. The ready-made engine is built +with 13.0. If you compile it yourself, use CUDA 13.0, 13.1 or 13.2.2 (13.2.2, nvcc build 13.2.86, fixes it; an older one can sit next to a newer: `STRATA_NVCC=`); +setup warns when it finds 13.2.0 or 13.2.1 for such a card, and takes an older 13.x when one is installed. + +## AMD cards + +**"No AMD GPU found (the amdgpu driver's KFD topology is empty)" on Linux.** +The kernel's amdgpu driver is not loaded for the card. Integrated Radeon GPUs are listed as not supported; setup +lists every card it found and whether Strata can use it. + +**The engine stops at start with the card's name, its architecture and the build's list.** +The engine was compiled for another card (for example after moving the Strata folder to another PC). Update the engine +(`strata update`), or in a source checkout run `./setup.sh --setup --backend hip`: it compiles the engine for this card's +architecture. + +**On Windows the engine exits with `0xC0000005` in `amdhip64_7.dll` before it prints anything (#654).** +Two things in your environment can cause it, and the server repairs both before it starts the engine (it says so in +the log): `HIP_PATH`, `HIP_DEVICE_LIB_PATH` or `LLVM_PATH` naming a ROCm folder that no longer exists (a deleted build), +and a `TEMP`/`TMP` folder the engine cannot create files in (AMD's runtime compiles its first kernels through temporary +files). If you start `strata.exe` by hand, fix them yourself: `set HIP_PATH=`, and point `TEMP` and `TMP` at a normal +folder such as `C:\Temp`. **Windows AMD: the driver resets (VIDEO_ENGINE_TIMEOUT_DETECTED / screen flicker / the engine dies mid-answer).** Windows gives a GPU about 2 seconds to answer; when a graphics card does not, it resets the driver (a TDR): the screen @@ -155,28 +342,32 @@ in order, one at a time, and tell us what changed: See [AMD_HIP.md](AMD_HIP.md#model-and-serving-configuration): the mapped expert mode avoids the full pinned arena. **"verify: timed out at layer N" or "no progress for 60 s" on AMD (Linux), mostly with `--mmap-experts`.** - -**A hand-edited engine option disappears.** -The run config tracks explicit options in `user_args` and the generated baseline in `args_written`. Prefer the -app's Expert settings or Terminal `--set` for supported overrides. Context, KV, picture reading and drafting are -launch choices; set them through the app or the corresponding `strata launch` flags. Inspect the effective config -rather than assuming a saved preference was applied. +Two reports fixed it with `"GPU_PINNED_MIN_XFER_SIZE": "1048576"` (RX 6800) or `"HSA_USERPTR_FOR_PAGED_MEM": "0"` (two +R9700) in the `env` block of the server JSON, then a restart. Experimental, one machine each; on a systemd unit use +`MemoryMax`, not `MemoryHigh`. Details: [AMD_HIP.md](AMD_HIP.md#linux-verify-timeouts-while-the-kernel-reclaims-host-memory). ## Source-checkout problems Python/venv, CUDA compiler versions, ROCm builds, `UPDATE.bat`, `update.sh` and generated `run-` scripts -belong to [SOURCE_INSTALL.md](SOURCE_INSTALL.md). Use the backend guide for build prerequisites. The packaged -Terminal carries Python; a missing system Python is not a reason to install a compiler for the normal release. - -If `git pull` fails in an old clone, back up your local work and follow the recovery steps the source update script prints. -Do not overwrite local branches or edits just to make `git pull` succeed. +belong to [SOURCE_INSTALL.md](SOURCE_INSTALL.md); the entries above marked "source checkout" are the common ones. Use the +backend guide for build prerequisites. If `git pull` fails in an old clone, see the `UPDATE.bat` entry above and do not +overwrite local branches or edits just to make `git pull` succeed. ## Logs and bug reports -- **App:** Settings → Engine → Diagnostics → View logs → Save logs. The diagnostic file goes to Downloads. +**Sending logs for a bug report.** +- **App:** Settings → Engine → Diagnostics → View logs → Save logs. It writes one text file, + `strata-diagnostics-.txt`, into your Downloads folder and shows where. It holds the engine's messages, the failed + steps and the end of each model's server log. - **Terminal:** include `strata --version`, `strata doctor --live`, `strata launch --status`, and the relevant log excerpt. -- **Windows app crash:** inspect `%LOCALAPPDATA%\Strata\logs` for `desktop-crash-.log`. -- **Linux app crash:** start the AppImage with `--save-logs` to collect diagnostics. +- **Windows app crash:** if the app closes right after you start it, it shows a message with the reason and writes + `desktop-crash-.log` in `%LOCALAPPDATA%\Strata\logs`; Save logs includes it, and so can you, by hand. +- **Linux app crash:** if the window crashes or will not open, run the AppImage with `--save-logs` in a terminal; it writes + the crash log and the other logs to one file in Downloads. +- **Installer or source checkout:** `strata-.log` from the Strata folder. -Include model and quantization, OS, GPU/VRAM, RAM, driver, install route, exact command, expected result and actual -error. Remove API keys and private data before sharing. Follow [CONTRIBUTING.md](../CONTRIBUTING.md). +Look through a log before you send it, and never send an API key. Include model and quantization, OS, GPU/VRAM, RAM, +driver, install route (app, Terminal or the installer), Strata and engine versions, exact command, expected result and +actual error. Open an [issue](https://github.com/Niko1221/Strata/issues) and attach the log. Follow +[CONTRIBUTING.md](../CONTRIBUTING.md). The full table of error messages, with the older engine fixes, is in the +[details](DETAILS.md#troubleshooting). diff --git a/tests/terminal/test_troubleshooting_page.py b/tests/terminal/test_troubleshooting_page.py new file mode 100644 index 00000000..f6ef6506 --- /dev/null +++ b/tests/terminal/test_troubleshooting_page.py @@ -0,0 +1,77 @@ +"""docs/TROUBLESHOOTING.md keeps every entry the 0.2.5 rewrite lost (restored for 0.2.7), and every pointer to it resolves. + +setup.py and the server print "see docs/TROUBLESHOOTING.md" with an entry's name, DETAILS.md sends readers there for environment variables, and other +pages link to its headings. An entry that disappears turns those pointers into dead ends (the "Windows AMD: the driver resets" entry did, and setup's own +test failed on it). +""" +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +PAGE = ROOT / "docs" / "TROUBLESHOOTING.md" + +# One distinctive phrase from the title of each entry the v0.2.4.2 page had (the page may reword the rest). +ENTRIES = [ + "couldn't find an engine for this computer", "needs a newer engine", "damaged and can't be opened", "strata doctor", "Sending logs for a bug report", + "froze, or got very slow", "app keeps more graphics memory free", "A download stopped", "driver is too old", "Port 8080 is already in use", + "Smart App Control", "new engine misbehaves", "git pull did not succeed", "build tools could not be installed", "does not compile", + "Startup takes a long time", "does not match GitHub's checksum", "It is slow and the disk light", "engine stopped unexpectedly", "exit code -9", + "exceeds the context", "slower than the tables", "came back empty", "Turing card", "--expert-cache N", "--resident-budget-gib N", + "page-locked expert copy", "0x141", "RTX 50 card", "Pictures are refused", "KFD topology is empty", "build's list", "0xC0000005", + "the driver resets", "Large pinned host allocations", "verify: timed out at layer N", +] + + +def slug(heading: str) -> str: + return re.sub(r"[^\w\- ]", "", heading.strip().lower()).replace(" ", "-") + + +def anchors(path: Path) -> set[str]: + return {slug(h) for h in re.findall(r"^#+\s+(.*)$", path.read_text(encoding="utf-8"), re.M)} + + +class TroubleshootingPage(unittest.TestCase): + def setUp(self): + self.text = PAGE.read_text(encoding="utf-8") + self.flat = re.sub(r"\s+", " ", self.text.replace("*", "")) + + def test_every_entry_of_v0_2_4_2_is_on_the_page(self): + for phrase in ENTRIES: + self.assertIn(re.sub(r"\s+", " ", phrase), self.flat, f"the entry about {phrase!r} is missing") + + def test_what_setup_and_the_server_point_to_is_there(self): + setup = (ROOT / "setup.py").read_text(encoding="utf-8") + for name in re.findall(r'docs/TROUBLESHOOTING\.md, \\"([^"\\]+)\\"', setup): + self.assertIn(name, self.text, f"setup.py points to the entry {name!r}") + server = (ROOT / "serve" / "server.py").read_text(encoding="utf-8") + self.assertIn("docs/TROUBLESHOOTING.md", server) + self.assertIn("Smart App Control", self.text) # that pointer is the blocked-executable message + self.assertIn("--vision no", self.text) # which names the way out for a source checkout + + def test_the_variables_that_other_pages_send_here_are_explained(self): + details = (ROOT / "docs" / "DETAILS.md").read_text(encoding="utf-8") + for line in details.splitlines(): + if "TROUBLESHOOTING.md" in line: + for name in re.findall(r"STRATA_[A-Z0-9_]+", line): + self.assertIn(name, self.text, f"DETAILS.md sends readers here for {name}") + + def test_links_into_the_page_and_out_of_it_resolve(self): + own = anchors(PAGE) + for md in sorted((ROOT / "docs").glob("*.md")) + [ROOT / "README.md", ROOT / "SECURITY.md"]: + for target in re.findall(r"\(((?:\.\./)?(?:docs/)?TROUBLESHOOTING\.md#[^)\s]+)\)", md.read_text(encoding="utf-8")): + self.assertIn(target.split("#", 1)[1], own, f"{md.name} links to {target}") + for match in re.finditer(r"\]\(([^)#\s]+)?(#[^)\s]*)?\)", self.text): + name, anchor = match.group(1), match.group(2) + if name and name.startswith("http"): + continue + target = (PAGE.parent / name).resolve() if name else PAGE + self.assertTrue(target.exists(), f"the page links to {name}, which is not there") + if anchor and target.suffix == ".md": + self.assertIn(anchor[1:], anchors(target), f"the page links to {name or ''}{anchor}") + + +if __name__ == "__main__": + unittest.main() From 5f81454038542c8baf4cb3ada2f91a3d25ab1d83 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:39:42 +0100 Subject: [PATCH 39/45] AMD on Windows: the shared-expert fork with KV streaming is not measured, never picked, and warned about when set by hand (#3895) On one Windows RX 6900 XT STRATA_SH_STREAM=1 together with --kv-resident failed the engine on its first request (verify: unspecified launch failure). setup --calibrate (tools/calibrate.py) no longer measures the fork on Windows when KV streaming is on (the fork is off by default on AMD, so nothing changes unless the person sets it), strata tune's never-pick list holds the combination (strata_control/tune_knobs.py), and a config that sets STRATA_SH_STREAM=1 with --kv-resident on Windows HIP gets one warning line when the engine starts (serve/server.py sh_stream_warning). Nothing is refused or removed: the variable still reaches the engine. Shipped without a hardware run, from one report; the reply to #3895 asks RX 6000 owners on Windows to test and report. Tests: tests/terminal/test_sh_stream_windows.py. --- serve/server.py | 17 +++++ strata_control/tune_knobs.py | 3 + tests/terminal/test_sh_stream_windows.py | 97 ++++++++++++++++++++++++ tools/calibrate.py | 16 +++- 4 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 tests/terminal/test_sh_stream_windows.py diff --git a/serve/server.py b/serve/server.py index adf9f552..25202d32 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3531,6 +3531,9 @@ def child_env(cfg: dict, *, offline: bool = False) -> dict: env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else [])) if cfg.get("backend") == "hip": hip_env_guard(env, cfg) + note = sh_stream_warning(env, cfg) + if note: + print(note, flush=True) auto = hip_auto_devices(cfg, env) if auto: env["HIP_VISIBLE_DEVICES"] = ",".join(str(i) for i in auto) @@ -3545,6 +3548,20 @@ def _dir_writable(p: str) -> bool: return False +def sh_stream_warning(env: dict, cfg: dict) -> str | None: + """#3895: the shared-expert fork (STRATA_SH_STREAM=1) together with KV streaming (--kv-resident) made one Windows RX 6900 XT fail on the first + request ("verify: unspecified launch failure"); each alone, or Linux, did not. A warning, not a refusal: the person set the variable, the + engine runs as asked, and the line says what to take out.""" + if os.name != "nt" or str(env.get("STRATA_SH_STREAM", "")).strip() in ("", "0"): + return None + args = [str(a) for a in cfg.get("args") or []] + if "--kv-resident" not in args: + return None + return ("[strata] WARNING: STRATA_SH_STREAM=1 with --kv-resident (KV streaming) failed on the first request on one Windows RX 6000 PC " + "(\"verify: unspecified launch failure\", #3895). If the engine stops that way, take STRATA_SH_STREAM out of the config's env " + "(AMD runs without it by default) or run without --kv-resident, and tell us the card and the driver.") + + def hip_env_guard(env: dict, cfg: dict) -> list[str]: """#654: two things in an AMD user's environment that crash the HIP runtime before it prints a line. (1) HIP_PATH, HIP_DEVICE_LIB_PATH or LLVM_PATH naming a folder that is gone (a ROCm build that was deleted): the bundled runtime diff --git a/strata_control/tune_knobs.py b/strata_control/tune_knobs.py index 54f27f72..0ee3842a 100644 --- a/strata_control/tune_knobs.py +++ b/strata_control/tune_knobs.py @@ -16,6 +16,7 @@ bit-exact run to run). Only ``exact`` is picked on its own; the others need the from __future__ import annotations +import sys from dataclasses import dataclass, field from typing import Any, Callable, Sequence @@ -152,6 +153,7 @@ BOUNDS: dict[str, dict[str, Any]] = { #: in plain words. ``when`` names facts from `condition_holds`; empty = always. NEVER: tuple[dict[str, Any], ...] = ( {"env": "STRATA_SH_STREAM", "when": ("gfx12",), "reason": "it halves decode speed on this graphics card"}, + {"env": "STRATA_SH_STREAM", "when": ("windows_amd_kv_stream",), "reason": "with KV streaming on Windows it made the engine fail on the first request on one RX 6000 PC (#3895)"}, {"env": "STRATA_RDNA2_SGEMM", "value": "all", "when": ("gfx12",), "reason": "it makes long prompts five times slower"}, {"env": "STRATA_SELECT_SIMT", "reason": "its gain is below the 3% margin"}, {"env": "STRATA_HIP_WMMA", "reason": "it changes the numbers (a quality setting)"}, @@ -220,6 +222,7 @@ def condition_holds(name: str, ctx: Context) -> bool: "vram_ge_24g": ctx.vram_mib >= 24000, "vram_le_8g": 0 < ctx.vram_mib <= 8400, "gfx12": bool(ctx.arch and ctx.arch.startswith("gfx12")), + "windows_amd_kv_stream": ctx.backend == "hip" and sys.platform == "win32" and "--kv-resident" in ctx.base_args, "pcie_bound": 0 < ctx.vram_mib < 24000, "ram_bound": bool(ctx.ram_gib and ctx.model_gib and ctx.ram_gib - ctx.model_gib < 30), "ctx_ge_128k": ctx.context_tokens >= 98304, diff --git a/tests/terminal/test_sh_stream_windows.py b/tests/terminal/test_sh_stream_windows.py new file mode 100644 index 00000000..5921710b --- /dev/null +++ b/tests/terminal/test_sh_stream_windows.py @@ -0,0 +1,97 @@ +"""#3895: STRATA_SH_STREAM=1 (the shared expert on its own stream) together with --kv-resident failed the engine on its first request on one +Windows RX 6900 XT ("verify: unspecified launch failure"). AMD runs without the fork by default. Calibrate does not measure the combination, the +tuner never picks it, and a person who set it by hand gets one warning line at the start. Nothing is refused. +""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) +import calibrate as CAL # noqa: E402 +from serve import server # noqa: E402 +from strata_control import tune_knobs # noqa: E402 +from tools.test_calibrate import BASE, FakeEngine # noqa: E402 + + +class CalibrateSkipsTheCombination(unittest.TestCase): + def measure(self, platform, args): + starts, envs, said = [], [], [] + + def start(a, env=None): + envs.append(dict(env or {})) + return FakeEngine(a, lambda f, p, w: 50.0, 6, starts) + + with mock.patch.object(CAL.sys, "platform", platform): + res = CAL.measure(args, [[1, 2, 3]] * 3, start, say=said.append, hip=True) + return res, envs, said + + def test_windows_with_kv_streaming_does_not_measure_the_fork(self): + args = CAL.with_arg(BASE, "--kv-resident", "32768") + res, envs, said = self.measure("win32", args) + self.assertEqual(res["env"], {}) + self.assertNotIn("sh_stream", res["report"]) + self.assertEqual(res["report"]["sh_stream_skipped"], "windows with --kv-resident") + self.assertTrue(all(CAL.SH_STREAM not in e for e in envs)) + self.assertTrue(any("#3895" in line and "STRATA_SH_STREAM=1" in line for line in said)) + + def test_linux_with_kv_streaming_and_windows_without_it_still_measure_it(self): + for platform, args in (("linux", CAL.with_arg(BASE, "--kv-resident", "32768")), ("win32", BASE)): + with self.subTest(platform=platform): + res, envs, _ = self.measure(platform, args) + self.assertEqual(set(res["report"]["sh_stream"]), {"0", "1"}) + self.assertNotIn("sh_stream_skipped", res["report"]) + + +class TunerNeverPicksIt(unittest.TestCase): + def ctx(self, platform, backend="hip", args=("--kv-resident", "32768")): + context = tune_knobs.Context(backend=backend, arch="gfx1030", gpu_count=1, vram_mib=16384, ram_gib=64, model_gib=40.0, base_args=list(args)) + return context, mock.patch.object(tune_knobs.sys, "platform", platform) + + def test_windows_amd_with_kv_streaming(self): + ctx, patch = self.ctx("win32") + with patch: + problems = tune_knobs.check_setting({}, {"STRATA_SH_STREAM": "1"}, ctx) + self.assertEqual(len(problems), 1) + self.assertIn("#3895", problems[0]) + + def test_other_cases_stay_allowed(self): + for platform, backend, args in (("linux", "hip", ("--kv-resident", "32768")), ("win32", "hip", ()), ("win32", "cuda", ("--kv-resident", "32768"))): + ctx, patch = self.ctx(platform, backend, args) + with patch, self.subTest(platform=platform, backend=backend, args=args): + self.assertEqual(tune_knobs.check_setting({}, {"STRATA_SH_STREAM": "1"}, ctx), []) + + +class StartWarning(unittest.TestCase): + CFG = {"backend": "hip", "args": ["--kv", "int8", "--kv-resident", "32768"]} + + def test_a_hand_set_fork_with_kv_streaming_on_windows_warns_once_per_start(self): + with mock.patch.object(server.os, "name", "nt"): + note = server.sh_stream_warning({"STRATA_SH_STREAM": "1"}, self.CFG) + self.assertIn("#3895", note) + self.assertIn("WARNING", note) + self.assertIn("take STRATA_SH_STREAM out", note) + + def test_no_warning_without_the_combination(self): + with mock.patch.object(server.os, "name", "nt"): + self.assertIsNone(server.sh_stream_warning({}, self.CFG)) + self.assertIsNone(server.sh_stream_warning({"STRATA_SH_STREAM": "0"}, self.CFG)) + self.assertIsNone(server.sh_stream_warning({"STRATA_SH_STREAM": "1"}, {"backend": "hip", "args": ["--kv", "int8"]})) + with mock.patch.object(server.os, "name", "posix"): + self.assertIsNone(server.sh_stream_warning({"STRATA_SH_STREAM": "1"}, self.CFG)) + + def test_child_env_prints_it_and_still_passes_the_variable(self): + cfg = {**self.CFG, "env": {"STRATA_SH_STREAM": "1"}} + with mock.patch.object(server.os, "name", "nt"), mock.patch("builtins.print") as shown, \ + mock.patch.object(server, "hip_env_guard", return_value=[]), mock.patch.object(server, "hip_auto_devices", return_value=None): + env = server.child_env(cfg) + self.assertEqual(env["STRATA_SH_STREAM"], "1") # nothing is taken away + self.assertTrue(any("#3895" in str(call.args[0]) for call in shown.call_args_list if call.args)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/calibrate.py b/tools/calibrate.py index 182c5a4d..56819e30 100644 --- a/tools/calibrate.py +++ b/tools/calibrate.py @@ -426,8 +426,14 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke # 6. HIP: the shared-expert stream fork (a restart each), with everything chosen so far. Both values are set # explicitly, so a value the config carried before does not decide the baseline. env = {} - if hip: - tuned = apply(base_args, settings) + tuned = apply(base_args, settings) + if hip and fork_is_unsafe(tuned): + # #3895: one Windows RX 6000 PC faulted the engine on the first request with the fork and KV streaming together. The fork is off by + # default on AMD, so skipping the measurement changes nothing; whoever wants it sets the variable by hand. + say(" Not measuring the shared expert on its own stream: on Windows with KV streaming (--kv-resident) it made the engine fail on the first " + f"request on one PC (#3895). To try it anyway, put {SH_STREAM}=1 in the config's env.") + report["sh_stream_skipped"] = "windows with --kv-resident" + elif hip: by_fork = {} for v in ("0", "1"): _check_cancel(cancel_event) @@ -455,6 +461,12 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke return {"settings": settings, "env": env, "report": report} +def fork_is_unsafe(args) -> bool: + """The shared-expert fork (STRATA_SH_STREAM) with KV streaming on Windows: the one combination that has made an engine fail on its first + request (#3895, an RX 6900 XT). Not measured there; a person can still set the variable.""" + return sys.platform == "win32" and arg_value(args, "--kv-resident") is not None + + def restart(start_engine, args, what, say, report): """#1337: a later step's engine start that fails is a candidate that loses, not a failed run: what the earlier steps measured (and the settings they chose) must survive it. Returns the engine, or None after saying why and From c2490b49f504b9ffdba38916211ff0f6e86d1943 Mon Sep 17 00:00:00 2001 From: Vop3p <69450118+Vop3p@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:39:43 +0100 Subject: [PATCH 40/45] docs/AMD_HIP.md: why STRATA_SH_STREAM goes both ways, and leave it off on Windows with KV streaming (#3895) Two paragraphs from PR #3895 by Vop3p, put under the table row they explain: the fork pays only when it has a CPU-pool wait to hide (4,859 slots on one RX 6900 XT, GPU-reach wait 20.7 of 39.1 ms; with every expert resident it is 43.4 against 62.9 tok/s on an R9700), and the Windows RX 6900 XT fault with the fork plus --kv-resident, its bisection and its limits (one PC, kernel not isolated). The text now says what the code does about it and asks RX 6000 owners on Windows to test. --- docs/AMD_HIP.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index d858002f..612d9c80 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -264,6 +264,26 @@ machine then swaps or stalls, raise it. Re-check after a ROCm update. | `STRATA_DENSE_MMQ=1` | Off | Dense GGUF prompt projections through int8 MMQ kernels instead of dequantize + hipBLAS. Greedy text can diverge after a few dozen tokens (q8_1 rounding). | | `STRATA_HIP_ADAPT_KERNEL_COPY=1` | Off | Adaptive-tier swaps copied by a kernel instead of the SDMA engine; a workaround for a gfx1030 hang with MMQ prompts and adaptive swaps (untested by the reporter) | +**Why `STRATA_SH_STREAM` goes both ways.** The fork has to hide something. With experts on the CPU in the window, the shared expert forks +off only after the doorbell is published (`STRATA_SH_FORK_LATE`, `src/core/verify.cpp`), so it runs while the GPU would otherwise wait for the +CPU pool. On a 16 GB card whose cache holds only part of the experts that wait is about half of a verify window (one RX 6900 XT under Linux, +4,859 slots, `STRATA_DECODE_TIMING=1`: GPU-reach wait 20.7 of 39.1 ms per window), which is where #1272's gain comes from. When every routed +expert is on the GPU there is no wait to fill, and the fork is two cross-stream event dependencies per layer and nothing else: 7fd67dd measured +it on an R9700 with `--resident-experts` and the KV stream path running (48,067-token prompt), 43.4 tok/s with the fork against 62.9 without; +a 256-token prompt barely moved (65.4 and 62.7). Windows adds its own cost to every cross-stream dependency (#816). + +**Windows with KV streaming: leave it off.** On one RX 6900 XT under Windows 11 (the 0.2.3 `rdna2` package, engine 0.1.48, Qwen3.8-Flash-Next +IQ3_S, 64K context, `--kv int8 --kv-resident 32768 --vram-reserve-mib 1536`) the fork together with KV streaming stopped the engine on its first +request ("verify: unspecified launch failure", in other starts first reported by the MTP draft step; exit code 0xC0000409). With the fork off, or +without `--kv-resident`, the same setup answered normally. Removing the other switches one at a time (`STRATA_HIP_PROMPT_F16`, `STRATA_HC_PERSIST`, +`STRATA_HIP_ADAPT_KERNEL_COPY`, `STRATA_PREFILL_CPU_SHARE`, `STRATA_PIPED_CONCURRENT`, `STRATA_PREFILL_STREAM_MIN`, `STRATA_IO_THREADS`, a rocBLAS +table) did not clear it; removing `STRATA_SH_STREAM` did. Two RX 6900 XT under Linux (layer split, the same model, the fork and `--kv-resident +32768`) have served without the fault since 0.1.40. It is one PC and one card, and the faulting kernel was not isolated. So `--calibrate` does +not measure the fork on Windows when KV streaming is on, `strata tune` never picks it there, and a config that sets it by hand gets a warning +line at the start; nothing is refused. If you have an RX 6000 card on Windows and want to help, run it once with `STRATA_SH_STREAM=1` and +`--kv-resident` and tell us in [#3895](https://github.com/Niko1221/Strata/pull/3895) whether the first request answered, with the card and the driver. + + ## Speed switches Switches for the prompt path. A switch you set yourself, to anything, is never overridden by an architecture default. Put From ab48216a7b276645c5fb37821cde2b349039f10b Mon Sep 17 00:00:00 2001 From: Norwin <17587814+NorwinYu@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:40:24 +0100 Subject: [PATCH 41/45] docs/MULTI_GPU.md: say when a layer split pays on a slow CPU (#3930) One bullet from PR #3930 by NorwinYu: on two identical RTX 2080 Ti over a dual-socket Xeon E5-2696 v4 a plain split moved decode from 35.2 to 51.0 tok/s and an 11.6K prompt from 672 to 908 tok/s, because the CPU pool per window fell from 9.52 to 0.79 ms (STRATA_DECODE_TIMING=1). The page's own 5080 + 3090 figures, where the second card is on par, came from a fast CPU; the bullet says so and that it is one measurement. No code changes: setup already splits across two cards. Shipped without a hardware run of ours; the reply asks owners of two older cards on slow CPUs to compare and report. --- docs/MULTI_GPU.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 36b35a81..37bd82aa 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -220,6 +220,14 @@ the Qwen layer split described above. On four Radeon AI PRO R9700 cards it reach An explicit `--expert-cache` on the first card is capped to leave room for them. - More cards pay off when the model's routed experts do not fit the faster ones. An extra slow card costs its own round per window and can make a good pair slower. +- **The split pays most when the CPU pool is the bottleneck.** On two identical RTX 2080 Ti 22 GB over a dual-socket Xeon E5-2696 v4 (AVX2 only, + 88 logical CPUs), a plain split moved decode from 35.2 to 51.0 tok/s (+45%) and an 11.6K-token prompt from 672 to 908 tok/s (+35%) at 180 W, + engine 0.1.49, six 300-token coding prompts. `STRATA_DECODE_TIMING=1` shows why: the window fell from 70.06 to 37.96 ms, almost entirely + because the CPU pool fell from 9.52 to 0.79 ms per window. The 5080 + 3090 measurement below, where decode with the second card is on par + with the 5080 alone, was taken over a fast CPU (Ryzen 9 9950X3D). When the CPU pool is what the window waits on, moving half the layers to a + second identical card removes that work. This is one pair of cards and one CPU, so there is no threshold, and the window breakdown from the + engine log is not the same statistic as the decode numbers beside it. Setup splits across two cards by itself; with two identical older cards + on a slow workstation CPU, compare one card against the split and tell us in [#3930](https://github.com/Niko1221/Strata/pull/3930). - For several conversations at once, `--batch N --batch-groups G --trim-stage-weights` pipelines them through the cards ([BATCHING.md](BATCHING.md)). From 10a62b8d2f500fca3bf8feecf9cf2ff8bb896d9f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:42:58 +0100 Subject: [PATCH 42/45] docker: model files left in the older /data/models stop the start instead of being downloaded again (#3421) A volume or bind mount from the 0.1.x image keeps its models in /data/models. The entry point moves a folder that is part of the volume, but a folder the person mounted there is left alone, and a failed move leaves the files too; with no MODEL_PATH the start then did not see them and downloaded the model again (tens of GB) without a word. Now, when .gguf files are still in /data/models and MODEL_PATH is not set, the container stops with code 2 and names the folder, says what to do (MODEL_PATH to the folder with the shards, or the files into /data/Strata-data/models) and that nothing was downloaded. ALLOW_DOWNLOAD=1 goes on anyway with the same text as a warning. docs/DOCKER.md lists the setting. The other points of the issue (the key, the removed variables, the status loop) are the owner's design questions and are not changed here. Tested by running the guard function with sh (tests/terminal/test_docker_files.py); the whole container was not run (no docker on this PC). --- docker/entrypoint.sh | 13 +++++++ docs/DOCKER.md | 6 ++- tests/terminal/test_docker_files.py | 57 +++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 6b6f87cf..f5476e3a 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -10,6 +10,7 @@ # MODEL model size, e.g. IQ3_XXS, Q2_0 (empty: Strata picks one for this card and says so) # FAMILY model family when a size is offered by several (qwen, swift, coder, ...) # MODEL_PATH GGUF files you already have, a folder or one .gguf, inside the container (mount it read-only) +# ALLOW_DOWNLOAD 1: go on and download the model although model files of the older layout (/data/models) were left unread (default: stop) # CONTEXT 32k, 64k, 128k, 256k or a number of tokens # PARALLEL requests answered at the same time, 1 to 8 (empty: fit to the card) # VISION off | on | gpu | cpu (pictures; the picture reader file is downloaded with the model) @@ -38,6 +39,17 @@ warn() { printf '[!] %s\n' "$*" >&2; } die() { printf '[X] %s\n' "$*" >&2; exit "${2:-1}"; } phase() { printf '%s\n' "$1" > "$PHASE_FILE" 2>/dev/null || true; } +# Model files of the older layout that this image did not move (a folder you mounted at /data/models, or a move that failed) are not read here, and +# the start would download the model again. Say so and stop instead (#3421); ALLOW_DOWNLOAD=1 goes on, with the same text as a warning. +# $1: MODEL_PATH (when it is set the files are named and nothing is lost), $2: the older models folder. +legacy_models_guard() { + [ -n "$1" ] && return 0 + stuck=$(find "$2" -maxdepth 3 -name '*.gguf' 2>/dev/null | head -1) + [ -n "$stuck" ] || return 0 + msg="There are model files in ${stuck%/*} (the older image's place). This image keeps its models in /data/Strata-data/models and does not read them there, so it would download the model again (tens of GB). To use them: mount that folder read-only and set MODEL_PATH to the folder that holds the shards (docs/DOCKER.md, \"Files you already have\"), or put them in /data/Strata-data/models//. To download anyway: set ALLOW_DOWNLOAD=1. Nothing was downloaded." + if [ "${ALLOW_DOWNLOAD:-0}" = "1" ]; then warn "$msg Going on, because ALLOW_DOWNLOAD=1."; else die "$msg" 2; fi +} + # ---- other commands: `docker run image strata ...`, `docker run image sh` if [ "$#" -gt 0 ] && [ "$1" != "run" ] && [ "$1" != "serve" ]; then case "$1" in strata) shift; exec "$STRATA" "$@" ;; *) exec "$@" ;; esac @@ -174,6 +186,7 @@ if [ -n "$model_path" ]; then 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 +legacy_models_guard "$model_path" "${STRATA_LEGACY_MODELS:-/data/models}" [ -n "${MODEL:-}" ] && { set -- "$@" --model "$MODEL"; have=1; } [ -n "${FAMILY:-}" ] && { set -- "$@" --family "$FAMILY"; have=1; } [ -n "$model_path" ] && { set -- "$@" --model-path "$model_path"; have=1; } diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 3ea6f661..d0825fd6 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -115,6 +115,7 @@ screens; leave out what you do not care about. | `MODEL` | model size: `IQ2_XS`, `IQ3_XXS`, `IQ3_S`, `Q2_0`, `UD-Q4_K_XL`, ... ([MODELS.md](MODELS.md)) | Strata picks what suits the card, and says so in the log | | `FAMILY` | `qwen`, `unsloth`, `gyro`, `coder`, `swift`, ...; use `qwen` for the original ISTA-DASLab packs | installer recommendation; may differ by hardware | | `MODEL_PATH` | GGUF files you already have: a folder or one `.gguf`, **inside the container** (mount it with `-v`, `:ro` is fine) | download | +| `ALLOW_DOWNLOAD` | `1`: go on and download the model although model files of the older layout were left unread in `/data/models` (see [From the older image](#from-the-older-image)) | stop | | `CONTEXT` | how much text it remembers at once: `32k`, `64k`, `128k`, `256k` or a number | the largest that fits | | `PARALLEL` | requests answered at the same time, 1 to 8 | fitted to the card | | `VISION` | `off`, `on` (the model reads pictures), `gpu`, `cpu`; the picture-reader file (about 0.9 GB) is downloaded with the model | `off` | @@ -276,7 +277,10 @@ package and start through `strata launch`. Mapping: 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. +is left alone: point `MODEL_PATH` at it. If model files are still in `/data/models` when the container starts (a folder you mounted there, or +a move that failed) and `MODEL_PATH` is not set, the start **stops at once and says where the files are**: it would otherwise download the model +again, tens of GB, because this image does not read that place. Name the folder in `MODEL_PATH`, or set `ALLOW_DOWNLOAD=1` to download anyway. +The container name, the volume and the port can stay as they were. ## Build it yourself diff --git a/tests/terminal/test_docker_files.py b/tests/terminal/test_docker_files.py index 3f2a5520..d146282a 100644 --- a/tests/terminal/test_docker_files.py +++ b/tests/terminal/test_docker_files.py @@ -133,6 +133,63 @@ class Compose(unittest.TestCase): self.assertNotIn("/dev/kfd:/dev/kfd", intel["devices"]) +@unittest.skipIf(SH is None, "needs sh") +class LegacyModelsGuard(unittest.TestCase): + """#3421: model files left in the older image's /data/models (a folder the person mounted there, or a failed move) are not read by this image, + so the start would download the model again. It stops and says where the files are; MODEL_PATH names them, ALLOW_DOWNLOAD=1 goes on.""" + + def run_guard(self, folder, model_path="", allow=None): + import os + import tempfile + entry = (DOCKER / "entrypoint.sh").read_text(encoding="utf-8") + body = entry[entry.index("legacy_models_guard() {"):] + body = body[:body.index("\n}\n") + 3] + with tempfile.TemporaryDirectory() as tmp: + script = Path(tmp) / "guard.sh" + script.write_text("warn() { printf '[!] %s\\n' \"$*\" >&2; }\ndie() { printf '[X] %s\\n' \"$*\" >&2; exit \"${2:-1}\"; }\n" + body + + f"\nlegacy_models_guard '{model_path}' '{sh_path(folder)}'\necho CONTINUED\n", encoding="utf-8", newline="\n") + env = dict(os.environ) + env.pop("ALLOW_DOWNLOAD", None) + if allow is not None: + env["ALLOW_DOWNLOAD"] = allow + return subprocess.run([SH, sh_path(script)], capture_output=True, text=True, env=env) + + def test_files_in_the_older_place_stop_the_start_with_the_folder_named(self): + import tempfile + with tempfile.TemporaryDirectory() as tmp: + shards = Path(tmp) / "IQ3_XXS" + shards.mkdir() + (shards / "model-00001-of-00002.gguf").write_bytes(b"GGUF") + done = self.run_guard(Path(tmp)) + self.assertEqual(done.returncode, 2, done.stdout + done.stderr) + self.assertNotIn("CONTINUED", done.stdout) + self.assertIn(shards.name, done.stderr) + self.assertIn("MODEL_PATH", done.stderr) + self.assertIn("ALLOW_DOWNLOAD=1", done.stderr) + self.assertIn("Nothing was downloaded", done.stderr) + + def test_model_path_allow_download_an_empty_folder_and_a_missing_one_go_on(self): + import tempfile + with tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / "IQ3_XXS").mkdir() + (Path(tmp) / "IQ3_XXS" / "model-00001-of-00002.gguf").write_bytes(b"GGUF") + named = self.run_guard(Path(tmp), model_path="/models") + self.assertEqual((named.returncode, "CONTINUED" in named.stdout), (0, True), named.stderr) + allowed = self.run_guard(Path(tmp), allow="1") + self.assertEqual((allowed.returncode, "CONTINUED" in allowed.stdout), (0, True), allowed.stderr) + self.assertIn("[!]", allowed.stderr) + self.assertIn("ALLOW_DOWNLOAD=1", allowed.stderr) + with tempfile.TemporaryDirectory() as empty: + nothing = self.run_guard(Path(empty)) + self.assertEqual((nothing.returncode, "CONTINUED" in nothing.stdout), (0, True), nothing.stderr) + missing = self.run_guard(Path("/no/such/folder")) + self.assertEqual((missing.returncode, "CONTINUED" in missing.stdout), (0, True), missing.stderr) + + def test_the_entry_point_runs_the_guard_before_any_flag_is_built(self): + entry = (DOCKER / "entrypoint.sh").read_text(encoding="utf-8") + self.assertLess(entry.index('legacy_models_guard "$model_path"'), entry.index('--model "$MODEL"')) + + class Document(unittest.TestCase): def test_every_documented_setting_is_read_by_the_entry_point(self): doc = (ROOT / "docs" / "DOCKER.md").read_text(encoding="utf-8") From 47c98bb23ad8740cd693d56e20be0f92c940fadb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:45:45 +0100 Subject: [PATCH 43/45] strata launch --show-key shows the key of a model setup.py set up (#3570) --show-key only knew a running launch or a preset. A model set up by setup.py (START-HERE.bat, ./setup.sh) keeps its generated key in strata-.json, so the command said there was no key and people read the JSON by hand. With no launch and no --preset, it now looks at the run configs of the installed models: one model with a key prints that key (stdout is the key alone; a hint line with the model and the file goes to stderr), several models ask for --model NAME (any case, the size or the full id), a name that matches nothing says so. --preset never falls back to a setup config, and no key is printed while the choice is open. Tests: tests/terminal/test_launch_show_key_setup.py. --- strata_cli/launch/cmd.py | 48 +++++++++++-- tests/terminal/test_launch_show_key_setup.py | 74 ++++++++++++++++++++ 2 files changed, 117 insertions(+), 5 deletions(-) create mode 100644 tests/terminal/test_launch_show_key_setup.py diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 48cd78ed..ca248829 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -147,7 +147,8 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] m.add_argument("--delete-preset", metavar="NAME", help="delete a saved preset") m.add_argument("--status", action="store_true", help="show what this command is serving now") m.add_argument("--stop", action="store_true", help="stop what this command started (with --preset NAME: that one)") - m.add_argument("--show-key", action="store_true", help="print the API key of --preset NAME (or of the running launch)") + m.add_argument("--show-key", action="store_true", help="print the API key of --preset NAME (or of the running launch); with none of those, the key of a model setup.py set up " + "(--model NAME picks one when several have a key)") c = sp.add_parser( "connect", help="print (or write) the setup for an app that uses the running server", epilog=EXAMPLES, @@ -650,6 +651,31 @@ def launch_info(name: str | None = None) -> dict | None: "port": port, "access": preset.access if preset else None} +def setup_config_keys(wanted: str | None = None) -> list[tuple[str, Path, str]]: + """(model id, config file, API key) for the models setup.py set up (strata-.json in the install folders) that carry a key, #3570. + `wanted` keeps the model whose id is that name or ends with it (coder-iq1_m for IQ1_M); case does not matter.""" + from strata_control import models + try: + listed = models.list_installed().get("models", []) + except Exception: # noqa: BLE001 - a folder that cannot be read has no key to show + return [] + found = [] + for entry in listed: + source = entry.get("source_config") + if not source: + continue + model_id = str(entry.get("id") or Path(source).stem) + if wanted and not (model_id.lower() == wanted.lower() or model_id.lower().endswith(wanted.lower())): + continue + try: + key = str(json.loads(Path(source).read_text(encoding="utf-8-sig")).get("api_key") or "").strip() + except (OSError, ValueError, AttributeError): + continue + if key and key.lower() != "none": + found.append((model_id, Path(source), key)) + return found + + def run_launch(a: argparse.Namespace) -> int: from strata_cli.launch import store from strata_cli.launch.catalog import Catalog, CatalogUnavailable @@ -694,10 +720,22 @@ def run_launch(a: argparse.Namespace) -> int: return 0 if a.show_key: info = launch_info(a.preset) - if not info or not info.get("key"): - return fail("There is no API key for that launch." + ("" if a.preset else " Name a preset with --preset NAME."), 5) - _say(info["key"]) - return 0 + if info and info.get("key"): + _say(info["key"]) + return 0 + if not a.preset: + # not a launch: a model set up by setup.py keeps its key in its own strata-.json (#3570) + found = setup_config_keys(getattr(a, "model", None)) + if len(found) == 1: + _say(found[0][2]) + if not machine: + print(f"(the key of {found[0][0]}, from {found[0][1]})", file=sys.stderr) + return 0 + if len(found) > 1: + return fail("Several models set up by setup.py have an API key: " + ", ".join(f[0] for f in found) + ". Name one with --model NAME.", 5) + if getattr(a, "model", None): + return fail(f"No model set up by setup.py matches '{a.model}' and has an API key, and no launch is running.", 5) + return fail("There is no API key for that launch." + ("" if a.preset else " Name a preset with --preset NAME, or a model set up by setup.py with --model NAME."), 5) try: catalog = Catalog() diff --git a/tests/terminal/test_launch_show_key_setup.py b/tests/terminal/test_launch_show_key_setup.py new file mode 100644 index 00000000..b9efe00a --- /dev/null +++ b/tests/terminal/test_launch_show_key_setup.py @@ -0,0 +1,74 @@ +"""#3570: `strata launch --show-key` printed a key only for a launch (a running one or a preset). A model set up by setup.py keeps its key in +strata-.json, so there the command said "no key" and people read the JSON by hand. It now reads that file when no launch has one.""" +from __future__ import annotations + +import contextlib +import io +import json +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_cli import cli +from strata_cli.launch import cmd as launch_cmd + + +class ShowKeyOfSetupConfigs(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + + def config(self, model_id, key="__none__", **extra): + path = self.root / f"strata-{model_id}.json" + body = {"exe": "x", "args": [], **extra} + if key != "__none__": + body["api_key"] = key + path.write_text(json.dumps(body), encoding="utf-8") + return {"id": model_id, "source_config": str(path)} + + def run_cli(self, entries, *argv, launch=None): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \ + mock.patch.object(launch_cmd, "launch_info", return_value=launch), \ + mock.patch("strata_control.models.list_installed", return_value={"models": entries}): + code = cli.main(["launch", "--show-key", *argv]) + return code, out.getvalue().strip(), err.getvalue() + + def test_the_only_model_with_a_key_is_shown(self): + code, out, err = self.run_cli([self.config("coder-iq1_m", "abc123-secret"), self.config("qwen-q2_0")]) + self.assertEqual((code, out), (0, "abc123-secret")) + self.assertIn("coder-iq1_m", err) # the hint is on stderr: stdout stays the key alone, for scripts + + def test_a_launch_that_has_a_key_comes_first(self): + code, out, _ = self.run_cli([self.config("coder-iq1_m", "from-the-file")], launch={"key": "from-the-launch"}) + self.assertEqual((code, out), (0, "from-the-launch")) + + def test_several_models_need_a_name_and_the_name_picks_one_in_any_case(self): + entries = [self.config("coder-iq1_m", "key-one"), self.config("qwen-iq3_xxs", "key-two")] + code, out, err = self.run_cli(entries) + self.assertEqual(code, 5) + self.assertEqual(out, "") + self.assertIn("coder-iq1_m", err) + self.assertIn("--model NAME", err) + self.assertNotIn("key-one", err + out) # no key is printed while the choice is open + code, out, _ = self.run_cli(entries, "--model", "IQ3_XXS") + self.assertEqual((code, out), (0, "key-two")) + + def test_no_key_anywhere_and_a_name_that_matches_nothing_are_told_plainly(self): + code, out, err = self.run_cli([self.config("qwen-q2_0")]) + self.assertEqual((code, out), (5, "")) + self.assertIn("There is no API key", err) + code, out, err = self.run_cli([self.config("qwen-q2_0", "none")], "--model", "iq1_m") + self.assertEqual(code, 5) + self.assertIn("iq1_m", err) + + def test_a_preset_name_never_falls_back_to_a_setup_config(self): + code, out, err = self.run_cli([self.config("coder-iq1_m", "abc123-secret")], "--preset", "mine") + self.assertEqual((code, out), (5, "")) + self.assertNotIn("abc123", err) + + +if __name__ == "__main__": + unittest.main() From fa128f91e8adf25f225eb3261b194bd1d032fcb6 Mon Sep 17 00:00:00 2001 From: gopinath87607 <85057872+gopinath87607@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:47:22 +0100 Subject: [PATCH 44/45] docs: --prompt-cache-every does not set the size of the pieces a prompt is read in (#3311, #2834) Only the part of PR #3311 by gopinath87607 that is about this engine: a periodic mark is saved at a chunk boundary of the batched prefill and the read carries on (src/program/generate.cpp, periodic_checkpoint), so the interval is not a piece-size dial; what cuts a read into runs is the re-read, the root, a message boundary and the start of the last turn; --prompt-cache-every 0 skips the periodic and the near-tail marks. The wall-time numbers and the comparison with the Maya checkout belong to another engine and are left out. New section in docs/PROMPT_CACHE_TAIL.md, linked from the option's row in docs/DETAILS.md. --- docs/DETAILS.md | 2 +- docs/PROMPT_CACHE_TAIL.md | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 27d0fdf3..0e765106 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -621,7 +621,7 @@ system prompt with a billing header that changes on every request; the server pi | Option | Effect | | --- | --- | | `--prompt-cache N` | Number of checkpoints (`0` = off, which also disables parking). | -| `--prompt-cache-every N`, `--prompt-cache-root N`, `--turn-token ID` | Checkpoint interval, the system-prompt checkpoint (`0` = none) and the turn token. | +| `--prompt-cache-every N`, `--prompt-cache-root N`, `--turn-token ID` | Checkpoint interval, the system-prompt checkpoint (`0` = none) and the turn token. The interval is not a piece-size setting: [what it does](PROMPT_CACHE_TAIL.md#prompt-cache-every-does-not-set-the-size-of-the-pieces-a-prompt-is-read-in). | | `--prompt-cache-spread` (opt-in) | The checkpoint that leaves is the one whose removal leaves the smallest gap, so the kept points thin out geometrically back from the end. An agent that rewrites its history a few thousand tokens back then resumes near the edit instead of at the system prompt. Same RAM. | | `"strata_checkpoint": false` (per request) | A one-shot request that no later request continues saves no checkpoints and keeps no session. | | `"strata_prefix": {"messages": 1}` (per request, opt-in) | One long document, many questions. Marks where the document ends: `{"messages": 1}`, `{"message": 0, "chars": 210000}` or `{"tokens": 12345}`. The checkpoint at the boundary is pinned, so 20 questions cost one read of the document. One pinned prefix at a time per engine; needs `--prompt-cache 3` or more; a malformed field is a 400. See [RESEARCH_RUNS.md](RESEARCH_RUNS.md). | diff --git a/docs/PROMPT_CACHE_TAIL.md b/docs/PROMPT_CACHE_TAIL.md index 836e3b9e..8e1d3cf0 100644 --- a/docs/PROMPT_CACHE_TAIL.md +++ b/docs/PROMPT_CACHE_TAIL.md @@ -31,3 +31,14 @@ This is a separate conservative alternative to the Strata-2080Ti Daily's checkpoint-grid patch. The grid changes chunk boundaries to reach exact checkpoint intervals and failed its local paired numerical gate. This option does not claim that the original grid patch has been fixed or validated. + +## `--prompt-cache-every` does not set the size of the pieces a prompt is read in + +The option can look like a piece-size dial, because a mark every N tokens sounds like a cut every N tokens. In this engine it is not one: a periodic +mark is saved at a chunk boundary of the batched prefill and the read carries on, so no piece ends at it, and changing N does not change how the prompt +is split into runs. What cuts a read into runs is the list of places where a read has to stop and start again: a re-read (`STRATA_CKPT_REREAD`), +the system-prompt root (`--prompt-cache-root`), a message boundary (`STRATA_CACHE_MESSAGE_BOUNDARY`, see +[MESSAGE_BOUNDARY_CACHE.md](MESSAGE_BOUNDARY_CACHE.md)) and the start of the last turn. So the lever for a fresh long read is those cuts, not this cadence. + +What `--prompt-cache-every 0` does: it skips the periodic marks and the near-tail one (`--prompt-cache-tail` needs `--prompt-cache-every` above 0), so a client +that rewrote a turn before the last one mounts a farther mark and reads more of it again. The root mark is controlled by `--prompt-cache-root`. From ee1a6efd5ceab1321b19f974bd06333c0c47684c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 22:20:55 +0100 Subject: [PATCH 45/45] docs/STRIX_HALO_WINDOWS.md: a Strix Halo Windows guide, measured again on 0.2.7 (#3029) Structure from the guide in PR #3029 by HaiYunChuang (what the PC reaches, memory and the BIOS, the configuration, what is on by default, traps), rewritten for the 0.2.7 install and with every number measured again: the Terminal and the gfx1151 engines built from f-027-int2 (3e468f5de), a local signed test feed, strata launch as a standard test user on the NucBox EVO-X2 (Adrenalin 26.10.1), tools/strata_bench.py over a tunnel. Qwen IQ3_S: 44 tok/s chat, prompts 755 / 821 / 792 tok/s at 4K / 16K / 32K. DeepSeek 2.00 bpw: 12 to 14 tok/s chat, prompts 214 to 342 tok/s. An interleaved A/B of STRATA_SH_STREAM on Windows gfx1151 (three pairs): off is 6.9% faster in chat decode, prompts unchanged. What launch chose and logged is quoted instead of a hand-made config. The first guide's tuning rows (engines 0.1.41 to 0.1.47) are not repeated. Co-authored-by: HaiYunChuang <97429634+HaiYunChuang@users.noreply.github.com> --- docs/README.md | 2 +- docs/STRIX_HALO.md | 2 + docs/STRIX_HALO_WINDOWS.md | 125 +++++++++++++++++++++++++++++++++++++ 3 files changed, 128 insertions(+), 1 deletion(-) create mode 100644 docs/STRIX_HALO_WINDOWS.md diff --git a/docs/README.md b/docs/README.md index ed4ebe06..9baad441 100644 --- a/docs/README.md +++ b/docs/README.md @@ -22,7 +22,7 @@ Use the guide for your GPU and operating system. Model and feature support can d | --- | --- | | NVIDIA RTX 20 / 30 / 40 / 50 | [Install](INSTALL.md#what-you-need) | | AMD Radeon (RX and AI PRO R9700) | [AMD / HIP](AMD_HIP.md) | -| AMD Ryzen AI Max / Strix Halo | [Strix Halo](STRIX_HALO.md) | +| AMD Ryzen AI Max / Strix Halo | [Strix Halo](STRIX_HALO.md), [on Windows](STRIX_HALO_WINDOWS.md) | | Intel Arc on Linux | [Intel Arc](INTEL_ARC.md) | | Apple Silicon | [Mac / Metal](MAC.md) | | More than one GPU | [Multiple GPUs](MULTI_GPU.md) | diff --git a/docs/STRIX_HALO.md b/docs/STRIX_HALO.md index e37db19f..72e55c06 100644 --- a/docs/STRIX_HALO.md +++ b/docs/STRIX_HALO.md @@ -32,6 +32,8 @@ change BIOS or kernel settings. The manual Linux toolchain below is for reproduc DeepSeek V4.1-Flash comes with its own engine package on Windows and needs nothing extra: pick the model and the app or `strata launch` downloads it ([DeepSeek on Strix Halo](#deepseek-v41-flash)). +On Windows, [STRIX_HALO_WINDOWS.md](STRIX_HALO_WINDOWS.md) has the speeds measured on 0.2.7 with Qwen IQ3_S and DeepSeek, how memory is used and the traps. + ## DeepSeek V4.1-Flash The model runs through its own engine, `strata-dsv41`, as on the other platforms ([DEEPSEEK41.md](DEEPSEEK41.md)); on Windows the diff --git a/docs/STRIX_HALO_WINDOWS.md b/docs/STRIX_HALO_WINDOWS.md new file mode 100644 index 00000000..3f4fca8b --- /dev/null +++ b/docs/STRIX_HALO_WINDOWS.md @@ -0,0 +1,125 @@ +# Strix Halo (Ryzen AI Max, gfx1151) on Windows: install, what you get, what to know + +This page is for a Windows PC with a Ryzen AI Max "Strix Halo" chip (Radeon 8060S / 8050S, `gfx1151`). It says what Strata does there out +of the box, what speed to expect with Qwen3.8-Flash-Next IQ3_S and with DeepSeek V4.1-Flash, and the traps on this hardware. The Linux +build, the toolchain and the opt-in switches are on [STRIX_HALO.md](STRIX_HALO.md); the DeepSeek details are in +[DEEPSEEK41.md](DEEPSEEK41.md). + +The structure of this page comes from the first Windows guide for this PC, written by HaiYunChuang (pull request #3029). It measured +engines 0.1.41 to 0.1.47 with a hand-made configuration (`--mmap-experts`, a list of switches, a batch file). Since then the app and +`strata launch` have taken over most of that, so this version describes the 0.2.7 install and every number in it was measured again. + +## 1. What this PC reaches + +Measured on 2026-10-26 on a GMKtec NucBox EVO-X2 (Ryzen AI Max+ 395, 128 GB shared memory: a 64 GB BIOS carve-out for the graphics chip +and 64 GB that Windows sees; Windows 11 Pro, AMD Adrenalin 26.10.1 / driver 32.0.32015.7029). Strata was the 0.2.7 release candidate +(Terminal and engine 0.1.51 built from commit `3e468f5de`, ROCm 10.2.0a20260930). The server was started with `strata launch` and +nothing else was set by hand; the speeds come from `tools/strata_bench.py` against the running server (three runs per test, medians, +the engine's own timings; the model is loaded before the clock starts). The numbers can still move before the release is cut. + +**Qwen3.8-Flash-Next IQ3_S** (`strata launch --family qwen --model iq3_s`; 131,072 tokens of context, int8 KV, pictures on): + +| Test | Result | +| --- | --- | +| Short chat, answer speed | **44.0 tok/s** (40.6 to 59.5: code-like answers are faster than prose) | +| Short chat, time to first token | 0.60 s | +| 4K prompt, read speed | **755 tok/s** (first token after 5.4 s) | +| 16K prompt | **821 tok/s** (19.6 s) | +| 32K prompt | **792 tok/s** (40.6 s) | +| Coding-agent session, 6 turns | 69% of the prompt came from the conversation cache; answers 47 tok/s; 4.5 s to the first token per turn | + +**DeepSeek V4.1-Flash 2.00 bpw** (`strata launch --family deepseek41 --model ist-das-2.00bpw`, Faster mode, the drafter on; the 4K row is +the default 8K context, the others 64K context with `--context 64k`): + +| Test | Result | +| --- | --- | +| Short chat, answer speed | **12.1 to 13.6 tok/s** | +| 4K prompt | **214 to 226 tok/s** (about 19 s to the first token) | +| 16K prompt | **326 tok/s** (51 s) | +| 32K prompt | **342 tok/s** (97 s) | +| Coding-agent session, 6 turns | 70% from the conversation cache; answers 14.2 tok/s; 17 to 31 s to the first token per turn | + +These are speed measurements. They say nothing about answer quality, and the short-chat range depends on the text. The DeepSeek 2.25 bpw set +and the other Qwen sizes were not measured for this page. + +## 2. Memory and the BIOS + +- Allocate a **fixed carve-out** to the graphics chip in the BIOS (64 GB on the measured PC). The engine counts the carve-out and the + RAM that Windows sees as one pool and does not change any BIOS or driver setting. +- The graphics chip and the CPU share that pool. For Qwen IQ3_S the engine reads the experts into RAM, keeps them there (it does not + register the arena with the GPU driver on an integrated chip) and gives the expert cache every slot: the start log says + `expert cache auto ... -> 24576 slots` and `expert arena: NOT registered with the GPU driver (integrated GPU, UMA mode)`. The process held + about 49 GB and 10 GB of RAM stayed free. Close other large programs before you load a model this size. +- The default of four parallel slots takes 7.5 GiB of the shared pool for slot sessions (the log says `--batch: 4 slot sessions ... take + 7.54 GiB`). With IQ3_S the cache still held every expert, so there was nothing to gain from fewer slots here; with a bigger model there may be. + +## 3. Install + +1. Use the Windows app (`Strata--windows-x64-setup.exe`) or the Terminal. The engine for this chip is the `windows-x86_64-hip-rdna3` + package; the app or `strata launch` downloads it on the first start, and `strata update` keeps it current. +2. Choose the model in the app, or `strata launch --family qwen --model iq3_s`. With model files you already have, add + `--model-path ` (for IQ3_S the two shards are in one folder: shard 1 is the main model, shard 2 holds the per-layer embedding + table and must stay a separate file). +3. The first start took about 20 minutes on the measured PC with the model files already on disk: the engine package (158 MB), the + check of the 84 GB of model files, the picture reader (0.9 GB), the draft layer (about 5 GB) and the one-time pack. The next start + took under two minutes. + +What `strata launch` wrote for IQ3_S, with no switches of mine (these are the settings to copy if you drive the engine by hand): + +``` +--expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5 --mtp +--max-context 131072 --kv int8 --vision --vram-reserve-mib 700 (backend hip, GPU picture reader) +``` + +and for DeepSeek 2.00 bpw: `--max-context 8192 --dspark auto --dspark-conf 0.65 --prefill-chunk 16384`, with `DS4_ASYNC_T=4` in the +environment and the package's `rocm/bin` folder on the library path. + +## 4. What is on by default + +- On `gfx1151` the engine turns on 19 exact speed switches by itself (the start line lists them; `STRATA_GFX1151_DEFAULTS=0` turns them all + off, and a switch you set is kept). They are the ones that give the same answers as without. `STRATA_HC_Q8=1` is also on here (decode + about 9% faster, near-tie tokens can differ); `STRATA_HC_Q8=0` keeps the old read. +- The hipBLASLt table for `gfx1151` ships in the package and is chosen without a setting (`prefill gemm: hipBLASLt tuning enabled (32 rows, + gfx1151, version 100500)` in the log). A hand-built engine has to be pointed at it: [AMD_HIP.md](AMD_HIP.md). +- `--mmap-experts` is not needed. The first Windows guide found that without it the pinned expert arena used up the graphics memory + budget and decode fell to 28 tok/s on engine 0.1.41; the engine on this page sizes the cache from the shared pool and reaches every slot. +- DeepSeek runs in "Faster" mode here: 5 of 6 experts per word. The app and `strata launch` say so; the quality change is small. + +**`STRATA_SH_STREAM` (the shared expert on its own stream) is on by default on `gfx1151`, and on this Windows PC it is slower.** The first +Windows guide found the same on engine 0.1.41 (+13% decode with it off). Measured again on 0.2.7 with Qwen IQ3_S, three starts each, run +in turn (on, off, on, off, on, off), the same quick suite after every start: + +| Start | `STRATA_SH_STREAM` | Chat decode, median of 9 answers (tok/s) | 4K prompt (tok/s) | +| --- | --- | ---: | ---: | +| 1 | 1 (default) | 43.9 | 742.9 | +| 2 | 0 | 48.3 | 742.9 | +| 3 | 1 | 43.6 | 746.8 | +| 4 | 0 | 46.0 | 740.8 | +| 5 | 1 | 43.2 | 745.5 | +| 6 | 0 | 46.6 | 739.4 | + +With the switch off, decode was **6.9% faster** (46.6 against 43.6, the median of the three starts) and the code-like question 14% faster +(67 against 59 tok/s); all three pairs went the same way. The prompt speed did not change. Setting it takes `strata launch ... --set +STRATA_SH_STREAM=0`; it changes only the order the work runs in, so the answers stay the same. Whether Windows `gfx1151` gets this by +default is a separate decision. This is one model, one PC and short answers; DeepSeek was not tested with it. + + +## 5. Traps + +1. **Keep RAM free.** Qwen IQ3_S held 49 GB of 63.6 GB. A browser with many tabs, or a second model, is enough to push the PC into paging. +2. **Do not run two engines.** One model at a time on this PC; `strata launch --status` shows what is serving, `strata launch --stop` ends it. +3. **The graphics driver.** The 2025-03 driver failed at 32K context for DeepSeek. The measured driver is Adrenalin 26.10.1 (32.0.32015.7029). +4. **If Windows resets the driver** (screen flicker, the engine dies mid-answer), see the driver-reset entry in + [TROUBLESHOOTING.md](TROUBLESHOOTING.md#amd-cards). +5. **Other tuning from the first guide** (a longer `--prefill`, `STRATA_PF_*` switches, `--lookup-chain`): those results are for engines + 0.1.41 to 0.1.47 and a hand-made configuration. They were not repeated here, so they are not part of this page. + +## 6. Reproduce it + +``` +strata launch --family qwen --model iq3_s # then, from a source checkout: +python tools/strata_bench.py --url http://127.0.0.1:8080 --runs 3 --long +``` + +`--long` adds the 32K prompt. For DeepSeek add `--context 64k` to `strata launch` first; the default 8K context skips the 16K prompt and +the agent session.