Host: a failed save of the native job history no longer stops inference or polling (#5802, #5744)

emit() wrote native-jobs.json synchronously without a guard, and poll() had only a
finally: a full disk or a locked file (ENOSPC, EACCES, a failed rename) threw out of
every state change and could leave the model looking stopped. native-job-store.mjs
writes to a unique temporary file beside the destination and renames it (the last
good JSON stays readable), keeps the newest state in memory, retries after 250 ms,
1 s, 3 s and then waits 30 s, skips unchanged saves, warns at most once a minute,
says when it recovered, and makes one last save at close. poll() catches its own
failures and polls again.
Tests (contributor's): native-job-store.test.mjs: 2 fail on 70667dd72, 7/7 pass.
This commit is contained in:
likenparklioo authored and Niko1221 committed 2026-11-16 14:54:31 +01:00
1 parent 70667dd72a
commit e19adee7e6
3 files changed
+179 -3

No files matched your search

+5 -3
View File
@@ -1,5 +1,6 @@
/** Native Strata control plane. All user actions are explicit; opening the UI only reads state. */
import {missingFilesError,missingNames} from './missing-files.mjs';
import { createJobStore } from './native-job-store.mjs';
import { spawn } from 'node:child_process';
import {chooseParallel,applyParallel,withoutParallel,FALLBACK_NOTE} from './native-parallel.mjs';
import { randomBytes, randomUUID, createHash } from 'node:crypto';
@@ -81,7 +82,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
let defaultId=null,timer=null,closing=false,polling=false;
/* Models the engine update stopped (with the person's yes): kept so the app can offer to start them again with the same settings. */
let stoppedForUpdate=null;
const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);};
const jobStore=createJobStore(join(directory,'native-jobs.json'));
const emit=()=>{const value=state();jobStore.save(value.jobs);changed(value);};
const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();};
function diskSpace(path){try{const s=statfsSync(path);return {free:Number(s.bavail)*Number(s.bsize),total:Number(s.blocks)*Number(s.bsize)};}catch{return null;}}
/* Does the engine in this release serve DFlash2? Control knows (strata_control/drafting.py); asked once, false until it answers. The Models screen offers the choice only when true. */
@@ -580,7 +582,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}
let pollCount=0;
/* The engine's metrics carry every finished request with `?requests=all`: a long session makes that a large JSON that the host parses and
pushes to the window every 2 s. The last dozen is what the app shows live; the full list is refreshed every tenth poll. */
async function poll(){if(polling||closing)return;polling=true;const full=pollCount++%10===0;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics${full?'?requests=all':''}`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');const fresh=await response.json();const older=instance.metrics?.requests,recent=fresh.requests;instance.metrics=full||!Array.isArray(older)||!Array.isArray(recent)||!recent.length?fresh:{...fresh,requests:[...recent,...older.filter(r=>Number(r.time)<Math.min(...recent.map(x=>Number(x.time))))]};const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';instance.misses=0;}catch{instance.metrics=null;instance.phase='unavailable';instance.misses=(instance.misses??0)+1;await reconcileLost(instance);}}));emit();}finally{polling=false;}}
async function poll(){if(polling||closing)return;polling=true;const full=pollCount++%10===0;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics${full?'?requests=all':''}`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');const fresh=await response.json();const older=instance.metrics?.requests,recent=fresh.requests;instance.metrics=full||!Array.isArray(older)||!Array.isArray(recent)||!recent.length?fresh:{...fresh,requests:[...recent,...older.filter(r=>Number(r.time)<Math.min(...recent.map(x=>Number(x.time))))]};const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';instance.misses=0;}catch{instance.metrics=null;instance.phase='unavailable';instance.misses=(instance.misses??0)+1;await reconcileLost(instance);}}));emit();}catch(error){console.warn('[strata host] Native polling failed; the next poll will retry:',error);}finally{polling=false;}}
/* The engine of a ready instance stopped answering. After a few looks in a row Control is asked: an owner that says the engine is stopped, failed or lost ends the "ready" the app was still showing (the model looked loaded for good while every request failed, #4973); an engine that is only busy stays as it is. */
async function reconcileLost(instance){if(instance.misses<3||instance.status!=='ready'||!instance.profile||typeof control.status!=='function')return;let st=null;try{st=await control.status(instance.profile);}catch{return;}if(instance.status==='ready'&&['stopped','failed','stale'].includes(st?.state)){instance.status='error';instance.error='Engine stopped. Open diagnostics or reload.';}}
function ensurePoll(){if(!timer){timer=setInterval(()=>void poll(),2000);timer.unref?.();}void poll();}
@@ -852,7 +854,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}
return {done:true,folder:st.from,partial:st.to,removed:result.removed??0,restored:result.restored??0};
}
async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.kind==='models-move'){/* a safe stop: the copy in flight is dropped, files already moved stay */try{writeFileSync(job.cancelFile,'stop');}catch{/* the run ends anyway */}job.summary='Stopping…';emit();return state();}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();}
async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running'&&!(job.kind==='update-strata'&&typeof job.appUpdateFrom==='string'))job.state='cancelled';}/* (an app update ends the app on purpose: its job stays running, so the next start can say it finished) */await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();}
async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running'&&!(job.kind==='update-strata'&&typeof job.appUpdateFrom==='string'))job.state='cancelled';}/* (an app update ends the app on purpose: its job stays running, so the next start can say it finished) */await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));jobStore.close();disconnect();}
// Remove nonserializable process references from public jobs.
const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,engineAbort,rawResult,...job})=>job);return value;};
async function localPreview(path){if(!packaged)throw new Error('Checking local model files is part of the Strata app.');if(typeof path!=='string'||!path.trim()||[...path].some(c=>c.charCodeAt(0)<32))throw new Error('Choose a folder.');return control.importPlan(path.trim());}
+68
View File
@@ -0,0 +1,68 @@
/** Best-effort job history: a failed status save must not stop inference. */
import * as fs from 'node:fs';
import { randomUUID } from 'node:crypto';
export function createJobStore(path, {
io = fs, warn = message => console.warn(message), now = Date.now,
setTimer = setTimeout, clearTimer = clearTimeout,
} = {}) {
let saved = null, pending = null, timer = null, retries = 0;
let retryAfter = 0, warningAt = -Infinity, failed = false, closed = false;
const delays = [250, 1000, 3000];
const report = message => { try { warn(message); } catch { /* logging cannot stop the host */ } };
function attempt() {
timer = null;
if (pending === null) return;
const text = pending, temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
try {
// Write beside the destination, then replace it: preserve the last good JSON on failure.
io.writeFileSync(temporary, text, { mode: 0o600 });
io.renameSync(temporary, path);
saved = text;
pending = null;
retries = 0;
retryAfter = 0;
if (failed) report('[strata host] Job history persistence recovered.');
failed = false;
} catch (error) {
if (!failed || now() - warningAt >= 60000) {
warningAt = now();
report(`[strata host] Job history save failed (${error.code ?? 'UNKNOWN'}, errno ${error.errno ?? '?'}, ${error.syscall ?? 'write'}): ${error.message}. Keeping in-memory state; inference continues.`);
}
failed = true;
if (!closed && retries < delays.length) {
timer = setTimer(attempt, delays[retries++]);
timer.unref?.();
} else {
retries = 0;
retryAfter = now() + 30000;
}
} finally {
// Only our uniquely named temporary file is eligible for cleanup.
try { io.rmSync(temporary, { force: true }); } catch { /* try no other files */ }
}
}
return {
save(jobs) {
if (closed) return;
const text = JSON.stringify(jobs);
if (text === saved) {
pending = null;
if (timer !== null) clearTimer(timer);
timer = null;
return;
}
pending = text; // Retries always write the newest state, never an older snapshot.
if (timer === null && now() >= retryAfter) attempt();
},
close() {
if (closed) return;
closed = true;
if (timer !== null) clearTimer(timer);
timer = null;
attempt(); // One final best-effort save, with no retry timer after shutdown.
},
};
}
+106
View File
@@ -0,0 +1,106 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { syncBuiltinESMExports } from 'node:module';
import { join } from 'node:path';
import { createJobStore } from '../server/native-job-store.mjs';
import { createNativeControl } from '../server/native-control.mjs';
const root = fs.mkdtempSync(join(import.meta.dirname, 'test-data-'));
test.after(() => { assert.equal(join(root, '..'), import.meta.dirname); fs.rmSync(root, { recursive: true, force: true }); });
const fault = () => Object.assign(new Error('simulated Windows open failure'), {code:'UNKNOWN',errno:-4094,syscall:'open'});
function fixture(ioPatch = {}) {
const directory = fs.mkdtempSync(join(root, 'case-'));
const path = join(directory, 'native-jobs.json');
const queue = new Map(), warnings = [];
let clock = 100000, next = 0;
const store = createJobStore(path, {
io: {...fs, ...ioPatch}, now:()=>clock, warn:x=>warnings.push(x),
setTimer(fn, delay) { const handle={id:++next,unref(){}}; queue.set(handle,{fn,delay});return handle; },
clearTimer(handle) { queue.delete(handle); },
});
return {store,path,queue,warnings,advance(ms){clock+=ms;},retry(){const [handle,item]=queue.entries().next().value;queue.delete(handle);item.fn();return item.delay;}};
}
test('unchanged jobs are not repeatedly written', () => {
let writes=0;
const f=fixture({writeFileSync(...args){writes++;return fs.writeFileSync(...args);}});
f.store.save([{id:'one',state:'done'}]);
f.store.save([{id:'one',state:'done'}]);
assert.equal(writes,1);
assert.deepEqual(JSON.parse(fs.readFileSync(f.path)),[{id:'one',state:'done'}]);
f.store.close();
});
test('UNKNOWN open failure preserves the old JSON; retry saves newest state', () => {
let blocked=true;
const f=fixture({writeFileSync(...args){if(blocked)throw fault();return fs.writeFileSync(...args);}});
fs.writeFileSync(f.path,'[{"id":"old"}]');
assert.doesNotThrow(()=>f.store.save([{id:'new'}]));
assert.deepEqual(JSON.parse(fs.readFileSync(f.path)),[{id:'old'}]);
f.store.save([{id:'newest'}]);
blocked=false;
assert.equal(f.retry(),250);
assert.deepEqual(JSON.parse(fs.readFileSync(f.path)),[{id:'newest'}]);
assert.equal(f.warnings.length,2);
assert.match(f.warnings[0],/UNKNOWN.*-4094.*inference continues/);
assert.match(f.warnings[1],/recovered/);
assert.equal(f.queue.size,0);
f.store.close();
});
test('rename failure preserves old JSON and cleans only the temporary file', () => {
const f=fixture({renameSync(){throw Object.assign(fault(),{code:'EPERM',syscall:'rename'});}});
fs.writeFileSync(f.path,'[{"id":"old"}]');
f.store.save([{id:'new'}]);
assert.deepEqual(JSON.parse(fs.readFileSync(f.path)),[{id:'old'}]);
assert.deepEqual(fs.readdirSync(join(f.path,'..')),['native-jobs.json']);
f.store.close();
assert.equal(f.queue.size,0);
});
test('persistent failures have bounded retries, cooldown and rate-limited warnings', () => {
let writes=0;
const f=fixture({writeFileSync(){writes++;throw fault();}});
f.store.save([]);
assert.equal(f.retry(),250);assert.equal(f.retry(),1000);assert.equal(f.retry(),3000);
assert.equal(writes,4);assert.equal(f.queue.size,0);assert.equal(f.warnings.length,1);
f.store.save([{id:'later'}]);assert.equal(writes,4);
f.advance(30001);f.store.save([{id:'later'}]);assert.equal(writes,5);
f.store.close();assert.equal(f.queue.size,0);
});
test('shutdown flushes the latest pending state and cancels retries', () => {
let blocked=true;
const f=fixture({writeFileSync(...args){if(blocked)throw fault();return fs.writeFileSync(...args);}});
f.store.save([{id:'one'}]);f.store.save([{id:'two'}]);blocked=false;f.store.close();
assert.deepEqual(JSON.parse(fs.readFileSync(f.path)),[{id:'two'}]);
assert.equal(f.queue.size,0);
});
test('real controller polling survives the exact filesystem failure and still publishes state', async () => {
const directory=fs.mkdtempSync(join(root,'controller-'));
const original=fs.writeFileSync;
let changes=0,controller;
fs.writeFileSync=function(path,...args){if(String(path).startsWith(join(directory,'native-jobs.json')))throw fault();return original(path,...args);};
syncBuiltinESMExports();
try {
controller=createNativeControl({directory,defaultRepo:directory,changed(){changes++;}});
await assert.doesNotReject(controller.poll());
assert.equal(changes,1);
} finally {fs.writeFileSync=original;syncBuiltinESMExports();}
await new Promise(resolve=>setTimeout(resolve,350));
assert.deepEqual(JSON.parse(fs.readFileSync(join(directory,'native-jobs.json'))),[]);
await controller.poll();assert.equal(changes,2);
await controller.close();
});
test('an unexpected polling callback failure does not leave polling stuck or reject', async () => {
const directory=fs.mkdtempSync(join(root,'boundary-'));
let changes=0;
const controller=createNativeControl({directory,defaultRepo:directory,changed(){if(++changes===1)throw new Error('simulated callback failure');}});
await assert.doesNotReject(controller.poll());
await assert.doesNotReject(controller.poll());
assert.equal(changes,2);
await controller.close();
});