Desktop (Linux) + App: after the in-app update the update job reads done, and no old AppImage runtime is kept alive

Found by the item 1 gate on l620 (0.2.13 TEST app -> 0.2.14 TEST app): the app came back by itself in 9 s, but
- the update job read "cancelled": the old host's close() marks running jobs cancelled when its shell stops it, and the new host
  settled only "running" records. A job with appUpdateFrom saved as cancelled is now settled the same way ("Strata is updated to
  <v>", or the "did not finish" error when the same version came back), and this host's close() leaves such a job running.
- each restarted AppImage runtime inherited an fd (1023) into the previous /tmp/.mount_*, so the old runtime and mount stayed until
  the app quit. The restarter now closes inherited fds before it starts Strata again.
This commit is contained in:
Niko1221 committed 2026-11-09 23:43:01 +01:00
1 parent b5dc27e388
commit 7937614e34
3 files changed
+64 -3

No files matched your search

+20
View File
@@ -296,6 +296,25 @@ pub fn original_environment(record: Option<&str>) -> Option<Vec<(String, String)
found.map(|vars| vars.into_iter().filter(|(k, _)| k != "STRATA_ORIGINAL_ENV").collect())
}
/// The files this process got from the window process that restarted it (the old AppImage's fd to its own mount, WebKit's /proc and cgroup files) are
/// closed before Strata is started again: a child would inherit them, and an open fd into the old /tmp/.mount_* keeps that AppImage's runtime and mount
/// alive until the new app quits. Only numbers above 2 (stdin, stdout, stderr stay); run first, before this process opens anything of its own.
fn close_inherited_fds() {
#[cfg(target_os = "linux")]
{
use std::os::fd::{FromRawFd, OwnedFd};
let Ok(dir) = std::fs::read_dir("/proc/self/fd") else { return };
let fds: Vec<i32> = dir.filter_map(|e| e.ok()?.file_name().to_str()?.parse::<i32>().ok()).filter(|fd| *fd > 2).collect();
// (the listing's own fd is in the list; it is closed by now, and closing a closed number again only fails)
for fd in fds {
if std::path::Path::new(&format!("/proc/self/fd/{fd}")).exists() {
// SAFETY: nothing in this process uses these numbers: they were inherited across exec and nothing has been opened yet
drop(unsafe { OwnedFd::from_raw_fd(fd) });
}
}
}
}
/// The program to start again: the AppImage file (the updater replaced it in place), else this executable.
fn program_to_restart() -> Option<PathBuf> {
if let Some(image) = std::env::var_os("APPIMAGE").filter(|v| !v.is_empty()) {
@@ -312,6 +331,7 @@ fn program_to_restart() -> Option<PathBuf> {
/// (a new shell, a new host), detached, and leave. If the old shell is still there after the wait, nothing is started: two Strata apps never run at once,
/// and a person's next start joins or replaces the old one as usual. Prints nothing: the old shell owned this process's output and is gone.
pub fn restart_after_update() -> i32 {
close_inherited_fds();
let log = Log::open();
let old = std::env::var(SHELL_PID_ENV).ok().and_then(|v| v.trim().parse::<u32>().ok()).filter(|p| *p != 0).or_else(|| read_session().map(|s| s.pid));
log.line("shell", &format!("started as the app window by the app updater, not by Strata (old app process {old:?}): restarting Strata"));
+5 -3
View File
@@ -46,10 +46,12 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
const instances=new Map(),processes=new Map(),jobs=new Map(),logs=[];
const savedJobs=readJson(join(directory,'native-jobs.json'),[]);/* An app update ends the app on purpose: the installer replaces it and starts it again. The job that asked for it was saved as running together with the app version it started from (appUpdateFrom); a start that finds a different version knows the update finished, instead of calling it an interrupted operation. */
const thisAppVersion=()=>process.env.STRATA_APP_VERSION||null;
/* The job that started an app update is still 'running' when the app ends for the installer; an older host's close() saved it as 'cancelled' (the app update ends the host the normal way on Linux): with appUpdateFrom set, that is the same record (APP-LIN 0.2.14). */
const closedForAppUpdate=j=>j.state==='running'||j.state==='cancelled'&&typeof j.appUpdateFrom==='string';
/* A record an OLDER host wrote (no appUpdateFrom): the app's own program file was replaced after the job began, so the installer finished. <install>/host/server is ROOT's parent chain: ROOT = <install>/host. */
const appProgramNewerThan=started=>{try{const t=Date.parse(started);if(!Number.isFinite(t))return false;const dir=dirname(ROOT),exe=join(dir,process.platform==='win32'?'strata-desktop.exe':'strata-desktop'),times=[];for(const f of [exe,join(dir,'uninstall.exe')])if(existsSync(f)){const st=statSync(f);times.push(st.mtimeMs,st.ctimeMs);}/* the installer keeps the build time as the program's modified time but writes uninstall.exe and changes the program file's metadata when it installs */return times.some(x=>x>t);}catch{return false;}};
const settledByAppUpdate=j=>j.state==='running'&&j.kind==='update-strata'&&((typeof j.appUpdateFrom==='string'&&!!thisAppVersion()&&thisAppVersion()!==j.appUpdateFrom)||(typeof j.appUpdateFrom!=='string'&&appProgramNewerThan(j.startedAt)));
const neverFinishedAppUpdate=j=>j.state==='running'&&j.kind==='update-strata'&&typeof j.appUpdateFrom==='string'&&!!thisAppVersion()&&thisAppVersion()===j.appUpdateFrom;
const settledByAppUpdate=j=>closedForAppUpdate(j)&&j.kind==='update-strata'&&((typeof j.appUpdateFrom==='string'&&!!thisAppVersion()&&thisAppVersion()!==j.appUpdateFrom)||(typeof j.appUpdateFrom!=='string'&&appProgramNewerThan(j.startedAt)));
const neverFinishedAppUpdate=j=>closedForAppUpdate(j)&&j.kind==='update-strata'&&typeof j.appUpdateFrom==='string'&&!!thisAppVersion()&&thisAppVersion()===j.appUpdateFrom;
for(const j of (Array.isArray(savedJobs)?savedJobs:[]).slice(-12))jobs.set(j.id,{...j,...(settledByAppUpdate(j)?{state:'done',error:null,summary:`Strata is updated to ${thisAppVersion()}.`,finishedAt:new Date().toISOString()}:neverFinishedAppUpdate(j)?{state:'error',error:`The update to ${j.appUpdateTo??'the new version'} did not finish: the app closed for the installer, but the old version ${j.appUpdateFrom} started again. Try Update again, or download the installer from the Strata release page (https://github.com/Niko1221/Strata/releases/latest).`,summary:'The app update did not finish',finishedAt:new Date().toISOString()}:j.state==='running'?{state:'error',error:'The host restarted before completion. Check diagnostics, then retry; completed files are kept.',summary:'Interrupted operation'}:{})});
/* Packaged mode: the app ships Strata Control (control-runtime.mjs). Models are run configs in an install folder, the engine
comes from the component folder, and a start is `strata runtime start` under the owner runtime. Nothing is installed,
@@ -837,7 +839,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.state='cancelled';}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(()=>{})));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());}
+39
View File
@@ -142,6 +142,45 @@ test('the engine update repairs run-config paths of a gone AppImage mount before
} finally { await f.native.close(); f.cleanup(); }
});
// ------------------------------------------------------------------ item 1: the app update's job across the restart
test('an app update job the old host closed as "cancelled" is read as finished by the new version; this host keeps it running when it closes', async () => {
const before = process.env.STRATA_APP_VERSION;
const root = mkdtempSync(join(tmpdir(), 'strata-applin-jobs-'));
try {
const job = { id: 'j1', kind: 'update-strata', state: 'cancelled', startedAt: new Date().toISOString(), summary: 'Downloading the app update: 100%', appUpdateFrom: '0.2.13', appUpdateTo: '0.2.14' };
writeFileSync(join(root, 'native-jobs.json'), JSON.stringify([job, { ...job, id: 'j2', appUpdateFrom: undefined }]));
process.env.STRATA_APP_VERSION = '0.2.14';
const mk = () => createNativeControl({ control: { control: { dir: '/c' }, version: '0.1.60' }, directory: root, spawnProcess: () => { throw new Error('no process'); }, fetcher: async () => Response.json({}), requests: () => [] });
const next = mk();
const jobs = next.state().jobs;
assert.equal(jobs.find(j => j.id === 'j1').state, 'done');
assert.match(jobs.find(j => j.id === 'j1').summary, /updated to 0\.2\.14/);
assert.equal(jobs.find(j => j.id === 'j2').state, 'cancelled', 'a cancelled job that was not an app update stays cancelled');
await next.close();
// the same version came back: the update did not finish, and it says so
writeFileSync(join(root, 'native-jobs.json'), JSON.stringify([{ ...job, appUpdateFrom: '0.2.14' }]));
const same = mk();
assert.equal(same.state().jobs[0].state, 'error');
await same.close();
} finally { if (before === undefined) delete process.env.STRATA_APP_VERSION; else process.env.STRATA_APP_VERSION = before; rmSync(root, { recursive: true, force: true }); }
});
test('closing the host during an app update leaves its job running (the next start settles it)', async () => {
const before = process.env.STRATA_APP_VERSION;
process.env.STRATA_APP_VERSION = '0.2.14';
const root = mkdtempSync(join(tmpdir(), 'strata-applin-close-'));
const control = { control: { dir: '/c' }, version: '0.1.60', async update() { return { ok: true, results: [] }; } };
const appUpdater = { check: async () => ({ available: true, version: '0.2.15' }), install: () => new Promise(() => {}) };
const native = createNativeControl({ control, appUpdater, directory: root, spawnProcess: () => { throw new Error('no process'); }, fetcher: async () => Response.json({}), requests: () => [] });
try {
const started = native.operation('update-strata', {});
for (let i = 0; i < 100 && !native.state().jobs.find(j => j.id === started.id)?.appUpdateFrom; i++) await new Promise(r => setTimeout(r, 10));
await native.close();
assert.equal(native.state().jobs.find(j => j.id === started.id).state, 'running');
} finally { if (before === undefined) delete process.env.STRATA_APP_VERSION; else process.env.STRATA_APP_VERSION = before; rmSync(root, { recursive: true, force: true }); }
});
// ------------------------------------------------------------------ item 5: the first-run card offers the Control update
const feedReport = control => ({ ok: true, feed: {}, hardware: { backend: 'sycl' }, engine: { status: 'install', installed: null, offered: { version: '0.1.60', variant: '', backend: 'sycl' }, download_bytes: 300e6 }, control, app: {} });