Archilyzer · Source

archilyzer

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

commit c0b977b798422d50403dc946ec20da0f71b72040
parent ccd01947e83e401a6183bed7d66ba4580b64ff13
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 18:20:42 -0500

posts: a resumed X history walk keeps its place -- the search phase's page marker is the resume point

A long first full-history walk of an X account stopped at its 180-minute budget. Resume backfill then
read 100 posts already archived, said "caught up", wrote nothing, and the saved place was cleared.

The cause, read from gallery-dl 1.32.9's twitter extractor: its timeline extractor reads the timeline
API first (state 1, a "Cursor: 1/..." line per page) and below that goes on by search, which pages by
max_id and logs "Next 'max_id': N" and never a cursor. This side read only "Cursor:" lines, so the place
it saved for the whole search phase was the last TIMELINE page. The resume re-read the search phase from
its top, met 100 known posts (stopAtKnown was on for everything but --full), returned complete, and the
settle cleared `backfill`.

- GalleryDlStream reads the search phase's marker as a resume point, `3_<N>/`: the extractor's own
  cursor form, which makes it ask `from:<handle> max_id:<N>` afresh. A page boundary for checkpoints
  and for Drain too.
- A resumed backfill does not stop at known posts (stopAtKnown is a sync's). It says once that it is
  skipping them, and ends at the timeline's end, its budget or a cap.
- A fetch that ended at known posts says so (`caughtUp`), and settleTimelineRun never clears a
  backfill's place on it.
- A resumed backfill whose first posts are at or above the newest archived post began again from the
  top: it stops at once with a sentence and keeps its place.

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

Diffstat:
MCOMMANDS.md | 2+-
Mcommon/controller/fetchPosts.test.ts | 164++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/controller/fetchPosts.ts | 10+++++++++-
Mcommon/lib/timelineWalk.test.ts | 13+++++++++++++
Mcommon/lib/timelineWalk.ts | 9++++++++-
Mcommon/social/fetchers.ts | 9+++++++++
Mcommon/social/xGalleryDlFetcher.test.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xGalleryDlFetcher.ts | 132++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mscripts/archilyzer-ops.mjs | 6+++++-
9 files changed, 409 insertions(+), 16 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -168,7 +168,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | | `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"} is SYNC NEW — from the top of the timeline down to the newest archived post (a sync that stopped part-way continues down to the watermark it began with). It never reads or clears an unfinished backfill's resume point. "backfill": true is RESUME BACKFILL instead (the same as resume-backfill). "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full", "older" and "backfill" are one at a time. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. AN INSTAGRAM CHANNEL: a sync reads ONE page (up to 30 posts), a first fetch, "full" or "backfill" walks up to 120 posts and the next run resumes; the new posts' pictures and videos are fetched in the same job (a sync 40 files / 200 MB, a walk 120 / 600 MB, 100 MB a file; a walk leaves the posts whose media would not fit for its next run; what is still not fetched is recorded as owed, and none after a refusal). Refused before a job exists when the channel has no cookiesFromBrowser of its own, with "retryOnBlock" or "older", and with a "queueKey" other than platform:instagram. A login, challenge or checkpoint page raises Instagram's alert and refuses every Instagram job until recheck-service; the first 429 holds Instagram for an hour (clear-platform-hold {"platform": "instagram"} ends that by hand). A drained fetch stops at its next resume point and the next run of the same walk resumes there. | `pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait` | -| `resume-backfill` | resume-backfill continues a social channel's unfinished full-history timeline walk (X, Bluesky) from its saved resume point, with no watermark: {"slug"} ("limit"? caps the posts this run reads). The walk is left part-way by a first fetch, a full re-walk or a backfill that stopped; the channel page then says "backfill unfinished — N archived" and shows Resume backfill. Nothing resumes it but this (or fetch-posts "backfill": true): a plain fetch-posts, Sync and the scheduler sync new posts and keep its place. Refused when none is part-way, on a forum thread (every fetch catches up, then continues its history) and on an X search channel. | `pnpm ops resume-backfill --json '{"slug":"example-x"}' --wait` | +| `resume-backfill` | resume-backfill continues a social channel's unfinished full-history timeline walk (X, Bluesky) from its saved resume point, with no watermark: {"slug"} ("limit"? caps the posts this run reads). The walk is left part-way by a first fetch, a full re-walk or a backfill that stopped; the channel page then says "backfill unfinished — N archived" and shows Resume backfill. Nothing resumes it but this (or fetch-posts "backfill": true): a plain fetch-posts, Sync and the scheduler sync new posts and keep its place. Refused when none is part-way, on a forum thread (every fetch catches up, then continues its history) and on an X search channel. It ends only at the timeline's end, its budget or a cap: posts already archived are skipped, never taken for the end, and its place is cleared only by the timeline's end. A resume that began again from the top (the first posts read are the newest) stops at once with a sentence and keeps its place. | `pnpm ops resume-backfill --json '{"slug":"example-x"}' --wait` | | `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. An Instagram channel is refused: no screenshot is taken of an Instagram post, and its media come with the post, in the fetch-posts job. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"&lt;id&gt;": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/&lt;handle&gt;.&lt;ext&gt; + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["&lt;one of their post ids&gt;"\], "avatarsOnly": true}. X also reads each post's CONTEXT off the same page -- the post it quotes and the post it answers (its author, check, date, words, media links) -- into its capture.json's "context"; "context": false turns that off. "contextOnly": true (X) loads ONE page per post for that alone (and the avatars it shows): the context written into capture.json, nothing shot, no media, article, thread shot or availability; a post whose context is already read is skipped unless "force". Not with "avatarsOnly". Paced like a post fetch, on its queue. An X trending library is captured by this same job, under channels/&lt;slug&gt;/trending/posts-media/&lt;id&gt;/. Its media comes from X's media CDN by the addresses in the library's saved captures: no login, one file after another 1-2 s apart, under X's cooldown, each file kept once (trending/media-store/, a hardlink per post). A file over the library's maxVideoMb (100 MB) and whatever is past the job's budget (40 files / 200 MB) is owed: asked for again by the next capture of that post. A 429 from the CDN stops the job and leaves X alone for 15 minutes; a 403 or 404 marks the file; three refusals in a row (a 403, or no answer) and the job asks the CDN no more; nothing retries. "keptMedia": true is for posts marked keep (refused for any other id): no per-file cap, and a post the CDN cannot serve whole is downloaded the logged-in way, if it is still kept when that download would start. A library's capture runs on X's queue only: "queueKey" is refused for it. | | | `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "&lt;branch&gt;", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of &lt;id&gt; in &lt;dir&gt; — archilyzer publish build &lt;id&gt;". `get publish` is the status. | | | `build-index`, `build-site`, `build-deploy`, `deploy-site`, `build-hub`, `deploy-hub`, `build-homepage`, `deploy-homepage` | build-index, build-site, build-deploy, deploy-site, build-hub, deploy-hub, build-homepage and deploy-homepage are publish's aliases, with their old bodies and answers ("skipData" is accepted and ignored). | `pnpm ops build-deploy --json '{"siteIds":["anilyzer","jeralyzer"]}' --wait`<br>`pnpm ops build-site --json '{"siteId":"anilyzer"}' --wait`<br>`pnpm ops deploy-site --json '{"siteId":"anilyzer","preview":"tags-exclude"}' --wait`<br>`pnpm ops build-hub --wait`<br>`pnpm ops build-hub --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-hub --wait`<br>`pnpm ops build-homepage --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait` | diff --git a/common/controller/fetchPosts.test.ts b/common/controller/fetchPosts.test.ts @@ -48,7 +48,25 @@ const tw = (n) => '[2, {"tweet_id": ' + (1899000000000000100n - BigInt(n)) + const page = (p) => { for (let i = 0; i < 3; i++) process.stdout.write(tw(p * 3 + i)); }; const log = (l) => process.stderr.write(l + "\\n"); log("[gallery-dl][debug] Version 1.32.9"); -if (process.env.FAKE_MODE === "known") { +if (process.env.FAKE_SCRIPT) { + // A walk the TEST writes (lane x-followups): FAKE_SCRIPT is a JSON file, + // {"<the cursor given, or ''>": [step, …]}; a step is {posts: [from, to]} + // (tweets from..to, newest first, a minute apart), {err: "a stderr line"}, + // {wait: ms} or {exit: code}. A cursor the script does not know exits 9. + const { readFileSync } = await import("node:fs"); + const steps = JSON.parse(readFileSync(process.env.FAKE_SCRIPT, "utf8"))[cursor ?? ""]; + if (!steps) { log("[twitter][error] the fake knows no cursor " + cursor); process.exit(9); } + const post = (n) => '[2, {"tweet_id": ' + (1899000000000000100n - BigInt(n)) + + ', "date": "' + new Date(Date.UTC(2026, 5, 28, 12) - n * 60000).toISOString().slice(0, 19).replace("T", " ") + + '", "content": "fake ' + n + '", "author": {"name": "faketester"}, "user": {"name": "faketester"}}]\\n'; + for (const step of steps) { + if (step.posts) for (let n = step.posts[0]; n <= step.posts[1]; n++) process.stdout.write(post(n)); + if (step.err) log(step.err); + if (step.wait) await new Promise((r) => setTimeout(r, step.wait)); + if (step.exit !== undefined) process.exit(step.exit); + } + process.exit(0); +} else if (process.env.FAKE_MODE === "known") { page(0); let n = 3; // Distinct tweets from before the archive's newest post: what an incremental @@ -499,3 +517,147 @@ test("`archilyzer posts fetch` on an X channel exits 1 with the sentence naming assert.equal(ran.stdout.trim(), ""); assert.equal((await readFile(ARGS_LOG, "utf8")).trim().split("\n").length, before); }); + +// ── lane x-followups: the history walk's search phase, and a resumed backfill ── + +// A channel of its own and a walk the test writes (the fake's FAKE_SCRIPT). +async function scripted(slug: string, script: Record<string, unknown[]>) { + const root = path.join(ROOT, "transcripts", "channels", slug); + await mkdir(root, { recursive: true }); + await writeFile( + path.join(root, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", postFetcher: "x-gallery-dl", socialHandle: "faketester", platform: "twitter", name: "Fake (X)", url: "https://x.com/faketester" }), + ); + const file = path.join(ROOT, `${slug}.script.json`); + writeFileSync(file, JSON.stringify(script)); + const paths = (await import("../lib/paths")).getPaths(); + const run = async (opts: Record<string, unknown> = {}, cancelOn?: RegExp) => { + const controller = new AbortController(); + const log: string[] = []; + process.env.FAKE_SCRIPT = file; + try { + const result = await fetchPosts({ + paths, + slug, + settings: {}, + signal: controller.signal, + onLog: (line) => { + log.push(line); + if (cancelOn?.test(line)) controller.abort(); + }, + ...opts, + }); + return { result, log }; + } finally { + delete process.env.FAKE_SCRIPT; + } + }; + return { root, run }; +} +const RATE_LIMIT = { err: "[twitter][info] Waiting for 14 minutes until 15:11:22 (rate limit)" }; +const cursorArg = async () => (await lastArgv()).find((a) => a.startsWith("extractor.twitter.cursor=")); + +test("a first walk that stops in its SEARCH phase saves the search's place, and Resume backfill continues from there to the timeline's end", async () => { + const { root, run } = await scripted("search-phase", { + "": [ + // The timeline API's pages, each with its cursor… + { posts: [0, 2] }, + { err: "[twitter][debug] Cursor: 1/TL-P1" }, + { posts: [3, 5] }, + { err: "[twitter][debug] Cursor: 1/TL-P2" }, + // …then the search below it: pages by max_id, and no "Cursor:" line at all. + { posts: [6, 8] }, + { err: "[twitter][debug] Next 'max_id': 1899000000000000091" }, + { posts: [9, 11] }, + { err: "[twitter][debug] Next 'max_id': 1899000000000000088" }, + RATE_LIMIT, + { wait: 60_000 }, + ], + "3_1899000000000000088/": [{ posts: [12, 14] }, { err: "[twitter][debug] Next 'max_id': 1899000000000000085" }, { posts: [15, 15] }], + }); + const first = await run({}, /rate limit/); + assert.equal(first.result.ok, true); + assert.equal(first.result.written, 12); + assert.equal(first.result.complete, false); + // The place is the search's last page, not the timeline phase's last cursor (which lies six posts above it). + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "3_1899000000000000088/"); + + const resumed = await run({ backfill: true }); + assert.equal(await cursorArg(), "extractor.twitter.cursor=3_1899000000000000088/"); + assert.equal(resumed.result.ok, true, resumed.log.join("\n")); + assert.equal(resumed.result.written, 4); + // gallery-dl walked to the end and exited: the timeline's real end. Only that clears the place. + assert.equal(resumed.result.complete, true); + assert.equal((await readPostFetchState(root))?.backfill, undefined); + assert.equal((await readSeenPostIds(root)).size, 16); +}); + +test("a resumed backfill skips posts already archived without stopping, and never ends as \"caught up\"", async () => { + const { root, run } = await scripted("skip-known", { + "": [{ posts: [0, 149] }, { err: "[twitter][debug] Cursor: 1/TL-P1" }, RATE_LIMIT, { wait: 60_000 }], + // The place points back into what is archived (as a place saved by an older build does): 130 known posts, then new ones. + "1/TL-P1": [{ posts: [20, 149] }, { err: "[twitter][debug] Next 'max_id': 1899000000000000001" }, { posts: [150, 152] }, RATE_LIMIT, { wait: 60_000 }], + "3_1899000000000000001/": [{ posts: [153, 153] }], + }); + await run({}, /rate limit/); + assert.equal((await readSeenPostIds(root)).size, 150); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "1/TL-P1"); + + const resumed = await run({ backfill: true }, /rate limit/); + assert.equal(resumed.result.ok, true, resumed.log.join("\n")); + assert.equal(resumed.result.written, 3); + assert.equal(resumed.result.complete, false); + assert.ok(!resumed.log.some((l) => /caught up/i.test(l)), resumed.log.join("\n")); + assert.ok(resumed.log.some((l) => /100 already-archived posts in a row: this walk has no watermark, so it skips them and reads on/.test(l))); + assert.ok(resumed.log.some((l) => /gallery-dl read 133 post\(s\): 3 new, 130 already archived/.test(l)), resumed.log.join("\n")); + // Stopped part-way (cancelled here; a budget is the same path): the place moved on, and is still there. + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "3_1899000000000000001/"); + // …and the next resume ends at the timeline's end. + const last = await run({ backfill: true }); + assert.equal(last.result.complete, true); + assert.equal((await readPostFetchState(root))?.backfill, undefined); + assert.equal((await readSeenPostIds(root)).size, 154); +}); + +test("a resumed backfill that began again from the top stops with a sentence and keeps its place", async () => { + const { X_BACKFILL_RESTARTED_FROM_TOP } = await import("../social/xGalleryDlFetcher"); + const { root, run } = await scripted("top-restart", { + "": [{ posts: [0, 39] }, { err: "[twitter][debug] Cursor: 1/TL-P1" }, { posts: [40, 59] }, { err: "[twitter][debug] Cursor: 1/TL-P2" }, RATE_LIMIT, { wait: 60_000 }], + // The cursor was not honoured: the timeline from its top — a post newer than anything archived, then the archive's newest… + "1/TL-P2": [{ posts: [-1, 30] }, { err: "[twitter][debug] Cursor: 1/TL-P1" }, { posts: [31, 300] }, { wait: 60_000 }], + }); + await run({}, /rate limit/); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "1/TL-P2"); + const started = Date.now(); + const resumed = await run({ backfill: true }); + assert.ok(Date.now() - started < 30_000, "gallery-dl was stopped, not left to walk on"); + assert.equal(resumed.result.ok, false); + assert.equal(resumed.result.error, X_BACKFILL_RESTARTED_FROM_TOP); + assert.equal(resumed.result.complete, false); + assert.ok(!resumed.log.some((l) => /caught up/i.test(l))); + // The place is the one it had. + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "1/TL-P2"); + // What it read of the top that was new is kept (a post is a post); nothing else was written. + assert.equal(resumed.result.written, 1); + assert.equal((await readSeenPostIds(root)).size, 61); +}); + +test("a sync still stops at known posts, and a full re-walk still reads through them", async () => { + const { root, run } = await scripted("sync-stops", { + "": [{ posts: [0, 149] }, { err: "[twitter][debug] Cursor: 1/TL-P1" }, { posts: [150, 150] }], + }); + const first = await run({}); + assert.equal(first.result.written, 151); + assert.equal(first.result.complete, true); + // SYNC NEW: a run of archived posts is where it ends. + const sync = await run({}); + assert.ok(sync.log.some((l) => /Reached 100 already-archived posts in a row — caught up; stopping gallery-dl\./.test(l)), sync.log.join("\n")); + assert.equal(sync.result.complete, true); + assert.equal(sync.result.written, 0); + // A FULL re-walk reads through all of them, to the end. + const full = await run({ full: true }); + assert.ok(!full.log.some((l) => /caught up/i.test(l)), full.log.join("\n")); + assert.ok(full.log.some((l) => /gallery-dl read 151 post\(s\): 0 new, 151 already archived/.test(l)), full.log.join("\n")); + assert.equal(full.result.complete, true); + assert.equal((await readPostFetchState(root))?.backfill, undefined); +}); diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -743,7 +743,10 @@ async function fetchTimeline(ctx: { ...(config.postPagePauseSeconds ? { pagePauseMs: config.postPagePauseSeconds * 1000 } : {}), - stopAtKnown: !opts.full, + // Known posts end a SYNC. A full re-walk reads through them on purpose, + // and a resumed backfill has no watermark: it skips them and reads on. + stopAtKnown: !opts.full && !opts.backfill, + ...(plan?.mode === "backfill" ? { resumedBackfill: true } : {}), onCheckpoint, signal: effectiveSignal, drain: opts.drain, @@ -770,6 +773,11 @@ async function fetchTimeline(ctx: { }; } + // A backfill is not finished by meeting known posts (settleTimelineRun). + if (plan?.mode === "backfill" && result.complete && result.caughtUp) { + result = { ...result, complete: false }; + log("The backfill met posts already archived and stopped there: that is not the timeline's end. Its resume point is kept."); + } const final = await write(result.posts); for (const shard of final.shards) shards.add(shard); const written = { diff --git a/common/lib/timelineWalk.test.ts b/common/lib/timelineWalk.test.ts @@ -157,3 +157,16 @@ test("the status lines say a backfill is unfinished, and what continues a stoppe assert.equal(describeTimelineSync({}), null); assert.match(describeTimelineSync({ sync: { cursor: "1/S", since: WATERMARK } }) ?? "", /down to 2026-11-01/); }); + +// Lane x-followups: a resumed backfill re-read archived posts, was taken for finished ("caught up") +// and lost its resume point. +test("a backfill is never finished by meeting known posts: its resume point is kept", () => { + const walks = { backfill: { cursor: "3_1899000000000000041/", savedAt: "2026-11-17T00:00:00.000Z" }, sync: { cursor: "1/S", since: "2026-11-01T00:00:00.000Z" } }; + const plan = planTimelineRun("backfill", walks, null) as TimelineRunPlan; + assert.deepEqual(settleTimelineRun(plan, walks, { complete: true, caughtUp: true }, NOW), walks); + // The timeline's real end clears it, as before. + assert.deepEqual(settleTimelineRun(plan, walks, { complete: true }, NOW), { sync: walks.sync }); + // A SYNC that caught up is finished: that is what catching up means for it. + const sync = planTimelineRun("sync", walks, "2026-11-10T00:00:00.000Z") as TimelineRunPlan; + assert.deepEqual(settleTimelineRun(sync, walks, { complete: true, caughtUp: true }, NOW), { backfill: walks.backfill }); +}); diff --git a/common/lib/timelineWalk.ts b/common/lib/timelineWalk.ts @@ -163,16 +163,23 @@ export function planTimelineRun( // clears its own slot (a full re-walk that finished clears both: it read // everything); one that stopped part-way saves its resume point there, or // keeps the one it had when it learned none. The other slot is never touched. +// +// A BACKFILL IS NEVER FINISHED BY MEETING KNOWN POSTS (lane x-followups): a +// run that ended "caught up" (`caughtUp`: a run of posts already archived, a +// sync's stop) says nothing of the history below them. A resumed backfill +// that ends so keeps the resume point it had. A resumed walk once re-read +// archived posts, was taken for finished, and its point was cleared. export function settleTimelineRun( plan: TimelineRunPlan, prior: TimelineWalks, - outcome: { complete: boolean; cursor?: string }, + outcome: { complete: boolean; cursor?: string; caughtUp?: boolean }, now: string, ): TimelineWalks { const next: TimelineWalks = { ...(prior.backfill ? { backfill: prior.backfill } : {}), ...(prior.sync ? { sync: prior.sync } : {}), }; + if (outcome.complete && outcome.caughtUp && plan.mode === "backfill") return next; if (outcome.complete) { if (plan.mode === "full") return {}; if (plan.saveTo === "sync") delete next.sync; diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -71,6 +71,11 @@ export type PostFetchInput = { // --full repair, which re-walks everything on purpose. Undefined: the // fetcher's own default. stopAtKnown?: boolean; + // The run RESUMES THE FULL-HISTORY WALK from `cursor` (lib/timelineWalk.ts + // "backfill"): no watermark, and posts already archived are not its end. A + // fetcher that can tell a resume point was not honoured says so instead of + // walking the timeline again from the top. + resumedBackfill?: boolean; // Save progress during a long run: called with posts not yet handed back and // the resume point they are safe under. Posts passed here are NOT returned // again in the result. A fetcher that pages in one shot never calls it. @@ -98,6 +103,10 @@ export type PostFetchResult = { // Maps onto the existing "needs cookies" snapshot bucket rather than // inventing a new failure surface. needsCookies?: boolean; + // `complete` because the walk met a run of posts already archived (a + // sync's "caught up"), not because the source had no more. Never the end of + // a history walk: the controller keeps a backfill's resume point on it. + caughtUp?: boolean; // The run failed part-way. `posts` and `cursor` still hold what it got, so // the controller saves them before reporting the failure. error?: string; diff --git a/common/social/xGalleryDlFetcher.test.ts b/common/social/xGalleryDlFetcher.test.ts @@ -514,3 +514,83 @@ test("normalizeXTweets (the Playwright fallback's batch) links quotes the same w assert.equal(posts.find((p) => p.id === T3)?.quoted?.id, T5); assert.ok(!posts.some((p) => p.id === Q1 || p.id === Q2)); }); + +// --------------------------------------------------------------------------- +// The history walk's search phase, and a resumed backfill (lane x-followups) +// --------------------------------------------------------------------------- + +test("stream: the search phase's page marker is a resume point, in the extractor's own cursor form", async () => { + const { searchPhaseCursor, X_SEARCH_PHASE_STATE } = await import("./xGalleryDlFetcher"); + assert.equal(searchPhaseCursor("1899000000000000041"), "3_1899000000000000041/"); + // State 3 is the unfiltered search: the one a text-tweets run goes to (it skips state 2, the media search). + assert.equal(X_SEARCH_PHASE_STATE, 3); + assert.ok(buildGalleryDlArgs({ accountUrl: ACCOUNT, stream: true }).includes("extractor.twitter.text-tweets=true")); + + const s = newStream({ searchPhaseCursors: true }); + s.pushStdout(jsonl(1)); + assert.equal(s.pushStderr("[twitter][debug] Cursor: 1/LAST-TIMELINE-PAGE"), "cursor"); + // The timeline API has ended: gallery-dl goes on by search, which logs no "Cursor:" line. + s.pushStdout(jsonl(2)); + assert.equal(s.pushStderr("[twitter][debug] Next 'max_id': 1899000000000000041"), "cursor"); + assert.equal(s.cursor, "3_1899000000000000041/"); + // A checkpoint is one page back, as with cursors. + assert.equal(s.takeCheckpoint()?.cursor, "1/LAST-TIMELINE-PAGE"); + s.pushStdout(jsonl(3)); + assert.equal(s.pushStderr("[twitter][debug] Next 'max_id': 1899000000000000030"), "cursor"); + assert.deepEqual(s.takeCheckpoint()?.cursor, "3_1899000000000000041/"); + assert.equal(s.cursor, "3_1899000000000000030/"); + // A search that falls back to cursor paging logs its own cursor: taken as it is. + s.pushStderr("[twitter][debug] Cursor: 3_1899000000000000030/API-CURSOR"); + assert.equal(s.cursor, "3_1899000000000000030/API-CURSOR"); + // Its other debug lines are noise, and no boundary. + assert.equal(s.pushStderr("[twitter][debug] Repeated 'max_id' value (1899000000000000030)"), undefined); + assert.equal(s.cursor, "3_1899000000000000030/API-CURSOR"); + // The search WALK (older posts, an X search channel) keeps its own resume point: the marker is not read. + const search = newStream(); + search.pushStdout(jsonl(1)); + assert.equal(search.pushStderr("[twitter][debug] Next 'max_id': 1899000000000000041"), undefined); + assert.equal(search.cursor, undefined); +}); + +test("stream: a walk that does not stop at known posts says once that it is skipping them", () => { + const archived = newStream(); + for (let n = 0; n <= STOP_AFTER_KNOWN + 5; n++) archived.pushStdout(jsonl(n)); + const seen = new Set(archived.finish().map((p) => p.id)); + const s = newStream({ seenIds: seen, stopAtKnown: false }); + for (let n = 0; n < STOP_AFTER_KNOWN - 1; n++) s.pushStdout(jsonl(n)); + assert.equal(s.skippingKnown, false); + s.pushStdout(jsonl(STOP_AFTER_KNOWN)); + assert.equal(s.skippingKnown, true); + assert.equal(s.stopReached, false); + // A new post after them is read as any other. + s.pushStdout(jsonl(9000)); + assert.equal(s.finish().length, 1); +}); + +test("stream: a resumed backfill whose first posts are the timeline's newest restarted from the top", async () => { + const { newestPostId, TOP_RESTART_WINDOW } = await import("./xGalleryDlFetcher"); + const id = (n: number) => String(1899000000000000000n + BigInt(n)); + // Archived: 100..500 (500 is the newest). + const seen = new Set(Array.from({ length: 401 }, (_, i) => id(100 + i))); + assert.equal(newestPostId(seen), 1899000000000000500n); + assert.equal(newestPostId(["not-a-number"]), null); + assert.equal(newestPostId([]), null); + const resumed = (ns: number[]) => { + const s = newStream({ seenIds: seen, stopAtKnown: false, topRestartAt: newestPostId(seen)! }); + for (const n of ns) s.pushStdout(jsonl(n)); + return s.restartedFromTop; + }; + // At its place: posts below everything archived, and the page it re-reads. + assert.equal(resumed([101, 100, 99, 98]), false); + // The newest archived post itself, or anything newer: the top. + assert.equal(resumed([500, 499]), true); + assert.equal(resumed([501, 500]), true); + // An old pinned post first, then the top: still the top. + assert.equal(resumed([3, 501]), true); + // Only the first page is judged. + assert.equal(resumed([...Array.from({ length: TOP_RESTART_WINDOW }, (_, i) => 99 - i), 500]), false); + // A walk that is no resumed backfill is not judged at all. + const sync = newStream({ seenIds: seen }); + sync.pushStdout(jsonl(501)); + assert.equal(sync.restartedFromTop, false); +}); diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -569,13 +569,69 @@ function pause(ms: number, signal: AbortSignal): Promise<void> { // posts it did get and the archive. export const RESTART_FROM_TOP_CURSOR = "1/"; -// A watermarked or resumed run stops once this many posts IN A ROW are already -// archived (or older than the watermark). Consecutive, so a pinned old post at -// the top of the timeline does not end the run; well above one page (~20 -// tweets, plus their quotes), so re-reading the page a resumed cursor points at -// does not end it either. +// A SYNC stops once this many posts IN A ROW are already archived (or older +// than the watermark). Consecutive, so a pinned old post at the top of the +// timeline does not end the run; well above one page (~20 tweets, plus their +// quotes), so re-reading the page a resumed cursor points at does not end it +// either. +// +// NOT A HISTORY WALK'S RULE (lane x-followups). A resumed backfill has no +// watermark, and known posts are not its end: it skips them and reads on, to +// the timeline's real end, its budget or a cap (the controller passes +// `stopAtKnown: false` for it, and never clears a backfill's resume point on +// a stop at known posts — lib/timelineWalk.ts settleTimelineRun). export const STOP_AFTER_KNOWN = 100; +// THE TIMELINE WALK HAS TWO PHASES, AND THE SECOND LOGS NO CURSOR (lane +// x-followups; read from gallery-dl 1.32.9's twitter extractor, and what a +// long walk showed). gallery-dl's timeline extractor reads the +// account's timeline API first (state 1: its "Cursor: 1/<API cursor>" after +// every page) and, where that ends — a few thousand posts down — goes on by +// SEARCH (`from:<handle> max_id:<id>`, state 3 with text-tweets on, which this +// fetcher always passes; state 2 is the media search it skips). The search +// pages by max_id: after each page it rewrites the query's `max_id:` and logs +// [twitter][debug] Next 'max_id': <N> +// and never a "Cursor:" line. Reading only "Cursor:", this side kept the LAST +// TIMELINE-PHASE cursor as the resume point for the whole search phase: a +// long walk that stopped at its budget saved a point thousands of posts above +// where it stood. Its resume re-read the search phase from the top — all +// archived — and ended "caught up" after 100 known posts. +// +// The search phase's resume point is the extractor's own cursor form with no +// API cursor: `3_<N>/` makes it ask `from:<handle> max_id:<N>` afresh, which +// is exactly the request it would have made next. +const MAX_ID_LINE = /\]\[debug\]\s+Next 'max_id':\s+(\d+)\s*$/; +export const X_SEARCH_PHASE_STATE = 3; +export function searchPhaseCursor(maxId: string): string { + return `${X_SEARCH_PHASE_STATE}_${maxId}/`; +} + +// A RESUMED BACKFILL THAT STARTED AGAIN FROM THE TOP. A resume point is +// gallery-dl's and X's to honour. When the first posts a resumed backfill +// reads are at or above the NEWEST archived post, the walk is at the top of +// the timeline, not at its saved place: it stops with this sentence and keeps +// the resume point, rather than walk the whole timeline again in silence. Only +// the first page is judged (a walk that began at its place cannot reach the +// top later). +export const TOP_RESTART_WINDOW = 20; +export const X_BACKFILL_RESTARTED_FROM_TOP = + "The resumed backfill did not continue from its saved resume point: the first posts gallery-dl read are the newest " + + "of the timeline, so the walk began again from the top. Stopped at once; the resume point is kept and nothing was " + + 'walked again. Run Resume backfill again; if it says this twice, fetch-posts {"older": true} walks down from the ' + + "oldest archived post instead."; + +// The newest of a set of post ids, as a number (X ids grow with time); null +// when none is numeric. +export function newestPostId(ids: Iterable<string>): bigint | null { + let max: bigint | null = null; + for (const id of ids) { + if (!/^\d+$/.test(id)) continue; + const n = BigInt(id); + if (max === null || n > max) max = n; + } + return max; +} + // How long one run may take. gallery-dl waits out X's rate limit in-process // ("Waiting for 14 minutes … (rate limit)"), so a backfill spends most of its // time asleep; with progress saved as it goes, a run that hits its budget @@ -622,6 +678,10 @@ export class GalleryDlStream { // The first challenge or login-wall line on stderr (xBlockLine), if any. challengeLine?: string; stopReached = false; + // A resumed backfill whose first posts are the timeline's newest (opts.topRestartAt). + restartedFromTop = false; + // STOP_AFTER_KNOWN known posts in a row were met by a walk that does not stop at them. + skippingKnown = false; cursor?: string; // The oldest post id read this run (any post, archived or not) — a search // walk's resume point. @@ -647,6 +707,14 @@ export class GalleryDlStream { seenIds: ReadonlySet<string>; since?: string; stopAtKnown: boolean; + // The timeline walk: read the search phase's page marker ("Next + // 'max_id': N") as a resume point (searchPhaseCursor). Off for a search + // walk, whose resume point is its own (oldestId). + searchPhaseCursors?: boolean; + // A resumed backfill: the newest archived post's id. One of the first + // TOP_RESTART_WINDOW posts at or above it means the walk restarted from + // the top (X_BACKFILL_RESTARTED_FROM_TOP). + topRestartAt?: bigint; // The account's handle, to recognise its `user` record. accountHandle?: string; onLog?: (line: string) => void; @@ -674,6 +742,13 @@ export class GalleryDlStream { this.cursor = cursor[1]; return "cursor"; } + // The search phase's page boundary: a resume point, as a cursor is. + const maxId = this.opts.searchPhaseCursors ? MAX_ID_LINE.exec(line) : null; + if (maxId) { + this.previousCursor = this.cursor; + this.cursor = searchPhaseCursor(maxId[1]); + return "cursor"; + } if (DEBUG_LINE.test(line) || !line.trim()) return undefined; const waiting = RATE_LIMIT_LINE.test(line); if (waiting) this.rateLimited = true; @@ -772,6 +847,14 @@ export class GalleryDlStream { this.accountCreatedAt = xCreatedAt({ date: user.date }); } } + if ( + this.opts.topRestartAt !== undefined && + this.distinct <= TOP_RESTART_WINDOW && + /^\d+$/.test(post.id) && + BigInt(post.id) >= this.opts.topRestartAt + ) { + this.restartedFromTop = true; + } const isKnown = this.opts.seenIds.has(post.id); const isOlder = !isKnown && Boolean(this.opts.since && post.createdAt <= this.opts.since); @@ -779,8 +862,9 @@ export class GalleryDlStream { if (isKnown) this.known++; else this.older++; this.knownRun++; - if (this.opts.stopAtKnown && this.knownRun >= STOP_AFTER_KNOWN) { - this.stopReached = true; + if (this.knownRun >= STOP_AFTER_KNOWN) { + if (this.opts.stopAtKnown) this.stopReached = true; + else this.skippingKnown = true; } return; } @@ -1341,12 +1425,18 @@ export const xGalleryDlFetcher: SocialFetcher = { ` (up to ${Math.round(budgetMs / 60_000)} min this run; progress is saved as it goes)`, ); + // A resumed backfill given a real resume point ("1/" asks for the top). + const resumedBackfill = input.resumedBackfill === true && Boolean(input.cursor) && input.cursor !== RESTART_FROM_TOP_CURSOR; + const newestKnown = resumedBackfill ? newestPostId(seenIds) : null; const stream = new GalleryDlStream({ channelSlug, seenIds, since, - // A --full repair re-walks everything on purpose. + // A --full repair re-walks everything on purpose; a resumed backfill + // skips what is archived and reads on (STOP_AFTER_KNOWN). stopAtKnown: input.stopAtKnown ?? Boolean(since), + searchPhaseCursors: true, + ...(resumedBackfill && newestKnown !== null ? { topRestartAt: newestKnown } : {}), onLog, }); @@ -1401,10 +1491,12 @@ export const xGalleryDlFetcher: SocialFetcher = { // if gallery-dl has not exited a few seconds later; the resume point is // the latest cursor, safe once both pipes have drained. let stoppedAtKnown = false; + let stoppedAtTop = false; + let saidSkipping = false; let drained = false; let betweenPages = false; const stopForDrain = () => { - if (drained || stoppedAtKnown) return; + if (drained || stoppedAtKnown || stoppedAtTop) return; drained = true; onLog?.("Drain requested: stopping gallery-dl at this page boundary."); subprocess.kill("SIGTERM"); @@ -1417,7 +1509,19 @@ export const xGalleryDlFetcher: SocialFetcher = { const stdoutDone = readLines(subprocess.stdout, (line) => { if (line.trim()) betweenPages = false; stream.pushStdout(line); - if (stream.stopReached && !stoppedAtKnown) { + if (stream.restartedFromTop && !stoppedAtTop && !stoppedAtKnown) { + stoppedAtTop = true; + onLog?.("The first posts read are the timeline's newest: the resume point was not honoured; stopping gallery-dl."); + subprocess.kill(); + } + if (stream.skippingKnown && !saidSkipping) { + saidSkipping = true; + onLog?.( + `${STOP_AFTER_KNOWN} already-archived posts in a row: this walk has no watermark, so it skips them and reads on ` + + "(it ends at the timeline's end, its budget or a cap).", + ); + } + if (stream.stopReached && !stoppedAtKnown && !stoppedAtTop) { stoppedAtKnown = true; onLog?.( `Reached ${STOP_AFTER_KNOWN} already-archived posts in a row — caught up; stopping gallery-dl.`, @@ -1483,7 +1587,13 @@ export const xGalleryDlFetcher: SocialFetcher = { }; } - if (stoppedAtKnown) return { posts, complete: true }; + // The walk began again from the top: its saved place is kept, and what it + // read of the top (new posts, if any) is written like any other. + if (stoppedAtTop) { + return { posts, complete: false, cursor: input.cursor, error: X_BACKFILL_RESTARTED_FROM_TOP }; + } + + if (stoppedAtKnown) return { posts, complete: true, caughtUp: true }; if (res.isCanceled || signal.aborted || res.timedOut) { onLog?.( diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -2150,7 +2150,11 @@ export function usage() { ' "backfill": true): a plain fetch-posts, Sync and the scheduler sync new', " posts and keep its place. Refused when none is part-way, on a forum", " thread (every fetch catches up, then continues its history) and on an X", - " search channel.", + " search channel. It ends only at the timeline's end, its budget or a cap:", + " posts already archived are skipped, never taken for the end, and its", + " place is cleared only by the timeline's end. A resume that began again", + " from the top (the first posts read are the newest) stops at once with a", + " sentence and keeps its place.", "", 'capture-posts captures archived posts of a social channel (X, forum,', ' Bluesky): a screenshot of each through the connected X profile (a forum',