Archilyzer · Source

archilyzer

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

commit 342830629fb66ab932e071a47b4cb1eafccbd195
parent 2c4281327ee4518c4c010adbe3de833061730d3d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 02:00:31 -0500

x-trending: a hung browser is killed by its checked pid; a reparse refuses inside the job too

The trending reader's kill was a close of a browser object Playwright does not give a persistent context. It is now the process itself: the pid in the profile's own SingletonLock, signalled only when /proc/<pid>/cmdline names this exact profile directory as its user-data-dir, checked immediately before the signal. Off Linux, or when the check does not hold, nothing is killed, the context is closed again and the job log says why. A reparse asks again inside its job whether the read whose capture it would parse is still running, and parses nothing if so.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/controller/readXTrending.test.ts | 34++++++++++++++++++++++++++++++++++
Mcommon/controller/readXTrending.ts | 23+++++++++++++++++++++++
Acommon/social/profileBrowserPid.test.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/profileBrowserPid.ts | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xTrendingRead.test.ts | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xTrendingRead.ts | 30+++++++++++++++++++++++-------
Meditor/app/channels/[slug]/xTrendingActions.ts | 3++-
7 files changed, 311 insertions(+), 8 deletions(-)

diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts @@ -521,3 +521,37 @@ test("N7: a reparse of a read that is still running is refused; of one that died }); assert.equal((dead as unknown as { ok: boolean }).ok, true); }); + +// Lane x-trending-2: the same refusal INSIDE the job. +test("a reparse whose read is still running when the job starts parses nothing and leaves the read's record alone", async () => { + const paths = corpus("running-in-job"); + const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); + let inJob: Awaited<ReturnType<typeof reparseXTrendingRead>> | null = null; + let recordThen: unknown = null; + await run(paths, fixtureTrendingResponses(), {}, { + openPage: (async () => { + // Planned as though no read were in flight (the plan can be old) — and + // run while the read is: the job itself refuses. + const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => false }); + assert.equal(planned.ok, true); + if (planned.ok && planned.plan.mode === "reparse") { + inJob = await reparseXTrendingRead({ plan: planned.plan, readInFlight: async () => true }); + recordThen = await readXTrendingReadRecord(root(paths), READ_1); + } + return { page, close: async () => {} }; + }) as never, + }); + const refused = inJob as unknown as { ok: boolean; outcome: string; sentence: string; posts: { onPage: number; added: number } }; + assert.equal(refused.ok, false); + assert.equal(refused.outcome, "error"); + assert.match(refused.sentence, new RegExp(`^Read ${READ_1} is still running: its capture is still being written\\..*Nothing was parsed or written\\.$`)); + assert.deepEqual(refused.posts, { onPage: 0, added: 0 }); + assert.equal((recordThen as { stop: string }).stop, "started"); + // Once the read has ended, the same reparse goes through. + const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => false }); + assert.equal(planned.ok, true); + if (planned.ok && planned.plan.mode === "reparse") { + const done = await reparseXTrendingRead({ plan: planned.plan, readInFlight: async () => true }); + assert.equal(done.ok, true); + } +}); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -614,6 +614,11 @@ export async function reparseXTrendingRead(o: { plan: Extract<ReadXTrendingPlan, { mode: "reparse" }>; onLog?: (line: string) => void; now?: () => number; + // Whether a read of this library is queued or running NOW (the editor asks + // its registry). Asked INSIDE the job too (lane x-trending-2), not only at + // enqueue: a reparse moved to another queue can start beside the read whose + // capture it would parse half-written. + readInFlight?: () => Promise<boolean>; }): Promise<ReadXTrendingResult> { const { plan } = o; const log = o.onLog ?? (() => {}); @@ -623,6 +628,24 @@ export async function reparseXTrendingRead(o: { // one it started with. (The plan's is used only for a read that has none.) const record = (await readXTrendingReadRecord(plan.channelRoot, plan.record.id)) ?? plan.record; const ref: XTrendingRef = { trendId: record.trendId, url: record.url }; + if (record.stop === "started" && (await o.readInFlight?.())) { + const sentence = `Read ${record.id} is still running: its capture is still being written. Parse it again once it has finished (its job is on /jobs). Nothing was parsed or written.`; + log(sentence); + return { + ok: false, + slug: plan.slug, + mode: "reparse", + url: record.url, + trendId: record.trendId, + read: record.id, + outcome: "error", + responses: 0, + operations: [], + posts: { onPage: 0, added: 0 }, + sentence, + error: sentence, + }; + } const walled = record.outcome === "login-wall"; const ingested = await ingestCapture({ channelRoot: plan.channelRoot, diff --git a/common/social/profileBrowserPid.test.ts b/common/social/profileBrowserPid.test.ts @@ -0,0 +1,96 @@ +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/profileBrowserPid.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { spawn, type ChildProcess } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { killProfileBrowser, profileBrowserPid } from "./profileBrowserPid"; + +const TMP = mkdtempSync(path.join(tmpdir(), "profile-pid-")); +const children: ChildProcess[] = []; +after(() => { + for (const c of children) if (c.pid !== undefined && c.exitCode === null) c.kill("SIGKILL"); + rmSync(TMP, { recursive: true, force: true }); +}); + +function profile(name: string, lock?: string): string { + const dir = path.join(TMP, name); + mkdirSync(dir, { recursive: true }); + if (lock) symlinkSync(lock, path.join(dir, "SingletonLock")); + return dir; +} + +// A process that stands in for a browser: it sleeps, with `arg` on its command line. +function sleeper(arg: string): Promise<ChildProcess> { + const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000); console.log('up')", "--", arg], { stdio: ["ignore", "pipe", "ignore"] }); + children.push(child); + return new Promise((resolve, reject) => { + child.once("error", reject); + child.stdout!.once("data", () => resolve(child)); + }); +} + +const exited = (c: ChildProcess) => new Promise<NodeJS.Signals | null>((resolve) => c.once("exit", (_code, signal) => resolve(signal))); + +const linux = process.platform === "linux"; + +test("the pid comes from the profile's own lock, and only when that process names this exact profile", async () => { + const none = profile("none"); + assert.deepEqual(await profileBrowserPid(none, { platform: "linux" }), { pid: null, why: "the profile has no browser lock (no browser holds it)" }); + const dir = profile("exact", "host-4242"); + const deps = (cmdline: string) => ({ platform: "linux", cmdline: async () => cmdline }); + assert.deepEqual(await profileBrowserPid(dir, deps(`chrome\0--headless\0--user-data-dir=${dir}\0`)), { pid: 4242 }); + // Another profile whose path merely starts the same: left alone. + const other = await profileBrowserPid(dir, deps(`chrome\0--user-data-dir=${dir}-other\0`)); + assert.equal(other.pid, null); + assert.match(other.pid === null ? other.why : "", /process 4242 does not name this profile on its command line \(a stale lock\): it is left alone/); + // The directory mentioned, but not as the profile argument. + assert.equal((await profileBrowserPid(dir, deps(`vim\0${dir}\0`))).pid, null); + // A lock whose process is gone. + const gone = await profileBrowserPid(dir, { platform: "linux", cmdline: async () => { throw new Error("ENOENT"); } }); + assert.match(gone.pid === null ? gone.why : "", /\(4242\) is gone/); + // A lock that names no usable pid: 0, 1, this process, no number. + for (const lock of ["host-0", "host-1", `host-${process.pid}`, "nonsense"]) { + const d = profile(`bad-${lock}`, lock); + assert.equal((await profileBrowserPid(d, deps(`x\0--user-data-dir=${d}\0`))).pid, null, lock); + } + // Off Linux nothing is looked for. + assert.deepEqual(await profileBrowserPid(dir, { platform: "darwin" }), { pid: null, why: "finding the browser's process is Linux-only" }); +}); + +test("a kill signals the checked pid and nothing else", async () => { + const dir = profile("kill", "host-777"); + const sent: Array<[number, string]> = []; + const kill = (pid: number, signal: NodeJS.Signals) => void sent.push([pid, signal]); + assert.deepEqual(await killProfileBrowser(dir, { platform: "linux", cmdline: async () => `c\0--user-data-dir=${dir}\0`, kill }), { killed: true, pid: 777 }); + assert.deepEqual(sent, [[777, "SIGKILL"]]); + // A stale lock: no signal at all. + const stale = await killProfileBrowser(dir, { platform: "linux", cmdline: async () => "bash\0", kill }); + assert.equal(stale.killed, false); + assert.equal(sent.length, 1); + // Off Linux: no signal, and why. + assert.deepEqual(await killProfileBrowser(dir, { platform: "win32", kill }), { killed: false, why: "finding the browser's process is Linux-only" }); + assert.equal(sent.length, 1); +}); + +test("for real: a process holding the profile is killed; one that does not name it is not", { skip: !linux }, async () => { + const dir = path.join(TMP, "real"); + mkdirSync(dir, { recursive: true }); + const holder = await sleeper(`--user-data-dir=${dir}`); + const bystander = await sleeper(`--user-data-dir=${dir}-other`); + // The lock names the bystander: nothing is killed. + symlinkSync(`host-${bystander.pid}`, path.join(dir, "SingletonLock")); + const no = await killProfileBrowser(dir); + assert.equal(no.killed, false); + assert.equal(bystander.exitCode, null); + // The lock names the holder: it is killed, the bystander is not. + rmSync(path.join(dir, "SingletonLock")); + symlinkSync(`host-${holder.pid}`, path.join(dir, "SingletonLock")); + const gone = exited(holder); + assert.deepEqual(await killProfileBrowser(dir), { killed: true, pid: holder.pid }); + assert.equal(await gone, "SIGKILL"); + assert.equal(bystander.exitCode, null); + assert.equal(bystander.signalCode, null); +}); diff --git a/common/social/profileBrowserPid.ts b/common/social/profileBrowserPid.ts @@ -0,0 +1,84 @@ +// THE BROWSER THAT HOLDS A PROFILE, BY PID (lane x-trending-2) — for ending a +// browser that no longer answers. +// +// Playwright gives a persistent context no process handle (only +// `launchServer` has `process()`), and closing a context that has stopped +// answering closes nothing: the browser keeps the profile, and every later +// read, capture, Refresh and Connect fails on Chromium's profile lock until +// somebody kills it by hand. So the pid is read where Chromium itself writes +// it: `<profile>/SingletonLock`, a symlink to `<host>-<pid>`. +// +// A PID IS ONLY EVER KILLED WHEN ITS COMMAND LINE NAMES THIS EXACT PROFILE +// DIRECTORY (`--user-data-dir=<profile>` as one argument of +// `/proc/<pid>/cmdline`), checked again immediately before the signal: a stale +// lock whose pid now belongs to another process, or a lock of another profile, +// is never signalled. Linux only (it reads /proc); anywhere else, and whenever +// the check does not hold, nothing is killed and the caller is told why — it +// falls back to closing, and says so in the job's log. +// +// `process.kill(pid)` on a checked pid, never a child's `.kill()` and never a +// process group. + +import { readFile, readlink } from "node:fs/promises"; +import path from "node:path"; + +export type ProfileBrowserPidDeps = { + platform?: string; + readlink?: (file: string) => Promise<string>; + // /proc/<pid>/cmdline, raw (arguments separated by NUL). + cmdline?: (pid: number) => Promise<string>; + kill?: (pid: number, signal: NodeJS.Signals) => void; + selfPid?: number; +}; + +export type ProfileBrowserPid = { pid: number } | { pid: null; why: string }; + +const realCmdline = (pid: number) => readFile(`/proc/${pid}/cmdline`, "utf8"); + +// The pid of the browser holding `profileDir`, checked against its command +// line — or why there is none to name. +export async function profileBrowserPid(profileDir: string, deps: ProfileBrowserPidDeps = {}): Promise<ProfileBrowserPid> { + if ((deps.platform ?? process.platform) !== "linux") { + return { pid: null, why: "finding the browser's process is Linux-only" }; + } + const dir = path.resolve(profileDir); + let target: string; + try { + target = await (deps.readlink ?? readlink)(path.join(dir, "SingletonLock")); + } catch { + return { pid: null, why: "the profile has no browser lock (no browser holds it)" }; + } + const m = /-(\d{1,10})$/.exec(target); + const pid = m ? Number(m[1]) : NaN; + if (!Number.isInteger(pid) || pid <= 1 || pid === (deps.selfPid ?? process.pid)) { + return { pid: null, why: "the profile's lock names no browser process" }; + } + let cmdline: string; + try { + cmdline = await (deps.cmdline ?? realCmdline)(pid); + } catch { + return { pid: null, why: `the process the profile's lock names (${pid}) is gone` }; + } + const args = cmdline.split("\0"); + // The exact directory, as one argument: never a prefix of another profile's path. + const names = args.some((a) => a.startsWith("--user-data-dir=") && path.resolve(a.slice("--user-data-dir=".length)) === dir); + if (!names) { + return { pid: null, why: `process ${pid} does not name this profile on its command line (a stale lock): it is left alone` }; + } + return { pid }; +} + +export type KilledProfileBrowser = { killed: true; pid: number } | { killed: false; why: string }; + +// SIGKILL to the browser holding `profileDir` — only to a pid that passes the +// check above, taken again here, immediately before the signal. +export async function killProfileBrowser(profileDir: string, deps: ProfileBrowserPidDeps = {}): Promise<KilledProfileBrowser> { + const found = await profileBrowserPid(profileDir, deps); + if (found.pid === null) return { killed: false, why: found.why }; + try { + (deps.kill ?? ((pid, signal) => void process.kill(pid, signal)))(found.pid, "SIGKILL"); + } catch (err) { + return { killed: false, why: `process ${found.pid} could not be signalled (${(err as Error).message.split("\n")[0]})` }; + } + return { killed: true, pid: found.pid }; +} diff --git a/common/social/xTrendingRead.test.ts b/common/social/xTrendingRead.test.ts @@ -497,3 +497,52 @@ test("N3: a call bounded on a signal already aborted leaves no unhandled rejecti process.off("unhandledRejection", onUnhandled); } }); + +// Lane x-trending-2: a browser that will not close is killed by its checked pid. +test("kill ends the browser's own process when its pid checks out; else it says why and closes again", async () => { + const profileDir = path.join(TMP, "killable", ".x-session", "profile"); + const stub = stubChromium(); + const log: string[] = []; + const sent: Array<[number, string]> = []; + const session = await openXTrendingPage(paths("killable"), { + chromium: stub.chromium, + onLog: (l) => log.push(l), + killDeps: { + platform: "linux", + readlink: async (file) => { + assert.equal(file, path.join(profileDir, "SingletonLock")); + return "host-31337"; + }, + cmdline: async () => `chrome\0--user-data-dir=${profileDir}\0`, + kill: (pid, signal) => void sent.push([pid, signal]), + }, + }); + await session.kill!(); + assert.deepEqual(sent, [[31337, "SIGKILL"]]); + assert.ok(log.some((l) => l === "Killed the browser that held the X profile (pid 31337): the profile is free again."), log.join("\n")); + + // A lock whose process does not name this profile: never signalled; closed again, and said. + let closes = 0; + const other = stubChromium(); + const real = other.chromium.launchPersistentContext; + other.chromium.launchPersistentContext = async (dir, opts) => { + const context = await real(dir, opts); + return { ...context, close: async () => void closes++ }; + }; + const log2: string[] = []; + const stale = await openXTrendingPage(paths("stale"), { + chromium: other.chromium, + onLog: (l) => log2.push(l), + killDeps: { platform: "linux", readlink: async () => "host-31337", cmdline: async () => "bash\0", kill: (pid, signal) => void sent.push([pid, signal]) }, + }); + await stale.kill!(); + assert.equal(sent.length, 1); + assert.equal(closes, 1); + assert.ok(log2.some((l) => /^The browser was not killed \(process 31337 does not name this profile on its command line \(a stale lock\): it is left alone\); closing it again instead\.$/.test(l)), log2.join("\n")); + + // Off Linux: the same fallback. + const log3: string[] = []; + const mac = await openXTrendingPage(paths("mac"), { chromium: stubChromium().chromium, onLog: (l) => log3.push(l), killDeps: { platform: "darwin" } }); + await mac.kill!(); + assert.ok(log3.some((l) => /not killed \(finding the browser's process is Linux-only\); closing it again instead/.test(l))); +}); diff --git a/common/social/xTrendingRead.ts b/common/social/xTrendingRead.ts @@ -31,8 +31,9 @@ // The caller (controller/readXTrending.ts) is one editor job on X's queue; // this module knows nothing of queues, alerts or the store. -// A browser that will not close is killed (`session.kill`): the guard every -// module that kills a process installs (lib/childKillGuard.test.ts). +// A browser that will not close is killed (`session.kill`, by a checked pid: +// profileBrowserPid.ts): the guard every module that kills a process installs +// (lib/childKillGuard.test.ts). import "../lib/childKillGuard"; import { appendFile, mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; @@ -45,6 +46,7 @@ import { import { importPlaywright, type ChromiumLike, type PageLike } from "./playwrightRuntime"; import { launchHeadedContext, type HeadedDisplayLaunchDeps } from "./headedDisplay"; import { findXBrowser } from "./xBrowser"; +import { killProfileBrowser, type ProfileBrowserPidDeps } from "./profileBrowserPid"; import { launchXProfile, xProfileDir } from "./xSessionBroker"; import { xIdOf } from "./xNormalize"; import { @@ -106,7 +108,8 @@ export type TrendingPageRead = { stoppedBy?: { op: string; status: number }; }; -// `kill` ends the browser when `close` does not answer (optional: a fake has none). +// `kill` ends the browser when `close` does not answer: the process itself, +// by its checked pid (openXTrendingPage). Optional: a test's page has none. export type TrendingPageSession = { page: PageLike; close: () => Promise<void>; kill?: () => Promise<void> }; export class PageDeadlineError extends Error { @@ -406,6 +409,8 @@ export async function openXTrendingPage( onLog?: (line: string) => void; env?: Record<string, string | undefined>; display?: HeadedDisplayLaunchDeps; + // For tests: how the browser's pid is found and signalled. + killDeps?: ProfileBrowserPidDeps; } = {}, ): Promise<TrendingPageSession> { const log = o.onLog ?? (() => {}); @@ -432,12 +437,23 @@ export async function openXTrendingPage( await context.close().catch(() => {}); throw err; } - // The browser behind a persistent context, when the runtime names it: what - // `kill` closes if the context itself stops answering. - const browser = (context as { browser?: () => { close?: () => Promise<void> } | null }).browser?.() ?? null; + // A BROWSER THAT DOES NOT CLOSE IS KILLED, BY PID (lane x-trending-2; + // profileBrowserPid.ts): the process Chromium's own lock in the profile + // names, and only when its command line names this exact profile directory. + // Off Linux, or when that check does not hold, nothing is killed: the + // context is closed again instead, and the log says which it was. + const profileDir = xProfileDir(paths); return { page, close: () => context.close(), - ...(browser?.close ? { kill: () => browser.close!() } : {}), + kill: async () => { + const r = await killProfileBrowser(profileDir, o.killDeps); + if (r.killed) { + log(`Killed the browser that held the X profile (pid ${r.pid}): the profile is free again.`); + return; + } + log(`The browser was not killed (${r.why}); closing it again instead.`); + await context.close(); + }, }; } diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts @@ -90,7 +90,8 @@ export async function readXTrendingAction(ask: ReadXTrendingAsk): Promise<Stream queueKey: X_TRENDING_QUEUE, paths, channelSlug: plan.slug, - fn: async (onLog) => done(onLog, await reparseXTrendingRead({ plan, onLog })), + // Asked again inside the job: the read may have started since the plan. + fn: async (onLog) => done(onLog, await reparseXTrendingRead({ plan, onLog, readInFlight })), }); } const busy = xPressInFlight();