commit 5c0dfc61191d69d55281efa456d7b44cb4bb1d01
parent bc71d1e1f3f669ca72ccdd35ceb0e7a6d2c0b861
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 22:55:38 -0500
x-trending review 2 (N2, N4, N7): the cooldown is always recorded and never settled early; a reparse reads the record as it is
N2: a 429 records X's cooldown before the outcome is decided, so a parse that also
failed cannot send the next read straight back to X; the error's sentence says X is
left alone and until when.
N4: a clean read no longer calls recordPlatformClean("twitter"). That entry is
shared with the download lane's X units, whose hold and pace a trending read has no
business easing; a cooldown this job set ends at its `until`.
N7: a reparse re-reads read.json inside the job (the plan's copy could be the one
the read wrote when it started), and a reparse of a read still in flight is refused
at enqueue; one that died unfinished is allowed.
read.json and the result name the operation and status of the first answer that
stopped a read (`stoppedBy`), and the 429 / 403 sentences name the operation.
Every test was seen red first.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
5 files changed, 164 insertions(+), 19 deletions(-)
diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts
@@ -59,7 +59,7 @@ async function run(
const notes: Array<Record<string, unknown>> = [];
const log: string[] = [];
let limited = 0;
- let cleaned = 0;
+ const cleaned = 0;
const at = Date.parse(over.at ?? "2026-11-17T10:00:00.000Z");
const page = fakeTrendingPage(() => ({ trending }));
const result = await runXTrendingRead({
@@ -70,7 +70,6 @@ async function run(
openPage: over.openPage ?? (async () => ({ page, close: async () => {} })),
held: over.held ?? (async () => null),
noteRateLimit: async () => (limited++, at + 15 * 60_000),
- noteClean: async () => void cleaned++,
...(over.ingest ? { ingest: over.ingest } : {}),
pauseMs: () => 0,
pause: async () => {},
@@ -321,10 +320,9 @@ test("X cooling down after a rate limit refuses a read at enqueue and at its sta
assert.equal(existsSync(path.join(root(paths), "trending")), false);
});
-test("a clean read settles X's cooldown; the real cooldown is 15 minutes on the twitter platform entry", async () => {
+test("a clean read records no rate limit; the real cooldown is 15 minutes on the twitter platform entry", async () => {
const paths = corpus("clean");
- const { cleaned, limited } = await run(paths, fixtureTrendingResponses());
- assert.equal(cleaned, 1);
+ const { limited } = await run(paths, fixtureTrendingResponses());
assert.equal(limited, 0);
const { X_RATE_LIMIT_HOLD_MS } = await import("./readXTrending");
assert.equal(X_RATE_LIMIT_HOLD_MS, 15 * 60_000);
@@ -340,7 +338,7 @@ test("a 403 fails with its own sentence, keeps what was read, and raises no logi
assert.equal(result.ok, false);
assert.equal(result.outcome, "forbidden");
assert.equal(result.scrolls, 0);
- assert.match(result.sentence, /^X answered 403 \(forbidden\) to the page's own request: the read stopped at once/);
+ assert.match(result.sentence, /^X answered 403 \(forbidden\) to the page's own request \(ExampleTrendTimeline\): the read stopped at once/);
assert.match(result.sentence, /3 posts read before it were kept \(3 new\)\./);
assert.match(result.sentence, /not taken for a lost login and no alert was raised/);
assert.deepEqual(notes, []);
@@ -435,3 +433,83 @@ test("the captures are never committed: the reads directory ignores everything u
// And it is not taken for a read.
assert.deepEqual((await listXTrending(root(paths))).reads, [READ_1]);
});
+
+// --- review 2 ---------------------------------------------------------------
+
+test("N2: a 429 leaves X alone even when the posts then cannot be written", async () => {
+ const paths = corpus("limited-and-broken");
+ const f = fixtureTrendingResponses();
+ const { result, limited } = await run(
+ paths,
+ { load: [f.load[1], { url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 429, text: "" }], scrolls: f.scrolls },
+ {},
+ { ingest: (async () => { throw new Error("EACCES: permission denied"); }) as never },
+ );
+ assert.equal(limited, 1, "the cooldown was recorded");
+ assert.equal(result.ok, false);
+ assert.equal(result.outcome, "error");
+ assert.match(result.sentence, /its posts could not be written: EACCES: permission denied\./);
+ assert.match(result.sentence, /X also answered 429 \(rate limit\): no trending read starts before 10:15 UTC \(15 min\)\./);
+});
+
+test("read.json names the operation and status that stopped a read", async () => {
+ const paths = corpus("stopped-by");
+ const f = fixtureTrendingResponses();
+ const { result } = await run(paths, {
+ load: [f.load[1], { url: "https://x.com/i/api/graphql/q9/ExamplePeripheralOp?variables=%7B%7D", status: 403, body: { errors: [] } }],
+ scrolls: f.scrolls,
+ });
+ assert.deepEqual(result.stoppedBy, { op: "ExamplePeripheralOp", status: 403 });
+ const record = await readXTrendingReadRecord(root(paths), READ_1);
+ assert.deepEqual(record?.stoppedBy, { op: "ExamplePeripheralOp", status: 403 });
+ assert.match(result.sentence, /^X answered 403 \(forbidden\) to the page's own request \(ExamplePeripheralOp\)/);
+ // A read nothing stopped names none.
+ const clean = await run(paths, fixtureTrendingResponses(), {}, { readId: READ_2 });
+ assert.equal(clean.result.stoppedBy, undefined);
+ assert.equal((await readXTrendingReadRecord(root(paths), READ_2))?.stoppedBy, undefined);
+});
+
+test("N7: a reparse planned while the read was unfinished parses the record as it is when the job runs", async () => {
+ const paths = corpus("stale-plan");
+ // The plan is made from the record a read writes when it STARTS.
+ let planned: Awaited<ReturnType<typeof planReadXTrending>> | null = null;
+ const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() }));
+ await run(paths, fixtureTrendingResponses(), { probe: true }, {
+ openPage: (async () => {
+ planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 });
+ return { page, close: async () => {} };
+ }) as never,
+ });
+ assert.ok(planned && (planned as { ok: boolean }).ok);
+ const plan = (planned as unknown as { plan: { record: { stop: string } } }).plan;
+ assert.equal(plan.record.stop, "started");
+ // The read has finished since. The reparse must not put the stale record back.
+ const reparsed = await reparseXTrendingRead({ plan: plan as never });
+ assert.equal(reparsed.ok, true);
+ const record = await readXTrendingReadRecord(root(paths), READ_1);
+ assert.equal(record?.stop, "idle");
+ assert.equal(record?.scrolls, 3);
+ assert.equal(record?.responses, 4);
+ assert.equal(record?.probe, true);
+ assert.equal(record?.outcome, "read");
+ assert.equal(record?.shot, true);
+});
+
+test("N7: a reparse of a read that is still running is refused; of one that died unfinished, allowed", async () => {
+ const paths = corpus("running");
+ let running: Awaited<ReturnType<typeof planReadXTrending>> | null = null;
+ let dead: Awaited<ReturnType<typeof planReadXTrending>> | null = null;
+ const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() }));
+ await run(paths, fixtureTrendingResponses(), {}, {
+ openPage: (async () => {
+ running = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => true });
+ dead = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => false });
+ return { page, close: async () => {} };
+ }) as never,
+ });
+ assert.deepEqual(running, {
+ ok: false,
+ error: `Read ${READ_1} is still running: parse it again once it has finished (its job is on /jobs).`,
+ });
+ assert.equal((dead as unknown as { ok: boolean }).ok, true);
+});
diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts
@@ -39,7 +39,6 @@ import { noteXServiceOutcome } from "../lib/serviceCookies-server";
import {
heldPlatformRefusal,
platformCooldownRemainingMs,
- recordPlatformClean,
recordPlatformCooldown,
} from "../jobs/downloadBackoff";
import {
@@ -174,7 +173,14 @@ function recordlessRead(readId: string, ref: XTrendingRef, at: string): XTrendin
export async function planReadXTrending(
paths: Paths,
ask: ReadXTrendingAsk,
- deps: { hasProfile?: () => Promise<boolean>; held?: () => Promise<string | null> } = {},
+ deps: {
+ hasProfile?: () => Promise<boolean>;
+ held?: () => Promise<string | null>;
+ // Whether a read-x-trending job of this library is queued or running
+ // (the editor asks its registry): a record still marked "started" then
+ // belongs to a read in flight, not to one that died.
+ readInFlight?: () => Promise<boolean>;
+ } = {},
): Promise<{ ok: true; plan: ReadXTrendingPlan } | { ok: false; error: string }> {
const fail = (error: string) => ({ ok: false as const, error });
// The slug becomes a path below: checked here, whoever the caller is.
@@ -221,6 +227,11 @@ export async function planReadXTrending(
}
record = recordlessRead(ask.reparse, ref, saved.mtime.toISOString());
}
+ // A read that has not ended (review 2 N7): its record is the one written
+ // when it started, and its capture is still being written.
+ if (record.stop === "started" && (await deps.readInFlight?.())) {
+ return fail(`Read ${ask.reparse} is still running: parse it again once it has finished (its job is on /jobs).`);
+ }
return { ok: true, plan: { mode: "reparse", slug: ask.slug, channelRoot, record, ...(topic ? { topic } : {}) } };
}
if (hasReparse) return fail(`Give "url" (a trending page to read) or "reparse" (a saved read's id), one of them.`);
@@ -259,6 +270,8 @@ export type ReadXTrendingResult = {
outcome: XTrendingReadOutcome;
stop?: string;
scrolls?: number;
+ // The operation and status of the first answer that stopped the read.
+ stoppedBy?: { op: string; status: number };
responses: number;
// Operation names and sizes — never a body.
operations: XTrendingReadOperation[];
@@ -333,10 +346,9 @@ export type ReadXTrendingDeps = {
profileBusy?: () => string | null;
noteOutcome?: typeof noteXServiceOutcome;
// X's cooldown: why no read may start now; a rate limit recorded (answers
- // when it ends, ms since the epoch); a clean read settling it.
+ // when it ends, ms since the epoch). Nothing settles it early: it runs out.
held?: () => Promise<string | null>;
noteRateLimit?: () => Promise<number>;
- noteClean?: () => Promise<void>;
// For tests: the capture → library step (default: ingestCapture).
ingest?: typeof ingestCapture;
};
@@ -450,6 +462,20 @@ export async function runXTrendingRead(o: {
? ` ${plural(ingested.onPage, "post")} read before it ${plan.probe ? "are in the capture" : `were kept (${ingested.added} new)`}.`
: "";
+ // A 429 LEAVES X ALONE WHATEVER ELSE WENT WRONG (review 2 N2): the cooldown
+ // is recorded before the outcome is decided, so a parse that also failed
+ // cannot send the next read straight back to X.
+ let limitedUntil: number | undefined;
+ if (page.stop === "rate-limit") {
+ limitedUntil = await (deps.noteRateLimit ?? (() => recordPlatformCooldown(X_PLATFORM, X_RATE_LIMIT_HOLD_MS, paths, now())))().catch(
+ () => now() + X_RATE_LIMIT_HOLD_MS,
+ );
+ }
+ const untilText =
+ limitedUntil === undefined ? "" : `${hhmm(limitedUntil)} UTC (${Math.ceil((limitedUntil - now()) / 60_000)} min)`;
+ const leftAlone = limitedUntil === undefined ? "" : ` No trending read starts before ${untilText}`;
+ const by = page.stoppedBy ? ` (${page.stoppedBy.op})` : "";
+
let outcome: XTrendingReadOutcome;
let sentence: string;
if (walled) {
@@ -467,20 +493,18 @@ export async function runXTrendingRead(o: {
outcome = "error";
sentence =
`The page was read and saved (${plural(page.responses, "answer")}), but its posts could not be written: ${ingestError}. ` +
+ (limitedUntil === undefined ? "" : `X also answered 429 (rate limit): no trending read starts before ${untilText}. `) +
`The capture is kept (${kept}); read-x-trending {"reparse": "${readId}"} parses it again without asking X.`;
} else if (page.stop === "rate-limit") {
outcome = "rate-limit";
- const until = await (deps.noteRateLimit ?? (() => recordPlatformCooldown(X_PLATFORM, X_RATE_LIMIT_HOLD_MS, paths, now())))().catch(
- () => now() + X_RATE_LIMIT_HOLD_MS,
- );
sentence =
- "X answered 429 (rate limit) to the page's own request: the read stopped at once and asked nothing more." +
+ `X answered 429 (rate limit) to the page's own request${by}: the read stopped at once and asked nothing more.` +
readSoFar +
- ` No trending read starts before ${hhmm(until)} UTC (${Math.ceil((until - now()) / 60_000)} min); nothing retries by itself. The capture is kept (${kept}).`;
+ `${leftAlone}; nothing retries by itself. The capture is kept (${kept}).`;
} else if (page.stop === "forbidden") {
outcome = "forbidden";
sentence =
- "X answered 403 (forbidden) to the page's own request: the read stopped at once and asked nothing more." +
+ `X answered 403 (forbidden) to the page's own request${by}: the read stopped at once and asked nothing more.` +
readSoFar +
" The page did not show the login wall, so this is not taken for a lost login and no alert was raised; " +
`if it happens again, Check login on /cookies. The capture is kept (${kept}).`;
@@ -516,8 +540,9 @@ export async function runXTrendingRead(o: {
// A clean request: a raised X alert it would clear is cleared.
const cleared = await note(paths, { url: plan.ref.url, channel: plan.slug });
if (cleared) log(cleared);
- // And X's cooldown, when an earlier rate limit left one behind.
- await (deps.noteClean ?? (async () => void (await recordPlatformClean(X_PLATFORM, paths))))().catch(() => {});
+ // The platform's backoff is NOT settled here (review 2 N4): that entry is
+ // shared with the download lane's X units, whose hold and pace are theirs
+ // to ease. A cooldown this job set ends at its `until`.
}
const ok = outcome === "read" || outcome === "probe" || outcome === "nothing-recognised";
const record: XTrendingReadRecord = {
@@ -541,6 +566,7 @@ export async function runXTrendingRead(o: {
posts: { onPage: ingested.onPage, added: ingested.added },
...(ingested.topic ? { topic: { id: ingested.topic.id, title: ingested.topic.title } } : {}),
shot: page.shot,
+ ...(page.stoppedBy ? { stoppedBy: page.stoppedBy } : {}),
sentence,
};
await writeXTrendingReadRecord(plan.channelRoot, record);
@@ -551,6 +577,7 @@ export async function runXTrendingRead(o: {
outcome,
stop: page.stop,
scrolls: page.scrolls,
+ ...(page.stoppedBy ? { stoppedBy: page.stoppedBy } : {}),
responses: page.responses,
operations: ingested.operations,
posts: { onPage: ingested.onPage, added: ingested.added },
@@ -569,7 +596,11 @@ export async function reparseXTrendingRead(o: {
}): Promise<ReadXTrendingResult> {
const { plan } = o;
const log = o.onLog ?? (() => {});
- const record = plan.record;
+ // THE RECORD AS IT IS NOW (review 2 N7), not as the plan saw it: the plan
+ // may have been made while the read was still running, and a reparse that
+ // wrote the plan's copy back would replace the read's final record with the
+ // 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 };
const walled = record.outcome === "login-wall";
const ingested = await ingestCapture({
diff --git a/common/controller/xTrendingCooldown.test.ts b/common/controller/xTrendingCooldown.test.ts
@@ -40,3 +40,32 @@ test("no cooldown: a read may start; after a 429: refused until the minute it na
await recordPlatformClean("twitter", paths);
assert.equal(await xTrendingHeld(paths), null);
});
+
+// Review 2 N4: a clean trending read settles nothing on the platform. The
+// download lane's own backoff and pace for X are its own; the read's cooldown
+// simply runs out.
+test("N4: a clean read leaves the download lane's X backoff exactly as it was", async () => {
+ const { mkdirSync, writeFileSync: write } = await import("node:fs");
+ const { recordDownloadBackoff } = await import("../jobs/downloadBackoff");
+ const { planReadXTrending, runXTrendingRead } = await import("./readXTrending");
+ const { fakeTrendingPage } = await import("../social/fakeXProfileBrowser");
+ const { FIXTURE_TREND_URL, fixtureTrendingResponses } = await import("../social/__fixtures__/xTrendingCapture");
+ const paths = getPaths();
+ mkdirSync(path.join(paths.channelsDir, "trending"), { recursive: true });
+ write(path.join(paths.channelsDir, "trending", "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }));
+ // The lane met a rate limit on X for its own reason.
+ await recordDownloadBackoff("twitter", paths, "rate_limit");
+ const before = await platformCooldownRemainingMs("twitter", paths);
+ assert.ok(before > 0);
+ const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL }, { hasProfile: async () => true, held: async () => null });
+ assert.ok(planned.ok && planned.plan.mode === "read");
+ const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() }));
+ const result = await runXTrendingRead({
+ paths,
+ plan: planned.plan as never,
+ deps: { openPage: async () => ({ page, close: async () => {} }), pauseMs: () => 0, pause: async () => {}, held: async () => null, noteOutcome: async () => null },
+ });
+ assert.equal(result.outcome, "read");
+ const after = await platformCooldownRemainingMs("twitter", paths);
+ assert.ok(after > 0 && after <= before, `the lane's cooldown stands (${before} → ${after})`);
+});
diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts
@@ -437,6 +437,9 @@ export type XTrendingReadRecord = {
scrolls: number;
// Why the scrolling stopped (xTrendingRead.ts TrendingReadStop).
stop: string;
+ // The operation and HTTP status of the first answer that stopped it (a
+ // 429, a 403 or a 401), when one did.
+ stoppedBy?: { op: string; status: number };
outcome: XTrendingReadOutcome;
responses: number;
saved: number;
diff --git a/common/social/xTrendingRead.ts b/common/social/xTrendingRead.ts
@@ -101,6 +101,9 @@ export type TrendingPageRead = {
// page.png was written.
shot: boolean;
error?: string;
+ // The FIRST answer that stopped the read — a 429, a 403 or a 401 — by its
+ // operation and status, so a read's record says which request it was.
+ stoppedBy?: { op: string; status: number };
};
// `kill` ends the browser when `close` does not answer (optional: a fake has none).
@@ -257,6 +260,7 @@ export async function readXTrendingPage(o: {
if (status === 429) rateLimited = true;
if (status === 401) unauthorized = true;
if (status === 403) forbidden = true;
+ if ((status === 429 || status === 401 || status === 403) && !out.stoppedBy) out.stoppedBy = { op, status };
const base = { n: ++n, at: new Date(now()).toISOString(), op, status, url };
const task = (async () => {
let text: string;