diff --git a/static/dashboard/CHANGELOG.md b/static/dashboard/CHANGELOG.md index 5625f55a8..07dc4de15 100644 --- a/static/dashboard/CHANGELOG.md +++ b/static/dashboard/CHANGELOG.md @@ -4,6 +4,7 @@ One line per version, newest first. Every REST-facing change bumps the version i (the app surfaces it via `/system/dashboard/update-check` and the "Update available" pill), so this file is the human record of what each bump enables. Keep entries short: `version - change (TICKET)`. +- **1.2.5** - maps stop/cancel actually stop (ADFA-4896, server half). The maps runner shelled through `sudo`, so pause/cancel only killed the wrapper — the `tile-extract.py` worker kept running, finished in the background, and the region ended up listed even after cancel. Fixes: the extract now spawns **detached** and the engine kills the whole **process group** (`-pid`) so the worker dies with it; the engine also drops **late updates** once a job is paused/canceled, so a slow-dying line can't resurrect the phase; and the maps runner now honors **pause vs cancel** (`classifyStop`) and **purges the partial** on any non-success — it prunes the half-written pmtiles the script leaves in `/library/downloads/maps` (which `tile-extract.py delete` does NOT touch) and runs `delete` (which refreshes extracts.json) for the rare race where the extract finished just as the stop landed. Pause is stop+restart (resume re-extracts clean), cancel removes the region entirely. `cancel()` now also finalizes a **paused** job to `canceled` (Cancel-after-Stop) instead of leaving it stuck at `paused`. No maps per-layer checkpoint yet (→ ADFA-4898). Device-verified: group-kill reaches the pmtiles worker under proot (no background survivor / phantom region). (ADFA-4896) - **1.2.4** - Download control surface (ADFA-4894, the engine half; app buttons land under ADFA-4896). Adds a **`paused`** job phase and `pause(id)` / `resume(id)` / `retry(id)` to the durable engine, exposed as `POST /:type/jobs/:id/{pause,resume,retry}`. Pause stops the runner but KEEPS the partial (resume continues via aria2 `--continue` for kiwix / per-item for books — the PAUSED-vs-CANCELLED distinction mirrors the APK ADFA-5119); retry re-runs an errored job. maps resume still restarts layers (no per-layer checkpoint yet → ADFA-4898). (ADFA-4894) - **1.2.3-dev** - Resilient content downloads (ADFA-4894, Area 1 of the ADFA-4893 contract). A network drop mid-job recovers or fails cleanly instead of failing the whole batch at the first blip: a shared `withRetry` backoff helper; job cancel now aborts an in-flight `fetch` (new `AbortSignal` on the runner), not just child processes; **books** get a per-attempt timeout + per-item retry/backoff and no longer fail a batch on one dropped EPUB; **kiwix** prunes the partial `.zim` + `.aria2` on cancel (clean-on-cancel) and gains aria2 reconnect flags (`--max-tries`/`--retry-wait`/`--timeout`, documented divergence from the app's `--max-tries=1` outer-loop model). kiwix also gets an **outer** reconnect loop (`withRetry` around aria2) so a full Wi-Fi drop — where aria2 exits on DNS (code 19) and can't retry itself — recovers across the handoff, resuming via `--continue`; books' retry budget widened to ~30s to outlast a real reassociation. Maps per-layer checkpoint is pending the on-box `tile-extract.py`. Version stays `1.2.3-dev.N` through the PR (device-verified on -dev.1); final bump to `1.2.3` at merge. (ADFA-4894) - **1.2.2** - New `GET /kolibri/subtree/:nodeId`: serves a channel's topic tree in Studio's `contentnode_tree` shape, with per-node byte sizes summed from the local content DB over each node's MPTT range, so the app browses an imported channel's whole tree offline (parsed by the same mapper it uses for Studio). Read-only; **404** when the channel's metadata is not imported, which the app reads as "fall back to Studio". Ships the endpoint PR added without a version bump. (ADFA-5094) diff --git a/static/dashboard/package.json b/static/dashboard/package.json index e526f3eff..9e08f379a 100644 --- a/static/dashboard/package.json +++ b/static/dashboard/package.json @@ -1,6 +1,6 @@ { "name": "dashboard-console", - "version": "1.2.4", + "version": "1.2.5", "description": "", "main": "index.js", "scripts": { diff --git a/static/dashboard/sockets/jobs.test.ts b/static/dashboard/sockets/jobs.test.ts index fa4f77f1b..4fe7bb215 100644 --- a/static/dashboard/sockets/jobs.test.ts +++ b/static/dashboard/sockets/jobs.test.ts @@ -80,6 +80,45 @@ test('retry re-runs a job that ended in error', async () => { assert.equal(attempt, 2); }); +test('a stopped job ignores late updates (no phase resurrection)', async () => { + // Models the maps bug (ADFA-4896): a slow-dying worker emits one more progress line right after + // pause. The engine must drop it so the phase stays 'paused' instead of flipping back to active. + jobs.registerRunner('kiwix', async (ctx: RunnerContext) => { + ctx.update({ phase: 'downloading', percent: 10 }); + await new Promise((_resolve, reject) => { + ctx.signal.addEventListener('abort', () => { + ctx.update({ phase: 'downloading', percent: 50 }); // late line after pause + reject(new Error('abort')); + }, { once: true }); + }).catch(() => { + if (ctx.isPaused()) throw new PausedError(); + throw new CanceledError(); + }); + }); + + const job = jobs.create('kiwix', ['wikipedia/late.zim']); + await tick(); + assert.equal(jobs.pause(job.id), true); + await tick(); + assert.equal(jobs.get(job.id)?.phase, 'paused'); // the late 'downloading' update was dropped +}); + +test('cancel finalizes a paused job (no orphan)', async () => { + // ADFA-4896: Cancel after Stop. The paused runner has already exited, so cancel must still record + // the terminal 'canceled' state instead of leaving the job stuck at 'paused'. + const g = gatedRunner(); + jobs.registerRunner('kiwix', g.runner); + + const job = jobs.create('kiwix', ['wikipedia/p.zim']); + await tick(); + assert.equal(jobs.pause(job.id), true); + await tick(); + assert.equal(jobs.get(job.id)?.phase, 'paused'); + + assert.equal(jobs.cancel(job.id), true); + assert.equal(jobs.get(job.id)?.phase, 'canceled'); // not left 'paused' +}); + test('the verbs no-op outside their phase', async () => { jobs.registerRunner('kiwix', async (ctx: RunnerContext) => { ctx.update({ phase: 'done', percent: 100 }); // completes immediately diff --git a/static/dashboard/sockets/jobs.ts b/static/dashboard/sockets/jobs.ts index 7544afefc..1fbc74069 100644 --- a/static/dashboard/sockets/jobs.ts +++ b/static/dashboard/sockets/jobs.ts @@ -159,10 +159,14 @@ class JobManager { const rt = this.runtime.get(id); if (rt) { rt.canceled = true; - for (const p of rt.procs) { try { p.kill('SIGKILL'); } catch { /* already gone */ } } + this.killAll(rt); try { rt.ac.abort(); } catch { /* ADFA-4894: interrupt an in-flight fetch too */ } } - if (ACTIVE.includes(job.phase)) this.patch(id, { phase: 'canceled' }); + // ADFA-4896: finalize to 'canceled' from any non-terminal phase, INCLUDING 'paused'. A paused + // job's runner has already exited (no rt to kill), so without this it would linger 'paused' + // forever after a Cancel-after-Stop. For maps the partial was already purged at pause time, so + // there is nothing left to clean here. + if (ACTIVE.includes(job.phase) || job.phase === 'paused') this.patch(id, { phase: 'canceled' }); return true; } @@ -179,7 +183,7 @@ class JobManager { const rt = this.runtime.get(id); if (rt) { rt.paused = true; - for (const p of rt.procs) { try { p.kill('SIGKILL'); } catch { /* already gone */ } } + this.killAll(rt); try { rt.ac.abort(); } catch { /* interrupt an in-flight fetch */ } } this.patch(id, { phase: 'paused' }); @@ -226,6 +230,21 @@ class JobManager { for (const job of stuck) this.launch(job); } + /** + * ADFA-4896: SIGKILL a job's children. A runner that shells through a wrapper (e.g. maps via + * `sudo`) spawns detached, so the wrapper is a process-group leader; we kill the whole group + * (-pid) so the real worker dies with it, not just the wrapper — otherwise the worker is + * reparented and runs to completion in the background (the region ends up added even though the + * job was canceled). For a non-detached child (kiwix's aria2c), -pid names a group that doesn't + * exist and the group kill is a harmless no-op; the direct kill still stops it. + */ + private killAll(rt: { procs: Set }): void { + for (const p of rt.procs) { + try { if (p.pid) process.kill(-p.pid, 'SIGKILL'); } catch { /* no such group / already gone */ } + try { p.kill('SIGKILL'); } catch { /* already gone */ } + } + } + private patch(id: string, patch: JobUpdate): void { const cur = this.get(id); if (!cur) return; @@ -256,7 +275,9 @@ class JobManager { const ctx: RunnerContext = { job, items, ids, - update: (p) => this.patch(job.id, p), + // ADFA-4896: once the job is stopped, drop late updates so a slow-dying process (or a + // final progress line racing the kill) can't resurrect the paused/canceled phase. + update: (p) => { if (rt.canceled || rt.paused) return; this.patch(job.id, p); }, isCanceled: () => rt.canceled, throwIfCanceled: () => { if (rt.canceled) throw new CanceledError(); }, isPaused: () => rt.paused, diff --git a/static/dashboard/sockets/maps.exec.ts b/static/dashboard/sockets/maps.exec.ts index eb74910cb..f3a94a65a 100644 --- a/static/dashboard/sockets/maps.exec.ts +++ b/static/dashboard/sockets/maps.exec.ts @@ -3,17 +3,63 @@ // Maps runner for the durable job engine: extract a tile region via tile-extract.py. // Ported from the Phase 1 maps.socket handler; reuses its box validation. A job item // is { name, box, noninteractive? }; deletion stays a separate op (not a long job). -import { jobs, RunnerContext, CanceledError, JobUpdate } from './jobs'; +import { jobs, RunnerContext, CanceledError, PausedError, classifyStop, JobUpdate } from './jobs'; import { parseBox } from './maps.socket'; +import { spawn } from 'child_process'; +import fs from 'fs'; import path from 'path'; const SCRIPTS_DIR = '/opt/iiab/maps/tile-extract/'; const EXTRACT_SCRIPT = path.join(SCRIPTS_DIR, 'tile-extract.py'); +// ADFA-4896: tile-extract.py extracts each pmtiles into TMP_DIR and only shutil.move()s all three +// into the served dir once ALL have finished, updating extracts.json last. So a killed extract +// leaves half-written pmtiles HERE (never in the catalog) — and the script's own `delete` only +// cleans the served dir, NOT this one. We prune these ourselves. Must match TMP_DIR in the script. +const MAPS_TMP_DIR = '/library/downloads/maps'; // name: letters/digits/hyphen/underscore, 1..34 (same rule as the socket handler). const NAME_RE = /^[A-Za-z0-9_-]{1,34}$/; interface MapItem { name?: string; box?: string; noninteractive?: boolean; } +/** ADFA-4896: run a tile-extract maintenance command to completion, best-effort. Used for the + * stop/cancel cleanup, which must run while the job's own context is being torn down, so it does + * NOT go through ctx.spawn (that child would be killed with the job). Never rejects — a failed + * purge is logged, not fatal. */ +function runMapsCmd(args: string[], log: (l: string) => void): Promise { + return new Promise((resolve) => { + const p = spawn('sudo', [EXTRACT_SCRIPT, ...args]); + p.stdout?.on('data', (d: Buffer) => log(d.toString().trim())); + p.stderr?.on('data', (d: Buffer) => log(d.toString().trim())); + p.on('error', () => resolve()); + p.on('exit', () => resolve()); + }); +} + +/** ADFA-4896: remove a region's half-written pmtiles left in TMP_DIR by a killed extract — the + * script's `delete` doesn't touch this dir. Name-scoped (`*.full-region..pmtiles`), so a + * concurrent extract for another region is untouched. Best-effort. */ +function cleanupTmpPartials(name: string, log: (l: string) => void): void { + try { + const suffix = `.full-region.${name}.pmtiles`; + for (const f of fs.readdirSync(MAPS_TMP_DIR)) { + if (f.endsWith(suffix)) { + try { fs.unlinkSync(path.join(MAPS_TMP_DIR, f)); log(`[maps] pruned partial ${f}`); } catch { /* gone */ } + } + } + } catch { /* dir missing / unreadable — nothing to prune */ } +} + +/** ADFA-4896: discard a region's partial extract and drop it from the catalog. There is no maps + * checkpoint yet, so pause is stop+restart and cancel is remove — both discard the partial so a + * resume/retry re-extracts from a clean slate and nothing half-written is left behind or listed. + * Two places to clean: TMP_DIR (a mid-extract kill) and, via the script's `delete` (which runs + * update-json itself), the served dir + extracts.json (the rare race where the extract finished + * just as the stop landed). delete on a name that was never served is a harmless no-op. */ +async function purgeRegion(name: string, log: (l: string) => void): Promise { + cleanupTmpPartials(name, log); + await runMapsCmd(['delete', name], log); +} + const mapsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { const item = (ctx.items[0] ?? {}) as MapItem; const name = String(item.name ?? ''); @@ -37,7 +83,10 @@ const mapsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { let lastPct = 0; await new Promise((resolve, reject) => { - const p = ctx.spawn('sudo', args, { env: { ...process.env, PYTHONUNBUFFERED: '1' } }); + // ADFA-4896: detached so `sudo` is a process-group leader and the engine's group-kill takes + // the python worker down with it (otherwise pause/cancel only kill the sudo wrapper and the + // extract finishes in the background). + const p = ctx.spawn('sudo', args, { env: { ...process.env, PYTHONUNBUFFERED: '1' }, detached: true }); const onData = (buf: Buffer) => { const text = buf.toString(); ctx.log(text.trim()); @@ -57,12 +106,31 @@ const mapsRunner: (ctx: RunnerContext) => Promise = async (ctx) => { p.stderr?.on('data', onData); p.on('error', reject); p.on('exit', (code, signal) => { - if (signal === 'SIGKILL' || ctx.isCanceled()) return reject(new CanceledError()); - if (code === 0) resolve(); - else reject(new Error(`tile-extract exited with code ${code}`)); + if (code === 0) return resolve(); + // Non-zero or killed: could be a pause/cancel (group-killed by the engine) or a real + // failure. The catch below classifies it via classifyStop(ctx); this message is only + // surfaced for a genuine error. + reject(new Error(signal ? `tile-extract killed by ${signal}` : `tile-extract exited with code ${code}`)); }); + }).catch(async (e: unknown) => { + // ADFA-4896: any non-success purges the partial (no maps checkpoint -> never keep half-work), + // then re-throws as pause/cancel/error so the engine records the right terminal phase. On + // pause the job is resumable (resume re-extracts clean); on cancel the region is gone. + await purgeRegion(name, ctx.log); + const stop = classifyStop(ctx); + if (stop === 'paused') throw new PausedError(); + if (stop === 'canceled') throw new CanceledError(); + throw e; }); + // A stop can race in exactly as the extract finishes (code 0). Honor it — purge and stop — + // rather than marking done, so a paused/canceled job never leaves a completed region behind. + const lateStop = classifyStop(ctx); + if (lateStop) { + await purgeRegion(name, ctx.log); + throw lateStop === 'paused' ? new PausedError() : new CanceledError(); + } + ctx.update({ phase: 'done', percent: 100 }); };