Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit b5192ad09507c728468143d9f97d76ce2b6b72c1
parent 6ebb7b6493fb17f14a70af3fdc0c593c690e2111
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 10 Oct 2026 00:07:54 -0400

umtool: fetch-via-editor waits as long as the editor job does, saying its place in the queue

No 10-minute timeout for one window (nor the 6-hour one for --all): a window
queued behind other work is waited for (release 19 A5's ruling). While the job
is queued its place is printed when it changes, from GET /api/ops/job/<id>
(the route `pnpm ops job wait` reads); an editor without the route is waited
for without one. A poll the editor does not answer is retried with a back-off
(10 in a row end the wait); an answer that refuses still ends it at once.
Ctrl-C exits 130 and says the job keeps running on the editor. A window the
editor already had in flight (its dedupe) is followed, and says so.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/report-to-video/fetch-via-editor.mjs | 126++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mumtool/report-to-video/fetch-via-editor.test.mjs | 162++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
2 files changed, 262 insertions(+), 26 deletions(-)

diff --git a/umtool/report-to-video/fetch-via-editor.mjs b/umtool/report-to-video/fetch-via-editor.mjs @@ -17,16 +17,29 @@ // // The local path is still there behind UMTOOL_LOCAL_FETCH=1 — for a machine // with no editor to ask. +// +// IT WAITS AS LONG AS THE JOB DOES. A window queued behind other work on the +// editor is not a hung fetch, so there is no timeout (operator ruling, +// release 19 A5): while the job waits, its place in the editor's queue is +// printed whenever it changes -- `GET /api/ops/job/<id>`, what `pnpm ops job +// wait` reads -- and a poll the editor fails to answer is retried with a +// back-off rather than ending the wait. Ctrl-C stops waiting (exit 130); the +// job keeps running on the editor, and the next ask finds it cached. import path from "node:path"; import { readFile } from "node:fs/promises"; const DEFAULT_EDITOR = "http://localhost:3001"; -const POLL_MS = 1000; -// A window is seconds of media; a queue behind a channel sync is not. Generous, -// and the job keeps running on the editor if we give up — nothing is lost, the -// next ask finds it cached. -const POLL_TIMEOUT_MS = 10 * 60_000; +// One poll a second while a job runs, one every five while it waits its turn. +// FETCH_VIA_EDITOR_POLL_MS scales both (a test seam). +const POLL_MS = Number(process.env.FETCH_VIA_EDITOR_POLL_MS) > 0 ? Number(process.env.FETCH_VIA_EDITOR_POLL_MS) : 1000; +const QUEUED_POLL_MS = POLL_MS * 5; +// Consecutive polls the editor does not answer at all (a busy single-process +// server can drop a request) before the wait gives up; each waits longer, +// up to MAX_BACKOFF_MS. An ANSWER that refuses (a 401, an unknown job) still +// ends the wait at once. +const MAX_POLL_FAILURES = 10; +const MAX_BACKOFF_MS = 30_000; const argv = process.argv.slice(2); const flag = (name) => { @@ -132,6 +145,73 @@ async function ask(url, init) { } } +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +// The jobs being waited for, so Ctrl-C can say what keeps running. +const waitingOn = new Set(); +process.on("SIGINT", () => { + if (waitingOn.size) { + const ids = [...waitingOn].join(", "); + EMIT("note", { message: `stopped waiting; editor job(s) ${ids} keep running there (ask again and the window is cached)` }); + } + process.exit(130); +}); + +// A poll of a job's own fetch route: its JSON once the editor answers. A poll +// the editor does not answer at all is retried, backing off, and only +// MAX_POLL_FAILURES in a row end the wait. An answer that is not a 2xx ends it. +async function pollJob(jobId) { + let backoff = POLL_MS; + for (let failures = 1; ; failures += 1) { + let res; + try { + res = await fetch(`${editorUrl}/api/media/fetch-window/${jobId}`, { headers }); + } catch (err) { + if (failures >= MAX_POLL_FAILURES) { + die(`lost contact with the editor at ${editorUrl}: ${failures} polls of job ${jobId} in a row went unanswered (${err.message}); it may still be running there`); + } + await sleep(backoff); + backoff = Math.min(backoff * 2, MAX_BACKOFF_MS); + continue; + } + const j = await res.json().catch(() => ({})); + if (!res.ok) die(`polling editor job ${jobId} failed (HTTP ${res.status}): ${j.error ?? ""}`); + return j; + } +} + +// WHERE A QUEUED JOB WAITS: `GET /api/ops/job/<id>`'s `queue` -- its key, its +// position (0 = at the head, running), how many wait, and the job holding the +// queue. Null when the editor does not say (an editor without the route, or a +// moment it does not answer): the wait goes on either way. +async function queuePlace(jobId) { + try { + const res = await fetch(`${editorUrl}/api/ops/job/${encodeURIComponent(jobId)}`, { headers }); + if (!res.ok) return null; + const body = await res.json().catch(() => null); + const q = body?.job?.queue; + return q && Number.isFinite(Number(q.position)) ? q : null; + } catch { + return null; + } +} + +/** The line a queued job's place is said in, e.g. "queued — position 3 of 4 on clips:youtube.com, behind persist-videos (some-channel)". */ +function placeLine(q) { + const head = q.head ? `, behind ${q.head.kind ?? "a job"}${q.head.channelSlug ? ` (${q.head.channelSlug})` : ""}` : ""; + const of = Number(q.queued) > 0 ? ` of ${q.queued}` : ""; + return `queued — position ${q.position}${of}${q.key ? ` on ${q.key}` : ""}${head}`; +} + +// Says a queued job's place whenever it changes; returns the new memo. +async function notePlace(jobId, label, last) { + const q = await queuePlace(jobId); + if (!q || !(Number(q.position) > 0)) return last; + const line = placeLine(q); + if (line !== last) EMIT("note", { message: ` editor job ${jobId}${label}: ${line}` }); + return line; +} + if (wantAll) { if (argv.includes("--full")) die("--all fetches windows; --full is one clip's whole recording"); const clips = (whole.timeline ?? []).filter((e) => e.type === "clip"); @@ -182,26 +262,28 @@ if (wantAll) { // Every job, polled to its end. A job that stopped short (a rate limit, two // 403s) fails with the reason; asking again later resumes it, the fetched // windows answering from the cache. + // No deadline: a batch queued behind hours of other work is waited for. const pending = new Map(body.jobs.map((j) => [j.jobId, j])); + for (const jobId of pending.keys()) waitingOn.add(jobId); const failed = []; - const deadline = Date.now() + 6 * 60 * 60_000; const last = new Map(); + const places = new Map(); while (pending.size > 0) { - if (Date.now() > deadline) die(`gave up waiting for editor job(s) ${[...pending.keys()].join(", ")}`); - await new Promise((r) => setTimeout(r, POLL_MS * 5)); + await sleep(QUEUED_POLL_MS); for (const [jobId, j] of pending) { - const poll = await ask(`${editorUrl}/api/media/fetch-window/${jobId}`, { headers }); - const p = await poll.json().catch(() => ({})); - if (!poll.ok) die(`polling editor job ${jobId} failed (HTTP ${poll.status}): ${p.error ?? ""}`); + const p = await pollJob(jobId); + const label = ` (${j.platform}, ${j.items} window(s))`; if (p.status !== last.get(jobId)) { last.set(jobId, p.status); - EMIT("note", { message: ` editor job ${jobId} (${j.platform}, ${j.items} window(s)): ${p.status}` }); + EMIT("note", { message: ` editor job ${jobId}${label}: ${p.status}` }); } + if (p.status === "queued") places.set(jobId, await notePlace(jobId, label, places.get(jobId))); if (p.status === "done") pending.delete(jobId); else if (p.status === "failed" || p.status === "cancelled") { pending.delete(jobId); failed.push(`${jobId} ${p.status}: ${String(p.error ?? "").split("\n").slice(-3).join(" / ")}`); } + if (!pending.has(jobId)) waitingOn.delete(jobId); } } const unfinished = failed.length + (body.refused?.length ?? 0) + (body.unresolved?.length ?? 0); @@ -332,25 +414,21 @@ if (res.status !== 202) { } const jobId = body.jobId; -EMIT("note", { message: ` queued on the editor as job ${jobId}` }); +EMIT("note", { message: ` queued on the editor as job ${jobId}${body.existing ? " (already asked for; following it)" : ""}` }); +waitingOn.add(jobId); -const deadline = Date.now() + POLL_TIMEOUT_MS; +// No deadline: the job is waited for however long its queue is, its place +// said as it moves. let last = ""; +let place = null; for (;;) { - if (Date.now() > deadline) { - die( - `gave up waiting for editor job ${jobId} after ${POLL_TIMEOUT_MS / 60_000} ` + - `minutes (it is still running there; ask again and it will be cached)`, - ); - } - await new Promise((r) => setTimeout(r, POLL_MS)); - const poll = await ask(`${editorUrl}/api/media/fetch-window/${jobId}`, { headers }); - const j = await poll.json().catch(() => ({})); - if (!poll.ok) die(`polling editor job ${jobId} failed (HTTP ${poll.status}): ${j.error ?? ""}`); + await sleep(last === "queued" ? QUEUED_POLL_MS : POLL_MS); + const j = await pollJob(jobId); if (j.status !== last) { last = j.status; EMIT("note", { message: ` editor job ${jobId}: ${j.status}` }); } + if (j.status === "queued") place = await notePlace(jobId, "", place); if (j.status === "done") { EMIT("fetch", { id: entry.id, video: entry.video, from, to, cached: true }); EMIT("done", { out: j.file ?? null, fetchStart: j.from ?? from, cached: false, ...heightOf(j) }); diff --git a/umtool/report-to-video/fetch-via-editor.test.mjs b/umtool/report-to-video/fetch-via-editor.test.mjs @@ -1,12 +1,14 @@ // fetch-via-editor.mjs's --max-height: checked before any request, sent with a -// window and with --full, and a reported height comes back on `done`. +// window and with --full, and a reported height comes back on `done`. And the +// wait: no timeout, the job's queue place said as it moves, unanswered polls +// retried, Ctrl-C a clean stop. // // The editor is a scripted HTTP server on a loopback port: no corpus, no // yt-dlp, nothing fetched. // // Run with: pnpm test:scripts import assert from "node:assert/strict"; -import { execFile } from "node:child_process"; +import { execFile, spawn } from "node:child_process"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import http from "node:http"; import os from "node:os"; @@ -116,3 +118,159 @@ test("no --max-height sends none; a bad one is refused before any request", asyn await ed.close(); } }); + +// ---- the wait ------------------------------------------------------------------ + +/** + * An editor that queues the window (202) and answers the job's two routes from + * scripts: `polls` for /api/media/fetch-window/<id> (one entry per poll, the + * last repeated; `"drop"` destroys the connection unanswered), `places` for + * /api/ops/job/<id> (the same). + */ +async function queueingEditor({ polls, places = [], post = { jobId: "job1" } }) { + const seen = { polls: 0, places: 0, auth: new Set() }; + const server = http.createServer((req, res) => { + seen.auth.add(req.headers.authorization); + const send = (status, body) => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(JSON.stringify(body)); + }; + if (req.method === "POST") { + req.resume(); + req.on("end", () => send(202, { ok: true, ...post })); + return; + } + if (req.url.startsWith("/api/media/fetch-window/")) { + const p = polls[Math.min(seen.polls++, polls.length - 1)]; + if (p === "drop") return req.socket.destroy(); + return send(p.http ?? 200, p); + } + if (req.url.startsWith("/api/ops/job/")) { + const q = places[Math.min(seen.places++, places.length - 1)]; + return q ? send(200, { ok: true, job: { id: "job1", status: "queued", queue: q } }) : send(404, { ok: false }); + } + send(404, {}); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const { port } = /** @type {import("node:net").AddressInfo} */ (server.address()); + return { seen, url: `http://127.0.0.1:${port}`, close: () => new Promise((r) => server.close(r)) }; +} + +/** Run the script with a fast poll; resolves with its exit code and events. */ +async function runWait(editorUrl, { extra = [], onEvent } = {}) { + const dir = await mkdtemp(path.join(os.tmpdir(), "fetch-via-editor-wait-")); + const manifest = path.join(dir, "video.manifest.json"); + await writeFile(manifest, JSON.stringify(MANIFEST)); + try { + return await new Promise((resolve) => { + const child = spawn(process.execPath, [SCRIPT, manifest, "--fetch-only", "c01", "--progress", "ndjson", ...extra], { + env: { ...process.env, ARCHILYZER_EDITOR_URL: editorUrl, WORKER_TOKEN: "tok", FETCH_VIA_EDITOR_POLL_MS: "5" }, + }); + const events = []; + let buf = ""; + child.stdout.on("data", (c) => { + buf += c; + let i; + while ((i = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, i); + buf = buf.slice(i + 1); + if (!line) continue; + const e = JSON.parse(line); + events.push(e); + onEvent?.(e, child); + } + }); + child.on("close", (code, signal) => resolve({ code, signal, events })); + }); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +test("a queued window is waited for with no timeout, its place in the editor's queue said as it moves", async () => { + const queued = { status: "queued", jobId: "job1" }; + const ed = await queueingEditor({ + polls: [...Array(12).fill(queued), { status: "running" }, { status: "done", file: "/corpus/w.mp4", from: 7, to: 23 }], + places: [ + { key: "clips:youtube.com", position: 3, queued: 3, head: { id: "j0", kind: "persist-videos", channelSlug: "big-channel" } }, + { key: "clips:youtube.com", position: 3, queued: 3, head: { id: "j0", kind: "persist-videos", channelSlug: "big-channel" } }, + { key: "clips:youtube.com", position: 2, queued: 2 }, + { key: "clips:youtube.com", position: 1, queued: 1 }, + ], + }); + try { + const { code, events } = await runWait(ed.url); + assert.equal(code, 0); + const notes = events.filter((e) => e.ev === "note").map((e) => e.message); + const places = notes.filter((m) => /queued — position/.test(m)); + assert.deepEqual(places, [ + " editor job job1: queued — position 3 of 3 on clips:youtube.com, behind persist-videos (big-channel)", + " editor job job1: queued — position 2 of 2 on clips:youtube.com", + " editor job job1: queued — position 1 of 1 on clips:youtube.com", + ]); + assert.ok(notes.includes(" editor job job1: running")); + const done = events.find((e) => e.ev === "done"); + assert.equal(done.out, "/corpus/w.mp4"); + assert.equal(done.fetchStart, 7); + assert.deepEqual([...ed.seen.auth], ["Bearer tok"], "every route is asked with the token"); + } finally { + await ed.close(); + } +}); + +test("an editor without the job route: the wait goes on, without a place", async () => { + const ed = await queueingEditor({ polls: [{ status: "queued" }, { status: "queued" }, { status: "done", file: "/c/w.mp4", from: 1 }] }); + try { + const { code, events } = await runWait(ed.url); + assert.equal(code, 0); + assert.ok(!events.some((e) => e.ev === "note" && /position/.test(e.message))); + assert.equal(events.at(-1).ev, "done"); + } finally { + await ed.close(); + } +}); + +test("a poll the editor drops is retried; an answer that refuses still ends the wait", async () => { + const ok = await queueingEditor({ polls: ["drop", "drop", { status: "running" }, { status: "done", file: "/c/w.mp4", from: 1 }] }); + try { + const { code } = await runWait(ok.url); + assert.equal(code, 0); + assert.ok(ok.seen.polls >= 4); + } finally { + await ok.close(); + } + const refused = await queueingEditor({ polls: [{ http: 404, error: "no such job" }] }); + try { + const { code, events } = await runWait(refused.url); + assert.equal(code, 1); + assert.ok(events.some((e) => e.ev === "note" && /polling editor job job1 failed \(HTTP 404\): no such job/.test(e.message))); + } finally { + await refused.close(); + } +}); + +test("Ctrl-C stops the wait (exit 130), saying the job keeps running on the editor", async () => { + const ed = await queueingEditor({ polls: [{ status: "queued" }], places: [{ key: "clips:youtube.com", position: 5, queued: 5 }] }); + try { + const { code, events } = await runWait(ed.url, { + onEvent: (e, child) => { + if (e.ev === "note" && /position 5/.test(e.message)) child.kill("SIGINT"); + }, + }); + assert.equal(code, 130); + assert.ok(events.some((e) => e.ev === "note" && /^stopped waiting; editor job\(s\) job1 keep running there/.test(e.message))); + } finally { + await ed.close(); + } +}); + +test("a window already being fetched (the editor's dedupe) is followed, and says so", async () => { + const ed = await queueingEditor({ post: { jobId: "job9", existing: true }, polls: [{ status: "done", file: "/c/w.mp4", from: 2 }] }); + try { + const { code, events } = await runWait(ed.url); + assert.equal(code, 0); + assert.ok(events.some((e) => e.ev === "note" && e.message === " queued on the editor as job job9 (already asked for; following it)")); + } finally { + await ed.close(); + } +});