diff --git a/apps/host/server/agent/harness-runtime.mjs b/apps/host/server/agent/harness-runtime.mjs index c89b8a8675..bc9c057e21 100644 --- a/apps/host/server/agent/harness-runtime.mjs +++ b/apps/host/server/agent/harness-runtime.mjs @@ -124,7 +124,7 @@ export class HarnessProcess { const done = new Promise(r => child.once('exit', r)); if (process.platform === 'win32') { // /T takes the shells and PTYs the agent started; /PID is this child only. - spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }); + taskkillTree(child.pid); } else { child.kill('SIGTERM'); setTimeout(() => { if (!this.exited) child.kill('SIGKILL'); }, graceMs).unref(); @@ -157,11 +157,22 @@ export function stopStaleAgent(pidFile) { rmSync(pidFile, { force: true }); const cmd = commandLineOf(pid); if (!cmd || !/lib[\\/]bin\.js/.test(cmd) || !/--profile web/.test(cmd)) return null; - if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true }); + if (process.platform === 'win32') taskkillTree(pid); else { try { process.kill(pid, 'SIGTERM'); } catch { /* already gone */ } } return pid; } +/** How long a taskkill may take. spawnSync blocks the host's whole event loop (every timer and every HTTP call) until the program returns, so it must have an end. */ +export const TASKKILL_TIMEOUT_MS = 10_000; + +/** + * Windows: end a process and its children (`taskkill /PID /T /F`, that PID's tree only). Bounded by TASKKILL_TIMEOUT_MS: a taskkill that stalls (a process the + * system cannot end, a machine out of memory) used to freeze the host for as long as it stalled. `run` is injectable for tests. + */ +export function taskkillTree(pid, run = spawnSync) { + return run('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore', timeout: TASKKILL_TIMEOUT_MS }); +} + /** Remove any occurrence of a secret value from text bound for a log. */ export function redact(text, secrets) { let out = String(text); diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index 3de2a6fad8..c29fbeb986 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -179,10 +179,36 @@ const failure = (result, fallback) => { return new ControlError(message, { exitCode: result.code, output: result.json, ...(UPDATE_LOCK_HELD.test(String(message)) ? { code: 'update_busy' } : {}) }); }; -/** Operations the app uses. `run` is injectable so the host's tests need no Python. */ -export function createControl({ control = findControl(), env = process.env, run = null } = {}) { +/** + * What a call to Control is called in the host log: its first two words and, when there is one, the profile it is about (`runtime stop (profile web-1)`). + * Nothing else of the command line is written: paths, feed addresses and keys stay out of the log. + */ +export function controlCallName(args) { + const words = args.slice(0, 2).map(String); + const at = args.indexOf('--profile'); + const profile = at >= 0 && typeof args[at + 1] === 'string' && /^[\w.-]{1,64}$/.test(args[at + 1]) ? args[at + 1] : null; + return profile ? `${words.join(' ')} (profile ${profile})` : words.join(' '); +} + +/** Operations the app uses. `run` is injectable so the host's tests need no Python; `log` (a line writer) makes every call write its start, its end and how long it took. */ +export function createControl({ control = findControl(), env = process.env, run = null, log = null, now = () => Date.now() } = {}) { if (!control) return null; - const call = run ?? ((args, options) => runCli(control, args, { env, ...options })); + const base = run ?? ((args, options) => runCli(control, args, { env, ...options })); + // A call to Control that never returns (a stuck stop, a start that waits) used to leave nothing in the host log to say which call it was or for how long. + let numbered = 0; + const call = !log ? base : async (args, options) => { + const n = ++numbered, name = controlCallName(args), t0 = now(); + const secs = () => ((now() - t0) / 1000).toFixed(1); + try { log(`control #${n} begin ${name}`); } catch { /* a log must not break a call */ } + try { + const result = await base(args, options); + try { log(`control #${n} end ${name}: exit ${result?.code ?? '?'} after ${secs()} s`); } catch { /* as above */ } + return result; + } catch (error) { + try { log(`control #${n} failed ${name}: ${error?.code ?? error?.name ?? 'error'} after ${secs()} s`); } catch { /* as above */ } + throw error; + } + }; const feedArgs = feed => (feed ? ['--feed', feed] : []); return { control, diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 539b897754..41151da1ef 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -129,7 +129,7 @@ const modelProviders = createModelProviders({ directory: store.DATA_DIR, knownTh const imageModels = createImageModels({ dataDir: store.DATA_DIR, modelsDir: () => store.MODELS_DIR, real: models.REAL, changed: value => hub.send('image-models', value) }); /* The installed app ships Strata Control (python + strata_control) next to the host; a source checkout has none and keeps its older paths. */ const CONTROL = findControl(); -const control = createControl({ control: CONTROL }); +const control = createControl({ control: CONTROL, log: line => console.log(line) }); // Files a run as administrator made in Strata's own folders (owner Administrators) are given back to the user at every start; best effort, never blocks. if (control && process.platform === 'win32' && !process.env.STRATA_NO_REPAIR_ACCESS) void control.repairAccess().catch(() => {}); /* Which window shows the page (the app window or, when that cannot run, a browser tab) and what only the app window can do: app-ui.mjs. */ diff --git a/apps/host/tests/control-call-log.test.mjs b/apps/host/tests/control-call-log.test.mjs new file mode 100644 index 0000000000..61961995dc --- /dev/null +++ b/apps/host/tests/control-call-log.test.mjs @@ -0,0 +1,75 @@ +// SOAK-APP 11-17 13:20: a model Unload stayed pending for 5 min 46 s and nothing in the host log said which call to Control it was waiting for, or for how long. +// Every call to Control now writes its start and its end with the time it took. Also: a Windows taskkill of the Harness (synchronous: it blocks the host's whole event +// loop, every timer and every HTTP call, until it returns) has an end. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { controlCallName, createControl } from '../server/control-runtime.mjs'; +import { TASKKILL_TIMEOUT_MS, taskkillTree } from '../server/agent/harness-runtime.mjs'; + +const control = { dir: '/c', python: 'p', cli: 'c' }; + +test('a call to Control writes its start, its end and how long it took; the command line past its first two words and the profile stays out of the log', async () => { + const lines = []; let clock = 1000; + const ctl = createControl({ + control, log: line => lines.push(line), now: () => clock, + run: async args => { clock += 2500; return { code: 0, json: { ok: true }, text: '', stderr: '', args }; }, + }); + await ctl.stop('web-1', { waitSeconds: 120 }); + assert.deepEqual(lines, ['control #1 begin runtime stop (profile web-1)', 'control #1 end runtime stop (profile web-1): exit 0 after 2.5 s']); + lines.length = 0; + await ctl.updateCheck({ feed: 'https://user:secret@example.invalid/feed', appVersion: '1.2.3' }).catch(() => {}); + assert.ok(lines.length >= 2, 'the update check was logged too: ' + lines.join(' | ')); + assert.match(lines[0], /^control #2 begin update --check$/); + for (const l of lines) assert.doesNotMatch(l, /secret|example\.invalid|1\.2\.3/, l); +}); + +test('a call that fails or times out is logged as failed with its code and its time, and the error still reaches the caller', async () => { + const lines = []; let clock = 0; + const ctl = createControl({ + control, log: line => lines.push(line), now: () => clock, + run: async () => { clock += 180_000; throw Object.assign(new Error('Strata Control did not answer within 180 s (runtime stop).'), { code: 'control_timeout' }); }, + }); + await assert.rejects(ctl.stop('web-1'), /did not answer within 180 s/); + assert.deepEqual(lines, ['control #1 begin runtime stop (profile web-1)', 'control #1 failed runtime stop (profile web-1): control_timeout after 180.0 s']); +}); + +test('calls are numbered, a log that throws never breaks a call, and without a log nothing is written', async () => { + const seen = []; + const noisy = createControl({ control, log: () => { throw new Error('the log is broken'); }, run: async args => { seen.push(args[0]); return { code: 0, json: { ok: true, state: 'ready' }, text: '', stderr: '' }; } }); + await noisy.stop('a'); await noisy.stop('b'); + assert.deepEqual(seen, ['runtime', 'runtime']); + const lines = []; + const numbered = createControl({ control, log: l => lines.push(l), run: async () => ({ code: 0, json: { ok: true }, text: '', stderr: '' }) }); + await numbered.stop('a'); await numbered.stop('b'); + assert.deepEqual(lines.filter(l => /begin/.test(l)), ['control #1 begin runtime stop (profile a)', 'control #2 begin runtime stop (profile b)']); + const quiet = createControl({ control, run: async () => ({ code: 0, json: { ok: true }, text: '', stderr: '' }) }); + await quiet.stop('a'); // no log option: as before +}); + +test('controlCallName: the first two words, the profile only when it is a plain name', () => { + assert.equal(controlCallName(['runtime', 'stop', '--profile', 'web-1', '--wait', '120']), 'runtime stop (profile web-1)'); + assert.equal(controlCallName(['components', 'engines', '--output', 'json']), 'components engines'); + assert.equal(controlCallName(['models', 'import', 'C:\\Users\\x\\secret model.gguf']), 'models import'); + assert.equal(controlCallName(['runtime', 'start', '--profile', 'C:\\Users\\x\\p']), 'runtime start'); +}); + +test('taskkillTree ends the tree of one PID and is bounded, so a stalled taskkill cannot freeze the host', () => { + assert.ok(TASKKILL_TIMEOUT_MS > 0 && TASKKILL_TIMEOUT_MS <= 15_000); + let seen = null; + const result = taskkillTree(4242, (cmd, args, options) => { seen = { cmd, args, options }; return { status: null, error: Object.assign(new Error('spawnSync taskkill ETIMEDOUT'), { code: 'ETIMEDOUT' }) }; }); + assert.deepEqual(seen.args, ['/PID', '4242', '/T', '/F']); + assert.equal(seen.cmd, 'taskkill'); + assert.equal(seen.options.timeout, TASKKILL_TIMEOUT_MS); + assert.equal(seen.options.stdio, 'ignore'); + assert.equal(seen.options.windowsHide, true); + assert.equal(result.error.code, 'ETIMEDOUT'); // a timeout is a result, never a throw +}); + +test('no taskkill in the Harness launcher is started without a time limit', () => { + const source = readFileSync(new URL('../server/agent/harness-runtime.mjs', import.meta.url), 'utf8'); + assert.equal(source.split('\n').filter(l => /spawnSync\(\s*'taskkill'/.test(l)).length, 0, 'taskkill is only started by taskkillTree'); + const started = source.split('\n').filter(l => /\brun\('taskkill'/.test(l)); + assert.equal(started.length, 1); + assert.match(started[0], /timeout: TASKKILL_TIMEOUT_MS/); +});