Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: end an MTPLX tuning relaunch as soon as PM2 says the process died

[._.]/ Adam Eivy7480e0476de6
diff --git a/server/lib/localModelTuning.js b/server/lib/localModelTuning.js
index 538e7475b0..1b331befc6 100644
--- a/server/lib/localModelTuning.js
+++ b/server/lib/localModelTuning.js
@@ -56,15 +56,22 @@
*
* ## Verifying an `mtplx serve` flag before declaring it
*
- * MTPLX's knobs were read off its own `serve` argument parser (upstream
- * `mtplx/cli.py`), not off its feature docs, and every one below was checked to
- * exist unchanged from MTPLX v1.0.0 through v2.9.0 — including the enum SPELLINGS,
- * since argparse rejects an unlisted choice exactly as it rejects an unknown
- * flag. That matters more here than for the other runtimes: `mtplx serve` exits
- * before it binds on a flag it does not recognize, which the LLMs page reports as
- * "the server would not start". Verify the same way (`mtplx serve --help`, or the
- * upstream parser) before adding one, and prefer a flag with a long history over
- * one that appeared in the current release.
+ * This matters more here than for the other runtimes: `mtplx serve` exits before
+ * it binds on a flag it does not recognize, which the LLMs page reports to the
+ * user as "the server would not start". The enum SPELLINGS carry the same risk —
+ * argparse rejects an unlisted `choices` value exactly as it rejects an unknown
+ * flag.
+ *
+ * So each knob below was read off MTPLX's own argument parser rather than its
+ * feature docs, at a spread of releases rather than only the newest, since other
+ * installs upgrade on their own schedule. Reproduce it the same way before
+ * adding one — on a machine with MTPLX, `mtplx serve --help`; otherwise read
+ * upstream `mtplx/cli.py` (github.com/youssofal/MTPLX), where the `serve`
+ * subparser and the `_add_batching_args` / `_add_paged_kv_quant_args` helpers it
+ * calls define these flags, and `mtplx/profiles.py` defines `PROFILE_CHOICES`.
+ * The six below and their options were confirmed present and unchanged at tags
+ * v1.0.0, v2.0.0, v2.5.4 and v2.9.0, with one exception noted on `profile`.
+ * Prefer a flag with that kind of history over one new in the current release.
*
* ## The sentinel contract
*
@@ -171,6 +178,12 @@ const RAW_SPECS = {
{ id: 'generationMode', label: 'Decode mode', type: 'enum', cli: '--generation-mode', options: ['mtp', 'ar'], hint: 'Native multi-token speculative decode, or plain target-only autoregressive. The comparison that answers whether MTP is actually paying off for this model here.' },
{ id: 'kvQuant', label: 'KV cache quantization', type: 'enum', cli: '--kv-quant', options: ['off', 'q8', 'q4'], hint: 'Quantizing the paged KV cache buys context length with a little quality. q4 is the smallest at every length but re-dequantizes each decode step, so long-context decode gets slower.' },
{ id: 'batchingPreset', label: 'Batching preset', type: 'enum', cli: '--batching-preset', options: ['solo', 'latency', 'agent', 'throughput'], hint: 'How the server trades per-request latency against total throughput. `solo` is the cleanest baseline for a single-stream measurement.' },
+ // `turbo` is the one option not present at every tag checked — it arrived in
+ // MTPLX v2.0.0. Offered anyway: an install old enough to reject it gets the
+ // refusal-and-restore path, not a dead daemon, and pinning the catalog to
+ // the oldest release would cost every current install the knob that matters
+ // most. The diagnostic profiles ('exact', 'max-diagnostic') are valid but
+ // are not what a throughput sweep is asking, so they are left out.
{ id: 'profile', label: 'Runtime profile', type: 'enum', cli: '--profile', options: ['sustained', 'turbo', 'performance-cold', 'stable'], hint: 'MTPLX\'s own bundle of runtime settings. `turbo` targets peak rate on the quantized flagships; `sustained` holds up over a long run. Diagnostic profiles are deliberately not offered.' },
],
// PortOS does not start vLLM at all — it is a container from the shipped
diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.js
index afd093e8e9..ee7b6f67ff 100644
--- a/server/services/localModelAssessments.js
+++ b/server/services/localModelAssessments.js
@@ -455,11 +455,24 @@ async function measureModel({ backend, modelId, contexts, tuning, signal, emit }
// tuning PortOS could not apply must not be filed as evidence for that tuning.
const launch = launchTuning(backend, normalizedTuning);
const request = requestBody(backend, normalizedTuning);
- const tuningApplication = Object.keys(launch).length > 0
- ? await applyLaunchTuning({ backend, modelId, launch })
+ let tuningApplication;
+ if (Object.keys(launch).length > 0) {
+ // Announced BEFORE the await, because applying a launch tuning stops and
+ // restarts a daemon — and a cold MLX or GGUF checkpoint can take minutes to
+ // load again. Without this the progress stream is silent for that whole
+ // stretch, on a run the user just started, which reads as a hang.
+ emit({
+ event: 'start',
+ sampleIndex: 0,
+ sampleCount: contexts.length,
+ message: `Restarting ${backend} with ${tuningLabel} before measuring…`,
+ });
+ tuningApplication = await applyLaunchTuning({ backend, modelId, launch });
+ } else {
// `null`, NOT `true`, when nothing was tuned. `true` when the only knobs set
// ride on the request body, which needs no daemon restart to take effect.
- : { applied: Object.keys(request).length > 0 ? true : null, reason: null, config: null };
+ tuningApplication = { applied: Object.keys(request).length > 0 ? true : null, reason: null, config: null };
+ }
const endpoint = isEndpointRuntime(backend) ? await runtimeEndpoint(backend) : null;
if (isEndpointRuntime(backend) && !endpoint) {
diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.js
index d0829849b5..f8e356420c 100644
--- a/server/services/mtplxServerManager.js
+++ b/server/services/mtplxServerManager.js
@@ -138,6 +138,14 @@ function parseTuningFromArgs(list) {
const raw = {};
for (const spec of tuningSpecsFor('mtplx')) {
if (!spec.cli) continue;
+ // `launchArgs` renders a boolean as a BARE flag, so its inverse is presence,
+ // not the next token — reading one would recover the NEXT flag's name as
+ // this knob's value. No MTPLX knob is boolean today; this is here so adding
+ // one cannot silently break re-adoption.
+ if (spec.type === 'boolean') {
+ if (list.includes(spec.cli)) raw[spec.id] = true;
+ continue;
+ }
const value = pm2ArgValue(list, spec.cli);
if (value !== null) raw[spec.id] = value;
}
@@ -151,13 +159,26 @@ async function waitForPortRelease(port) {
}
/**
- * Block until the endpoint answers, or the readiness budget elapses.
- * `false` means it never answered — a wedged process, not a slow-loading one.
+ * Block until the relaunched server answers, or until it is proven dead.
+ *
+ * Polls PM2 alongside the endpoint, because the two failures look identical from
+ * the endpoint alone and cost wildly different amounts of time. `mtplx serve`
+ * accepts a `--context-window` far past what the machine can hold, then dies
+ * partway through loading the checkpoint — well after `startMtplxServer`'s short
+ * startup window has already returned. Waiting the full readiness budget out on
+ * a process PM2 has already marked `errored` would leave the install's `mtplx`
+ * provider down for minutes per bad launch line, and a tuning sweep is EXPECTED
+ * to produce bad launch lines.
+ *
+ * `false` means it will not serve — dead or wedged; either way, restore.
*/
-async function waitForEndpoint(endpoint) {
+async function waitForRelaunchedEndpoint(endpoint) {
const deadline = Date.now() + relaunchReadyTimeoutMs;
while (Date.now() < deadline) {
if (await probeEndpoint(endpoint)) return true;
+ clearJlistCache();
+ const proc = await getAppStatusStrict(MTPLX_APP);
+ if (proc && ['errored', 'stopped', 'not_found'].includes(proc.status)) return false;
await sleep(1000);
}
return false;
@@ -482,15 +503,35 @@ export async function stopMtplxServer() {
* @returns {Promise<{applied: boolean, reason: string|null, config: object|null}>}
*/
export async function relaunchMtplxServerWithTuning(tuning = {}) {
- const knobs = Object.entries(normalizeTuning('mtplx', tuning)).filter(([, v]) => v !== null && v !== undefined);
+ const normalized = normalizeTuning('mtplx', tuning);
+ const knobs = Object.entries(normalized);
if (knobs.length === 0) {
return { applied: false, reason: 'no launch knobs were requested', config: currentConfig };
}
+ // Gated on the RENDERED flags, not the knob count: a knob can normalize to a
+ // value that renders nothing (a boolean set to false — a CLI has no spelling
+ // for "explicitly off"). Relaunching on that would run daemon defaults while
+ // the caller records `tuningApplied: true`, which is the un-applied-but-claimed
+ // reading this whole path exists to prevent.
+ if (launchArgs('mtplx', normalized).length === 0) {
+ return { applied: false, reason: 'that tuning renders no `mtplx serve` flag, so there is nothing to relaunch with', config: currentConfig };
+ }
const status = await getMtplxServerStatus();
if (!status.running) {
return { applied: false, reason: 'MTPLX is not running, so PortOS has no checkpoint to relaunch with', config: null };
}
+ // `null` is "PM2 could not be read", NOT "someone else started it". Collapsing
+ // the two would tell a user their own managed daemon is external — a
+ // misdiagnosis that points them at the wrong fix. Refusing is still right:
+ // PortOS must not stop a process it cannot prove it owns.
+ if (status.managed === null) {
+ return {
+ applied: false,
+ reason: 'PortOS could not read PM2, so it cannot tell whether it owns this MTPLX server',
+ config: status.config || null,
+ };
+ }
if (!status.managed) {
return {
applied: false,
@@ -515,7 +556,7 @@ export async function relaunchMtplxServerWithTuning(tuning = {}) {
// which makes `compareTunings` rank two readings that were not what they say.
// Replacing is exact here because an absent `mtplx serve` flag IS the daemon
// default — the same sentinel contract `lib/localModelTuning.js` documents.
- const next = { ...previous, tuning: Object.fromEntries(knobs) };
+ const next = { ...previous, tuning: normalized };
const port = next.port ?? DEFAULT_PORT;
console.log(`🚄 MTPLX: relaunching to apply tuning (${knobs.map(([k, v]) => `${k}=${v}`).join(', ')})`);
@@ -539,7 +580,7 @@ export async function relaunchMtplxServerWithTuning(tuning = {}) {
// waits only long enough to catch a server that dies immediately, and a cold
// MLX checkpoint takes far longer than that to load. So `online: false` here
// is "not ready YET", not "wedged"; give it the real readiness budget first.
- const ready = started.online || await waitForEndpoint(started.endpoint);
+ const ready = started.online || await waitForRelaunchedEndpoint(started.endpoint);
if (ready) return { applied: true, reason: null, config: started.config };
// Still silent. Treat it exactly like a rejected launch line: put the previous
diff --git a/server/services/mtplxServerManager.test.js b/server/services/mtplxServerManager.test.js
index 36a8cb31f5..360379a24a 100644
--- a/server/services/mtplxServerManager.test.js
+++ b/server/services/mtplxServerManager.test.js
@@ -310,6 +310,46 @@ describe('mtplxServerManager', () => {
expect(pm2State?.status).toBe('online');
});
+ // A launch line MTPLX ACCEPTS but the machine cannot hold dies partway
+ // through loading the checkpoint — after the short startup window has
+ // already returned. Waiting the full readiness budget out on a process PM2
+ // has marked `errored` leaves the install's mtplx provider down for minutes
+ // per bad launch line, and a sweep is expected to produce several.
+ it('restores immediately when PM2 shows the relaunch died, not after the full budget', async () => {
+ await startMtplxServer({ tuning: { depth: 2 } });
+ // Long enough that sitting it out would blow the per-test timeout, so the
+ // assertion is about noticing the death rather than about the clock.
+ _resetMtplxServerStateForTests({ startupWait: 20, startupPoll: 5, relaunchReadyTimeout: 60_000 });
+
+ const realExec = pm2Module.execPm2.getMockImplementation();
+ vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {
+ const out = await realExec(args);
+ // Comes up "online", then dies once the startup wait has already passed.
+ if (args[0] === 'start' && args.includes('--context-window')) {
+ setTimeout(() => { if (pm2State) pm2State.status = 'errored'; }, 30);
+ }
+ return out;
+ });
+
+ const result = await relaunchMtplxServerWithTuning({ contextWindow: 1048576 });
+ expect(result.applied).toBe(false);
+ expect(result.reason).toMatch(/never answered/);
+ expect(result.config.tuning).toEqual({ depth: 2 });
+ });
+
+ it('refuses when PM2 cannot be read, without calling the daemon external', async () => {
+ // `pm2 jlist` fails transiently while MTPLX is still answering: running,
+ // but PortOS cannot prove it owns the process.
+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: true });
+ vi.spyOn(pm2Module, 'getAppStatusStrict').mockResolvedValue(null);
+ const result = await relaunchMtplxServerWithTuning({ depth: 3 });
+ expect(result.applied).toBe(false);
+ expect(result.reason).toMatch(/could not read PM2/);
+ // The misdiagnosis this replaced: telling a user their own managed daemon
+ // was started outside PortOS points them at the wrong fix.
+ expect(result.reason).not.toMatch(/outside PortOS/);
+ });
+
it('refuses when nothing is running, since there is no checkpoint to reuse', async () => {
const result = await relaunchMtplxServerWithTuning({ depth: 3 });
expect(result.applied).toBe(false);