diff --git a/apps/host/scripts/make-guic-locales.py b/apps/host/scripts/make-guic-locales.py
index bf9a89922e..64857e4de2 100644
--- a/apps/host/scripts/make-guic-locales.py
+++ b/apps/host/scripts/make-guic-locales.py
@@ -498,6 +498,27 @@ add(en="Stopped: it reached the helper time limit.",
ko="중지됨: 도우미 시간 제한에 도달했습니다.",
fr="Arrêté : la durée maximale a été atteinte.",
he="נעצר: הגיע למגבלת הזמן של העוזרים.")
+# #1607: the model card's notice when the engine reports that the Windows commit limit (memory plus page file) is close, and its numbers line. English approved by the coordinator 11-17.
+add(en="Windows is close to its memory limit (memory plus page file). Strata may stop without a message. Make the Windows page file larger, or choose a shorter context.",
+ zh="Windows 的内存上限(内存加页面文件)快要用完了。Strata 可能会在没有任何提示的情况下停止。请增大 Windows 页面文件,或选择较短的上下文。",
+ ja="Windows のメモリ上限(メモリとページファイル)に近づいています。Strata がメッセージなしで停止することがあります。Windows のページファイルを大きくするか、コンテキストを短くしてください。",
+ de="Windows nähert sich seiner Speichergrenze (Arbeitsspeicher plus Auslagerungsdatei). Strata kann ohne Meldung stoppen. Vergrößern Sie die Windows-Auslagerungsdatei oder wählen Sie einen kürzeren Kontext.",
+ es="Windows está cerca de su límite de memoria (memoria más archivo de paginación). Strata puede detenerse sin mostrar ningún mensaje. Aumenta el archivo de paginación de Windows o elige un contexto más corto.",
+ ru="Windows близка к пределу памяти (память плюс файл подкачки). Strata может остановиться без сообщения. Увеличьте файл подкачки Windows или выберите более короткий контекст.",
+ pt="O Windows está perto do limite de memória (memória mais arquivo de paginação). O Strata pode parar sem nenhuma mensagem. Aumente o arquivo de paginação do Windows ou escolha um contexto menor.",
+ ko="Windows가 메모리 한도(메모리와 페이지 파일)에 가까워졌습니다. Strata가 메시지 없이 멈출 수 있습니다. Windows 페이지 파일을 늘리거나 더 짧은 컨텍스트를 선택하세요.",
+ fr="Windows approche de sa limite de mémoire (mémoire plus fichier d'échange). Strata peut s'arrêter sans aucun message. Agrandissez le fichier d'échange de Windows ou choisissez un contexte plus court.",
+ he="Windows קרוב למגבלת הזיכרון שלו (זיכרון בתוספת קובץ הדפדוף). ייתכן ש-Strata ייעצר בלי הודעה. הגדילו את קובץ הדפדוף של Windows או בחרו הקשר קצר יותר.")
+add(en="{0} GB of {1} GB are left.",
+ zh="还剩 {0} GB(共 {1} GB)。",
+ ja="{1} GB のうち残りは {0} GB です。",
+ de="Noch {0} GB von {1} GB frei.",
+ es="Quedan {0} GB de {1} GB.",
+ ru="Осталось {0} GB из {1} GB.",
+ pt="Restam {0} GB de {1} GB.",
+ ko="{1} GB 중 {0} GB가 남았습니다.",
+ fr="Il reste {0} GB sur {1} GB.",
+ he="נותרו {0} GB מתוך {1} GB.")
here = APP / "src" / "locales"
NBSP = " "
diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx
index b4d546265f..f8dae280a5 100644
--- a/apps/host/src/components/NativeModels.tsx
+++ b/apps/host/src/components/NativeModels.tsx
@@ -33,6 +33,7 @@ import { useStore } from '../lib/store';
import { NativePresets } from './NativePresets';
import { NativeTune } from './NativeTune';
import { NativeTuneBadge } from './NativeTuneBadge';
+import { commitWarning } from '../lib/commit-warning';
import { nativeCatalogModels, catalogVersionLabel, fetchesPictures, hasKvChoice } from '../lib/native-catalog';
export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine }: {
onOtherModels: () => void;
@@ -92,6 +93,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
// What a running job works on, by its name in the list: "Qwen3.8-Flash-Next · Gyro · Smallest".
const jobLabel = (j: NativeJob) => { const v = allSizes.find(s => s.id === j.model || (s.model === j.model && (!j.family || s.sourceFamily === j.family))); const f = v && families.find(x => x.sizes.includes(v)); return v ? [f?.title, catalogVersionLabel(v)].filter(Boolean).join(' · ') : ''; };
const loadedSelected = native?.instances.find(i => i.model === selectedSize?.id && i.status === 'ready');
+ const loadedCommit = commitWarning(loadedSelected?.metrics?.engine); // #1607: the engine says the Windows commit limit is close
// What the running model was really started with is what the page shows: after Load the highlight must still be the profile that was applied.
useEffect(() => { if (loadedSelected?.resourceProfile)
setResourceProfile(loadedSelected.resourceProfile); }, [loadedSelected?.id, loadedSelected?.resourceProfile]);
@@ -263,6 +265,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
{tr(contextIsTight(fitHardware.vram_gb, context, kv, selectedSize?.context_fit) ?
{tr("This much context takes about {0} GB of graphics memory and leaves little room for the model on this card. Strata will try it; if it does not start, choose a shorter context.", [contextCacheGb(context, kv, selectedSize?.context_fit).toFixed(1)])}
{tr("Windows is close to its memory limit (memory plus page file). Strata may stop without a message. Make the Windows page file larger, or choose a shorter context.")}
{tr("{0} GB of {1} GB are left.", [loadedCommit.left, loadedCommit.limit])}
: null)}> : null)}
diff --git a/apps/host/src/lib/commit-warning.ts b/apps/host/src/lib/commit-warning.ts
new file mode 100644
index 0000000000..0adae8f905
--- /dev/null
+++ b/apps/host/src/lib/commit-warning.ts
@@ -0,0 +1,17 @@
+/**
+ * The engine's Windows commit-limit warning (#1607) as the model card shows it. On Windows the engine compares what a run plans to allocate on the host with the
+ * commit that is left (RAM + page file) and warns when it will not fit: it can end at the limit with no message while RAM is still free. The server reads the
+ * engine's log line and reports the numbers in /metrics `engine.commit_warning` (serve/commit_limit.py); the card says it in plain words with one next step.
+ */
+export interface CommitWarning { left: string; limit: string }
+
+const gb = (value: unknown) => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null);
+
+/** The warning of one running model's /metrics `engine` object, with its numbers as the card shows them (one decimal), or null when the engine did not warn. */
+export function commitWarning(engine: unknown): CommitWarning | null {
+ const w = (engine && typeof engine === 'object' ? (engine as Record).commit_warning : null) as Record | null | undefined;
+ if (!w || typeof w !== 'object') return null;
+ const left = gb(w.left_gib), limit = gb(w.limit_gib);
+ if (left === null || limit === null || limit <= 0) return null;
+ return { left: left.toFixed(1), limit: limit.toFixed(1) };
+}
diff --git a/apps/host/src/locales/guic-de.json b/apps/host/src/locales/guic-de.json
index 53de5f376c..b84d703089 100644
--- a/apps/host/src/locales/guic-de.json
+++ b/apps/host/src/locales/guic-de.json
@@ -44,5 +44,7 @@
"guic43": "1 Stunde",
"guic44": "2 Stunden",
"guic45": "Dieser Helfer arbeitet seit über 30 Minuten.",
- "guic46": "Beendet: Das Zeitlimit für Helfer wurde erreicht."
+ "guic46": "Beendet: Das Zeitlimit für Helfer wurde erreicht.",
+ "guic47": "Windows nähert sich seiner Speichergrenze (Arbeitsspeicher plus Auslagerungsdatei). Strata kann ohne Meldung stoppen. Vergrößern Sie die Windows-Auslagerungsdatei oder wählen Sie einen kürzeren Kontext.",
+ "guic48": "Noch {0} GB von {1} GB frei."
}
diff --git a/apps/host/src/locales/guic-en.json b/apps/host/src/locales/guic-en.json
index fe111427a6..37e12e97de 100644
--- a/apps/host/src/locales/guic-en.json
+++ b/apps/host/src/locales/guic-en.json
@@ -44,5 +44,7 @@
"guic43": "1 hour",
"guic44": "2 hours",
"guic45": "This helper has been working for over 30 minutes.",
- "guic46": "Stopped: it reached the helper time limit."
+ "guic46": "Stopped: it reached the helper time limit.",
+ "guic47": "Windows is close to its memory limit (memory plus page file). Strata may stop without a message. Make the Windows page file larger, or choose a shorter context.",
+ "guic48": "{0} GB of {1} GB are left."
}
diff --git a/apps/host/src/locales/guic-es.json b/apps/host/src/locales/guic-es.json
index 8896a45192..b0847168be 100644
--- a/apps/host/src/locales/guic-es.json
+++ b/apps/host/src/locales/guic-es.json
@@ -44,5 +44,7 @@
"guic43": "1 hora",
"guic44": "2 horas",
"guic45": "Este ayudante lleva más de 30 minutos trabajando.",
- "guic46": "Detenido: alcanzó el límite de tiempo de los ayudantes."
+ "guic46": "Detenido: alcanzó el límite de tiempo de los ayudantes.",
+ "guic47": "Windows está cerca de su límite de memoria (memoria más archivo de paginación). Strata puede detenerse sin mostrar ningún mensaje. Aumenta el archivo de paginación de Windows o elige un contexto más corto.",
+ "guic48": "Quedan {0} GB de {1} GB."
}
diff --git a/apps/host/src/locales/guic-fr.json b/apps/host/src/locales/guic-fr.json
index 23bbe8814e..78bb449c3e 100644
--- a/apps/host/src/locales/guic-fr.json
+++ b/apps/host/src/locales/guic-fr.json
@@ -44,5 +44,7 @@
"guic43": "1 heure",
"guic44": "2 heures",
"guic45": "Cet auxiliaire travaille depuis plus de 30 minutes.",
- "guic46": "Arrêté : la durée maximale a été atteinte."
+ "guic46": "Arrêté : la durée maximale a été atteinte.",
+ "guic47": "Windows approche de sa limite de mémoire (mémoire plus fichier d’échange). Strata peut s’arrêter sans aucun message. Agrandissez le fichier d’échange de Windows ou choisissez un contexte plus court.",
+ "guic48": "Il reste {0} GB sur {1} GB."
}
diff --git a/apps/host/src/locales/guic-he.json b/apps/host/src/locales/guic-he.json
index d43cdfe66a..298f4024b2 100644
--- a/apps/host/src/locales/guic-he.json
+++ b/apps/host/src/locales/guic-he.json
@@ -44,5 +44,7 @@
"guic43": "שעה אחת",
"guic44": "שעתיים",
"guic45": "העוזר הזה עובד כבר יותר מ־30 דקות.",
- "guic46": "נעצר: הגיע למגבלת הזמן של העוזרים."
+ "guic46": "נעצר: הגיע למגבלת הזמן של העוזרים.",
+ "guic47": "Windows קרוב למגבלת הזיכרון שלו (זיכרון בתוספת קובץ הדפדוף). ייתכן ש-Strata ייעצר בלי הודעה. הגדילו את קובץ הדפדוף של Windows או בחרו הקשר קצר יותר.",
+ "guic48": "נותרו {0} GB מתוך {1} GB."
}
diff --git a/apps/host/src/locales/guic-ja.json b/apps/host/src/locales/guic-ja.json
index 66357e6914..10a06018cc 100644
--- a/apps/host/src/locales/guic-ja.json
+++ b/apps/host/src/locales/guic-ja.json
@@ -44,5 +44,7 @@
"guic43": "1時間",
"guic44": "2時間",
"guic45": "このヘルパーは30分以上作業しています。",
- "guic46": "停止しました:ヘルパーの時間制限に達しました。"
+ "guic46": "停止しました:ヘルパーの時間制限に達しました。",
+ "guic47": "Windows のメモリ上限(メモリとページファイル)に近づいています。Strata がメッセージなしで停止することがあります。Windows のページファイルを大きくするか、コンテキストを短くしてください。",
+ "guic48": "{1} GB のうち残りは {0} GB です。"
}
diff --git a/apps/host/src/locales/guic-ko.json b/apps/host/src/locales/guic-ko.json
index 043a3f1212..2fb72e6a99 100644
--- a/apps/host/src/locales/guic-ko.json
+++ b/apps/host/src/locales/guic-ko.json
@@ -44,5 +44,7 @@
"guic43": "1시간",
"guic44": "2시간",
"guic45": "이 도우미가 30분 넘게 작업하고 있습니다.",
- "guic46": "중지됨: 도우미 시간 제한에 도달했습니다."
+ "guic46": "중지됨: 도우미 시간 제한에 도달했습니다.",
+ "guic47": "Windows가 메모리 한도(메모리와 페이지 파일)에 가까워졌습니다. Strata가 메시지 없이 멈출 수 있습니다. Windows 페이지 파일을 늘리거나 더 짧은 컨텍스트를 선택하세요.",
+ "guic48": "{1} GB 중 {0} GB가 남았습니다."
}
diff --git a/apps/host/src/locales/guic-pt.json b/apps/host/src/locales/guic-pt.json
index b1c3b4ba42..3df03e7a40 100644
--- a/apps/host/src/locales/guic-pt.json
+++ b/apps/host/src/locales/guic-pt.json
@@ -44,5 +44,7 @@
"guic43": "1 hora",
"guic44": "2 horas",
"guic45": "Este ajudante está trabalhando há mais de 30 minutos.",
- "guic46": "Interrompido: atingiu o limite de tempo dos ajudantes."
+ "guic46": "Interrompido: atingiu o limite de tempo dos ajudantes.",
+ "guic47": "O Windows está perto do limite de memória (memória mais arquivo de paginação). O Strata pode parar sem nenhuma mensagem. Aumente o arquivo de paginação do Windows ou escolha um contexto menor.",
+ "guic48": "Restam {0} GB de {1} GB."
}
diff --git a/apps/host/src/locales/guic-ru.json b/apps/host/src/locales/guic-ru.json
index dbd51b7879..5558b4787f 100644
--- a/apps/host/src/locales/guic-ru.json
+++ b/apps/host/src/locales/guic-ru.json
@@ -44,5 +44,7 @@
"guic43": "1 час",
"guic44": "2 часа",
"guic45": "Этот помощник работает уже больше 30 минут.",
- "guic46": "Остановлен: достигнут лимит времени помощников."
+ "guic46": "Остановлен: достигнут лимит времени помощников.",
+ "guic47": "Windows близка к пределу памяти (память плюс файл подкачки). Strata может остановиться без сообщения. Увеличьте файл подкачки Windows или выберите более короткий контекст.",
+ "guic48": "Осталось {0} GB из {1} GB."
}
diff --git a/apps/host/src/locales/guic-zh.json b/apps/host/src/locales/guic-zh.json
index d6ba8de0e7..84f797b95b 100644
--- a/apps/host/src/locales/guic-zh.json
+++ b/apps/host/src/locales/guic-zh.json
@@ -44,5 +44,7 @@
"guic43": "1 小时",
"guic44": "2 小时",
"guic45": "这个助手已经工作超过 30 分钟。",
- "guic46": "已停止:已达到助手时间限制。"
+ "guic46": "已停止:已达到助手时间限制。",
+ "guic47": "Windows 的内存上限(内存加页面文件)快要用完了。Strata 可能会在没有任何提示的情况下停止。请增大 Windows 页面文件,或选择较短的上下文。",
+ "guic48": "还剩 {0} GB(共 {1} GB)。"
}
diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css
index 59c1e5c573..d04464f62b 100644
--- a/apps/host/src/styles/app.css
+++ b/apps/host/src/styles/app.css
@@ -7683,3 +7683,8 @@ button.sent-quote__label { text-decoration: underline; text-underline-offset: 2p
(the default) is the 56ch above and needs no rule. */
:root[data-measure='wide'] { --st-measure: 72ch; }
:root[data-measure='full'] { --st-measure: 400ch; }
+
+/* The model card's notice that the engine says the Windows commit limit is close (#1607): the sentence with its warning sign, and the numbers under it. */
+.native-commit-note { display: flex; flex-direction: column; gap: 2px; margin: 6px 0; }
+.native-commit-note p { margin: 0; display: flex; gap: 6px; align-items: flex-start; }
+.native-commit-note .st-icon { flex: none; margin-top: 2px; }
diff --git a/apps/host/tests/commit-warning.test.mjs b/apps/host/tests/commit-warning.test.mjs
new file mode 100644
index 0000000000..de4450cfc2
--- /dev/null
+++ b/apps/host/tests/commit-warning.test.mjs
@@ -0,0 +1,42 @@
+// #1607: on Windows the engine warns (in its log) that the commit limit (memory plus page file) is close and it may stop without a message. serve/commit_limit.py puts the
+// numbers in /metrics engine.commit_warning; the loaded model's card says it in plain words with one next step.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { transform } from 'esbuild';
+
+const src = name => readFileSync(new URL(`../src/${name}`, import.meta.url), 'utf8').replace(/\r\n/g, '\n');
+const { code } = await transform(src('lib/commit-warning.ts'), { loader: 'ts', format: 'esm' });
+const { commitWarning } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
+const LANGS = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr', 'he'];
+const NOTICE = 'Windows is close to its memory limit (memory plus page file). Strata may stop without a message. Make the Windows page file larger, or choose a shorter context.';
+const LEFT = '{0} GB of {1} GB are left.';
+
+test('the card reads the engine\'s warning from /metrics engine.commit_warning, with one decimal; no warning, no notice', () => {
+ assert.deepEqual(commitWarning({ commit_warning: { limit_gib: 92.8, left_gib: 0.8, planned_gib: 2, floor_gib: 4 } }), { left: '0.8', limit: '92.8' });
+ assert.deepEqual(commitWarning({ commit_warning: { limit_gib: 31.94, left_gib: 1.46 } }), { left: '1.5', limit: '31.9' });
+ for (const engine of [undefined, null, {}, { commit_warning: null }, { commit_warning: {} }, { commit_warning: { limit_gib: 0, left_gib: 0 } },
+ { commit_warning: { limit_gib: 'x', left_gib: 1 } }, { commit_warning: { limit_gib: 10, left_gib: -1 } }, { commit_warning: 5 }, 'text', 7])
+ assert.equal(commitWarning(engine), null, JSON.stringify(engine));
+});
+
+test('the model card shows the notice for the loaded model only, with the numbers line', () => {
+ const card = src('components/NativeModels.tsx');
+ assert.match(card, /import \{ commitWarning \} from '\.\.\/lib\/commit-warning';/);
+ assert.ok(card.includes('const loadedCommit = commitWarning(loadedSelected?.metrics?.engine);'));
+ assert.ok(card.includes(`{tr(loadedCommit ?
: null)}`));
+});
+
+test('both texts are in the catalog in all ten languages with the language rules', () => {
+ const cat = Object.fromEntries(LANGS.map(l => [l, JSON.parse(readFileSync(new URL(`../src/locales/guic-${l}.json`, import.meta.url), 'utf8'))]));
+ for (const text of [NOTICE, LEFT]) {
+ const key = Object.keys(cat.en).find(k => cat.en[k] === text);
+ assert.ok(key, `${text} is in guic-en.json`);
+ for (const l of LANGS) assert.ok(cat[l][key] && cat[l][key].trim(), `${l}: ${key}`);
+ assert.equal(/[^ ][;:?!]| [;:?!]/.test(cat.fr[key]), false, 'French: ; : ? ! only after a no-break space');
+ }
+ const left = Object.keys(cat.en).find(k => cat.en[k] === LEFT);
+ for (const l of LANGS) assert.ok(cat[l][left].includes('{0}') && cat[l][left].includes('{1}'), `${l} keeps both numbers`);
+ const notice = Object.keys(cat.en).find(k => cat.en[k] === NOTICE);
+ assert.match(cat.de[notice], /Vergrößern Sie/, 'German uses Sie');
+});
diff --git a/serve/commit_limit.py b/serve/commit_limit.py
new file mode 100644
index 0000000000..86a0d0bc1f
--- /dev/null
+++ b/serve/commit_limit.py
@@ -0,0 +1,29 @@
+"""serve/commit_limit.py - the engine's Windows commit-limit warning (#1607), as a fact the Monitor and the app can read.
+
+On Windows the engine compares what a run plans to allocate on the host with the commit that is left (RAM + page file) and, when it will not fit, writes one line
+to its log: "strata serve: WARNING the Windows commit limit is 92.8 GiB (RAM + page file) and 0.8 GiB of it is left, but this run plans 2.0 GiB of host
+allocations and keeps 4.0 GiB free: it can end at the limit with no message (exit code 0xC0000409, #1607) while RAM is still free. ..." The engine has no
+structured field for it (0.2.17: give it one), so the server reads the line from this start's log and puts the numbers in engine.info["commit_warning"], which /metrics
+carries in `engine` like the other INFO facts. The pattern is pinned to the engine's own text by the unit test (serve/test_commit_limit.py).
+"""
+from __future__ import annotations
+
+import re
+
+_LINE = re.compile(
+ r"WARNING the Windows commit limit is (?P[0-9]+(?:\.[0-9]+)?) GiB \(RAM \+ page file\) and (?P[0-9]+(?:\.[0-9]+)?) GiB of it is left, "
+ r"but this run plans (?P[0-9]+(?:\.[0-9]+)?) GiB of host allocations and keeps (?P[0-9]+(?:\.[0-9]+)?) GiB free")
+
+
+def commit_warning(log_text: str) -> dict | None:
+ """The numbers of the engine's commit-limit warning in this start's log text (the last such line), or None when there is none:
+ {"limit_gib", "left_gib", "planned_gib", "floor_gib"}."""
+ found = None
+ for line in (log_text or "").splitlines():
+ m = _LINE.search(line)
+ if m:
+ found = m
+ if found is None:
+ return None
+ return {"limit_gib": float(found.group("limit")), "left_gib": float(found.group("left")),
+ "planned_gib": float(found.group("planned")), "floor_gib": float(found.group("floor"))}
diff --git a/serve/server.py b/serve/server.py
index f99b8be061..a431a22a88 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -69,6 +69,7 @@ from serve.frontend import (CALL_END, CALL_START, FUNC_END, FUNC_START, THINK_EN
from serve.mcp import McpCancelled, hub_from_config, resolve_image_results # noqa: E402
from serve import runconfig # noqa: E402
from serve import expert_heat # noqa: E402
+from serve import commit_limit # noqa: E402
from serve.webfiles import subtree_file as web_subtree_file # noqa: E402
from strata_control import engine_component # noqa: E402
from strata_control import tls # noqa: E402
@@ -1375,6 +1376,13 @@ class StrataEngine:
if self.info.get("engine"):
self.info["version"] = str(self.info["engine"])
self.terminal_stages = read_engine_stage_log(log, log_start) if log else []
+ self.info.pop("commit_warning", None) # this start only: a restart that no longer warns clears it
+ try: # #1607: the engine's Windows commit-limit warning, for the Monitor and the app
+ warned = commit_limit.commit_warning(start_log_text(log, log_start)) if log else None
+ if warned:
+ self.info["commit_warning"] = warned
+ except Exception: # noqa: BLE001 - a note must never stop a start
+ pass
try: # which drafter runs, and in plain words why not the one that was asked for
self.info.update(drafting.engine_info(args, start_log_text(log, log_start), drafting.take_note()))
except Exception: # noqa: BLE001 - a note must never stop a start
diff --git a/serve/test_commit_limit.py b/serve/test_commit_limit.py
new file mode 100644
index 0000000000..d45b791e1b
--- /dev/null
+++ b/serve/test_commit_limit.py
@@ -0,0 +1,94 @@
+"""The engine's Windows commit-limit warning (#1607) becomes engine.info["commit_warning"]. The pattern is pinned to the engine's own text: the first line below is
+the one a Strix Halo start wrote (par/soak1117/evidence/engine-log-1304.txt, line 58), the second is what include/strata/platform/host_limits.hpp prints for other numbers."""
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+from serve import commit_limit
+from serve.server import StrataEngine
+
+SOAK_LINE = ("strata serve: WARNING the Windows commit limit is 92.8 GiB (RAM + page file) and 0.8 GiB of it is left, but this run plans 2.0 GiB of host allocations "
+ "and keeps 4.0 GiB free: it can end at the limit with no message (exit code 0xC0000409, #1607) while RAM is still free. Raise the page file (System managed, "
+ "or RAM-sized) or lower --conversation-cache-mib / --max-context / --prefill")
+OTHER_LINE = SOAK_LINE.replace("92.8", "31.9").replace("0.8 GiB", "1.5 GiB").replace("plans 2.0", "plans 18.0")
+INFO_LINE = "strata serve: Windows commit: 0.8 GiB left of a 92.8 GiB limit (RAM + page file)"
+
+
+class CommitWarning(unittest.TestCase):
+ def test_the_engines_line_gives_its_numbers(self):
+ log = "strata generate: PCIe probe\n" + INFO_LINE + "\n" + SOAK_LINE + "\nstrata serve: every expert is in the GPU cache\n"
+ self.assertEqual(commit_limit.commit_warning(log), {"limit_gib": 92.8, "left_gib": 0.8, "planned_gib": 2.0, "floor_gib": 4.0})
+
+ def test_the_last_warning_of_the_log_wins_and_other_numbers_read(self):
+ got = commit_limit.commit_warning(SOAK_LINE + "\n" + OTHER_LINE + "\n")
+ self.assertEqual(got, {"limit_gib": 31.9, "left_gib": 1.5, "planned_gib": 18.0, "floor_gib": 4.0})
+
+ def test_no_warning_no_fact(self):
+ for text in ("", None, INFO_LINE + "\n", "strata serve: ready\n", "WARNING the Windows commit limit is soon\n"):
+ self.assertIsNone(commit_limit.commit_warning(text), repr(text))
+
+ def test_the_pattern_follows_the_engines_format_string(self):
+ # host_limits.hpp builds the text from these pieces: if the engine's words change, this fails here instead of the notice silently never showing
+ header = Path(__file__).resolve().parents[1] / "include" / "strata" / "platform" / "host_limits.hpp"
+ if not header.exists():
+ self.skipTest("the engine headers are not in this checkout")
+ source = header.read_text(encoding="utf-8")
+ for piece in ("WARNING the Windows commit limit is %.1f GiB (RAM + page file) and %.1f GiB of it is left, but this run ",
+ "plans %.1f GiB of host allocations and keeps %.1f GiB free: it can end at the limit with no message "):
+ self.assertIn(piece, source)
+
+ def test_the_server_applies_it_once_per_start_and_clears_it(self):
+ source = (Path(__file__).resolve().parent / "server.py").read_text(encoding="utf-8")
+ self.assertIn('self.info.pop("commit_warning", None)', source)
+ self.assertIn("commit_limit.commit_warning(start_log_text(log, log_start))", source)
+ self.assertIn('self.info["commit_warning"] = warned', source)
+
+
+FAKE = r"""
+import sys
+args = sys.argv[1:]
+sys.stderr.write('strata serve: Windows commit: 0.8 GiB left of a 92.8 GiB limit (RAM + page file)' + chr(10))
+if '--warn' in args:
+ sys.stderr.write(WARNING + chr(10))
+sys.stderr.flush()
+print('READY 4096 stop', flush=True)
+for line in sys.stdin:
+ if line.startswith('QUIT'):
+ break
+"""
+
+
+class RealEngineStart(unittest.TestCase):
+ """A real process and a real pipe (a fake engine program that writes the engine's own line to its stderr, which is the log), like serve/test_drafting_retry.py."""
+
+ def make(self, *extra):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ root = Path(tmp.name)
+ py = root / "native.py"
+ source = "WARNING = " + repr(SOAK_LINE.split("strata serve: ", 1)[1]) + chr(10) + FAKE
+ if os.name == "nt":
+ py.write_text(source)
+ script = root / "native.cmd"
+ script.write_text(f'@"{sys.executable}" "{py}" %*\r\n')
+ else:
+ script = py
+ py.write_text("#!" + sys.executable + chr(10) + source)
+ py.chmod(0o700)
+ engine = StrataEngine(str(script), ["--pack", "/d/packs/g", *extra], log=str(root / "engine.log"))
+ self.addCleanup(engine.close)
+ return engine
+
+ def test_a_start_whose_log_has_the_warning_reports_it_in_the_engine_facts(self):
+ engine = self.make("--warn")
+ self.assertEqual(engine.info["commit_warning"], {"limit_gib": 92.8, "left_gib": 0.8, "planned_gib": 2.0, "floor_gib": 4.0})
+
+ def test_a_start_without_the_warning_reports_none(self):
+ engine = self.make()
+ self.assertNotIn("commit_warning", engine.info)
+
+
+if __name__ == "__main__":
+ unittest.main()