Archilyzer · Source

archilyzer

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

commit 453dfa4c7e8cb9f013406172eb8688ff1b524720
parent 8d74a3c7684a90e8b8b163c34c091bdbb646b137
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 00:28:18 -0500

posts: sync new and resume backfill are two walks with two positions

A plain fetch-posts on an X or Bluesky channel with a stored cursor resumed
the old backfill and skipped the watermark: madamsavvy-x (6 Nov) walked old
history, stopped "caught up" on 100 archived posts, missed 85 newer ones and
cleared the cursor, losing the backfill's place too.

lib/timelineWalk.ts (pure) keeps the timeline's two walks apart in
posts-state.json:
- SYNC NEW, the default: from the top down to the newest archived post. It
  never reads or clears `backfill`. When it stops part-way it saves its own
  point in `sync`, with the watermark it began with, and the next sync
  continues down to that watermark.
- RESUME BACKFILL (fetch-posts `backfill`, CLI --backfill): continues
  `backfill.cursor` with no watermark and never touches `sync`. It is refused
  when no backfill is part-way, with full or older, on a forum thread (whose
  catch-up always comes first) and on an X search channel.
A first walk (nothing archived) and an unfinished --full leave a backfill.

Migration: a legacy `cursor` is read as the backfill's position and dropped
on the next timeline write. A forum thread still reads it as its pre-37
history position. Bluesky now honours the watermark the controller hands it
beside a cursor. Each job log line names the mode.

Operator, 6 Nov 2026: "We should have distinct 'sync new' and 'resume
backfill' actions, they are different actions for different purposes".

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

Diffstat:
Mcommon/bin/archilyzer.ts | 2+-
Mcommon/bin/fetch-posts.ts | 13+++++++++++--
Mcommon/controller/fetchOlderPosts.test.ts | 6++++--
Mcommon/controller/fetchPosts.test.ts | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/controller/fetchPosts.ts | 128++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/lib/posts-server.ts | 21+++++++++++++++------
Acommon/lib/timelineWalk.test.ts | 147+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/timelineWalk.ts | 231+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/blueskyFetcher.ts | 11++++++-----
Mcommon/social/fetchers.ts | 12+++++++-----
10 files changed, 621 insertions(+), 55 deletions(-)

diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -856,7 +856,7 @@ export const COMMANDS: Command[] = [ script(["duplicates"], "duplicate-shorts.ts", "[--threshold N] [--all-durations] [--blocking title|duration|both] [--near F] [--tolerance N] … on-demand duplicate detection (after index + stats)", 8192), script(["posts", "fetch"], "fetch-posts.ts", - "--slug <channel> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M] fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-*: wait out a challenge or refusal page and run again)"), + "--slug <channel> [--backfill | --full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M] fetch a social channel's posts into its posts corpus (plain: sync new — from the top down to the newest archived post, never the backfill; --backfill: resume the timeline's unfinished full-history walk from its saved point; --older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-*: wait out a challenge or refusal page and run again)"), { path: ["posts", "import-html"], usage: diff --git a/common/bin/fetch-posts.ts b/common/bin/fetch-posts.ts @@ -2,7 +2,7 @@ // Fetch social posts for one channel into its on-disk posts corpus. // // pnpm --filter yt-dlp-transcript-common exec tsx bin/fetch-posts.ts \ -// --slug <channel-slug> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] +// --slug <channel-slug> [--backfill | --full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] // [--retry-on-block | --retry-minutes N --retry-tries M] // // --pages caps how many pages one run reads, for a source read page by page (a @@ -16,6 +16,14 @@ // walk; wait N minutes and run again, M tries in all. --retry-on-block uses // settings.social.xenforo.retryOnBlock (nothing when unset). // +// A plain run is SYNC NEW: from the top of the timeline down to the newest +// archived post (an unfinished sync continues down to the watermark it began +// with). It never reads or clears the backfill's resume point. +// +// --backfill is RESUME BACKFILL: the timeline's unfinished full-history walk +// continued from its saved resume point, with no watermark (refused when none +// is part-way). lib/timelineWalk.ts. +// // --full re-walks the account's whole history instead of stopping at the // stored watermark. New posts are still deduped against the posts-archive, so // it repairs a gap rather than creating duplicates. @@ -39,7 +47,7 @@ const flags = parseFlags(process.argv.slice(2)); const slug = flags.slug; if (!slug) { console.error( - "Usage: fetch-posts.ts --slug <channel-slug> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M]", + "Usage: fetch-posts.ts --slug <channel-slug> [--backfill | --full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M]", ); process.exit(2); } @@ -74,6 +82,7 @@ fetchPosts({ slug, settings: getSettings(), full: flags.full === "true", + backfill: flags.backfill === "true", older: flags.older === "true", floor: flags.floor, from: flags.from, diff --git a/common/controller/fetchOlderPosts.test.ts b/common/controller/fetchOlderPosts.test.ts @@ -212,12 +212,14 @@ test("an older fetch walks back window by window and stops after four empty wind assert.ok(again.some((l) => /already complete/.test(l)), again.join("\n")); }); -test("a normal fetch ignores the older walk's state, resumes the TIMELINE, and keeps the older state", async () => { +test("resume backfill ignores the older walk's state, resumes the TIMELINE's backfill, and keeps the older state", async () => { const slug = "older-walk"; const channelRoot = path.join(channelsDir, slug); const olderBefore = (await readPostFetchState(channelRoot))?.older; assert.ok(olderBefore); - const result = await fetchPosts({ paths: getPaths(), slug, settings: LOGIN }); + // The seeded legacy `cursor` is the backfill's (lib/timelineWalk.ts): a + // plain fetch would sync new from the top; `backfill` resumes it. + const result = await fetchPosts({ paths: getPaths(), slug, settings: LOGIN, backfill: true }); assert.equal(result.ok, true); const argv = (await argvLines()).at(-1)!; assert.equal(argv[argv.length - 1], `https://x.com/${HANDLE}/timeline`); diff --git a/common/controller/fetchPosts.test.ts b/common/controller/fetchPosts.test.ts @@ -1,7 +1,10 @@ // fetchPosts over the gallery-dl X fetcher, end to end against a fake binary: // a run that is cancelled (or times out) part-way keeps what it read and the -// resume point, and the next run continues from there. A drained run stops at -// a page boundary, keeps that resume point, and is not a failure. +// resume point, and the next run of the same walk continues from there. A +// drained run stops at a page boundary, keeps that resume point, and is not a +// failure. The timeline's two walks (lib/timelineWalk.ts): a plain fetch is +// SYNC NEW and never reads or clears the backfill's point; RESUME BACKFILL +// (`backfill`) continues it. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchPosts.test.ts @@ -121,7 +124,7 @@ async function lastArgv(): Promise<string[]> { return JSON.parse(lines[lines.length - 1]) as string[]; } -test("a cancelled backfill keeps what it read and where it stopped", async () => { +test("a cancelled first walk keeps what it read, and where it stopped as the BACKFILL's point", async () => { const controller = new AbortController(); const log: string[] = []; const result = await fetchPosts({ @@ -140,26 +143,71 @@ test("a cancelled backfill keeps what it read and where it stopped", async () => assert.equal(result.complete, false); assert.equal((await readSeenPostIds(channelRoot)).size, 6); const state = await readPostFetchState(channelRoot); - assert.equal(state?.cursor, "1/AFTER-P2"); + assert.equal(state?.backfill?.cursor, "1/AFTER-P2"); + assert.equal(state?.cursor, undefined); + assert.equal(state?.sync, undefined); assert.ok(log.some((l) => /Cancelled; the next run resumes/.test(l)), log.join("\n")); + assert.ok(log.some((l) => /sync new — nothing archived yet, so this is the first full-history walk/.test(l)), log.join("\n")); const argv = await lastArgv(); assert.ok(argv.includes("output.jsonl=true")); assert.ok(argv.includes("--verbose")); }); -test("the next run resumes from the saved cursor and finishes the history", async () => { +test("a plain fetch is SYNC NEW: from the top down to the watermark, never reading the backfill's point, and keeping it", async () => { + process.env.FAKE_MODE = "known"; + const log: string[] = []; + let result; + try { + result = await fetchPosts({ + paths: (await import("../lib/paths")).getPaths(), + slug: SLUG, + settings: {}, + onLog: (l) => log.push(l), + }); + } finally { + delete process.env.FAKE_MODE; + } + assert.equal(result.ok, true, log.join("\n")); + assert.equal(result.complete, true); + // From the top: no resume point handed to gallery-dl. + assert.equal((await lastArgv()).some((a) => a.startsWith("extractor.twitter.cursor=")), false); + assert.ok(log.some((l) => /— sync new, since 2026-06-28/.test(l)), log.join("\n")); + assert.ok(log.some((l) => /A backfill is unfinished \(6 archived; its resume point is kept\)/.test(l)), log.join("\n")); + // Caught up — and the backfill's point is exactly where it was. + assert.equal((await readPostFetchState(channelRoot))?.backfill?.cursor, "1/AFTER-P2"); +}); + +test("RESUME BACKFILL continues from the saved point and finishes the history; the point is then cleared", async () => { + const log: string[] = []; const result = await fetchPosts({ paths: (await import("../lib/paths")).getPaths(), slug: SLUG, settings: {}, + backfill: true, + onLog: (l) => log.push(l), }); assert.equal(result.ok, true); assert.equal(result.written, 3); assert.equal(result.complete, true); assert.ok((await lastArgv()).includes("extractor.twitter.cursor=1/AFTER-P2")); + assert.ok(log.some((l) => /— resume backfill, from its saved resume point/.test(l)), log.join("\n")); assert.equal((await readSeenPostIds(channelRoot)).size, 9); // Caught up: no resume point left behind. - assert.equal((await readPostFetchState(channelRoot))?.cursor, undefined); + const state = await readPostFetchState(channelRoot); + assert.equal(state?.backfill, undefined); + assert.equal(state?.cursor, undefined); +}); + +test("RESUME BACKFILL with none part-way, or with full or older, is refused and spawns nothing", async () => { + const before = (await readFile(ARGS_LOG, "utf8")).trim().split("\n").length; + const paths = (await import("../lib/paths")).getPaths(); + const { NO_BACKFILL_TO_RESUME, BACKFILL_AND_FULL_REFUSAL, BACKFILL_AND_OLDER_REFUSAL } = await import("./fetchPosts"); + const none = await fetchPosts({ paths, slug: SLUG, settings: {}, backfill: true }); + assert.equal(none.ok, false); + assert.equal(none.error, NO_BACKFILL_TO_RESUME); + assert.equal((await fetchPosts({ paths, slug: SLUG, settings: {}, backfill: true, full: true })).error, BACKFILL_AND_FULL_REFUSAL); + assert.equal((await fetchPosts({ paths, slug: SLUG, settings: {}, backfill: true, older: true })).error, BACKFILL_AND_OLDER_REFUSAL); + assert.equal((await readFile(ARGS_LOG, "utf8")).trim().split("\n").length, before); }); test("an incremental run stops itself once it is past everything new", async () => { @@ -179,6 +227,36 @@ test("an incremental run stops itself once it is past everything new", async () assert.equal((await readdir(channelRoot)).includes("posts-state.json"), true); }); +test("MIGRATION: a legacy single `cursor` is the backfill's — a plain fetch syncs new past it and keeps it; backfill resumes it", async () => { + // The madamsavvy-x shape (2026-11-06): an unfinished backfill's cursor, from + // before the walks split. A plain fetch used to resume it and miss the new + // posts above the archive. + await writeFile( + path.join(channelRoot, "posts-state.json"), + JSON.stringify({ lastFetchedAt: "2026-11-05T00:00:00.000Z", lastFetchedCount: 0, cursor: "1/AFTER-P2" }), + ); + const paths = (await import("../lib/paths")).getPaths(); + process.env.FAKE_MODE = "known"; + const log: string[] = []; + try { + const sync = await fetchPosts({ paths, slug: SLUG, settings: {}, onLog: (l) => log.push(l) }); + assert.equal(sync.ok, true, log.join("\n")); + } finally { + delete process.env.FAKE_MODE; + } + assert.equal((await lastArgv()).some((a) => a.startsWith("extractor.twitter.cursor=")), false); + assert.ok(log.some((l) => /Read the old single resume point/.test(l)), log.join("\n")); + assert.ok(log.some((l) => /— sync new, since /.test(l)), log.join("\n")); + const raw = JSON.parse(await readFile(path.join(channelRoot, "posts-state.json"), "utf8")) as Record<string, unknown>; + assert.equal("cursor" in raw, false); + assert.equal((raw.backfill as { cursor?: string } | undefined)?.cursor, "1/AFTER-P2"); + + const resumed = await fetchPosts({ paths, slug: SLUG, settings: {}, backfill: true }); + assert.equal(resumed.ok, true); + assert.ok((await lastArgv()).includes("extractor.twitter.cursor=1/AFTER-P2")); + assert.equal((await readPostFetchState(channelRoot))?.backfill, undefined); +}); + test("a run that dies part-way fails the job but keeps its posts and resume point", async () => { process.env.FAKE_MODE = "crash"; const result = await fetchPosts({ @@ -191,7 +269,11 @@ test("a run that dies part-way fails the job but keeps its posts and resume poin assert.match(result.error ?? "", /exited 4: .*404 Not Found/); assert.equal(result.written, 3); const state = await readPostFetchState(channelRoot); - assert.equal(state?.cursor, "1/CRASH-P1"); + // A SYNC that stopped: its own point, with the watermark it began with — + // not the backfill's. + assert.equal(state?.sync?.cursor, "1/CRASH-P1"); + assert.equal(state?.sync?.since, "2026-06-28T12:00:00.000Z"); + assert.equal(state?.backfill, undefined); assert.match(state?.lastError ?? "", /404 Not Found/); }); @@ -211,7 +293,7 @@ test("an auth failure that read nothing keeps the resume point it had, and inven // The crash above left a resume point: an auth failure must not drop it. const kept = await run(); assert.equal(kept.needsCookies, true); - assert.equal((await readPostFetchState(channelRoot))?.cursor, "1/CRASH-P1"); + assert.equal((await readPostFetchState(channelRoot))?.sync?.cursor, "1/CRASH-P1"); // From a caught-up state it must not invent one either: the watermark stands. await writeFile(path.join(channelRoot, "posts-state.json"), "{}"); @@ -224,6 +306,8 @@ test("an auth failure that read nothing keeps the resume point it had, and inven const state = await readPostFetchState(channelRoot); assert.equal(state?.needsCookies, true); assert.equal(state?.cursor, undefined); + assert.equal(state?.sync, undefined); + assert.equal(state?.backfill, undefined); }); async function makeChannel(slug: string): Promise<string> { @@ -286,7 +370,7 @@ test("a drain mid-page waits for the page's cursor, stops there and keeps it; th assert.equal(result.written, 6); assert.equal((await readSeenPostIds(root)).size, 6); const state = await readPostFetchState(root); - assert.equal(state?.cursor, "1/PAGES-P1"); + assert.equal(state?.backfill?.cursor, "1/PAGES-P1"); assert.equal(state?.lastError, undefined); assert.equal(log.some((l) => /page 2 read/.test(l)), false, log.join("\n")); assert.ok(log.some((l) => /Drained; the next run resumes from the last page read/.test(l)), log.join("\n")); @@ -300,6 +384,7 @@ test("a drain mid-page waits for the page's cursor, stops there and keeps it; th paths: (await import("../lib/paths")).getPaths(), slug, settings: {}, + backfill: true, signal: cancel.signal, onLog: (line) => { if (!/^Running /.test(line)) return; @@ -337,7 +422,7 @@ test("a drain while gallery-dl waits out a rate limit stops it at once, keeping assert.equal(result.written, 6); // Not left asleep for its 60 s. assert.ok(Date.now() - started < 15_000, `took ${Date.now() - started} ms`); - assert.equal((await readPostFetchState(root))?.cursor, "1/AFTER-P2"); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "1/AFTER-P2"); }); test("a drain before the fetch starts reads nothing and spawns nothing", async () => { diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -53,6 +53,21 @@ import { isUtcDay, olderFloorDay, } from "../social/olderBackfill"; +import { + BACKFILL_AND_FULL_REFUSAL, + BACKFILL_AND_OLDER_REFUSAL, + hasTimelineResumePoint, + NO_BACKFILL_TO_RESUME, + planTimelineRun, + settleTimelineRun, + timelineRunLine, + timelineWalkFields, + timelineWalks, + withResumePoint, + type TimelineMode, + type TimelineRunPlan, + type TimelineWalks, +} from "../lib/timelineWalk"; // Registering the built-in fetchers is a side effect of importing them. Keep // this list here (rather than inside fetchers.ts) so the registry module stays // free of imports from the heavier fetchers. @@ -85,6 +100,13 @@ export type FetchPostsOptions = { // posts are still deduped against the archive, so this is a safe repair // operation rather than a duplicate-maker. full?: boolean; + // RESUME BACKFILL (lib/timelineWalk.ts): continue the timeline's unfinished + // full-history walk from its saved resume point (posts-state.json's + // `backfill`), with no watermark. Without it a fetch is SYNC NEW: from the + // top down to the newest archived post, never reading or clearing the + // backfill's position. Refused when no backfill is part-way, with `full` or + // `older`, on a forum thread and on an X search channel. + backfill?: boolean; // Walk the account's history BACKWARDS from the oldest archived post, with // the fetcher's `fetchOlder` (X: search windows), instead of fetching new // posts. Its position is kept in posts-state.json's `older`, apart from the @@ -139,6 +161,24 @@ export const RETRY_AND_OLDER_REFUSAL = "Retry on a block applies to a new-posts export const FULL_AND_OLDER_REFUSAL = "A full re-fetch and an older-posts fetch are different walks — run one at a time."; +export { BACKFILL_AND_FULL_REFUSAL, BACKFILL_AND_OLDER_REFUSAL, NO_BACKFILL_TO_RESUME }; + +// A forum thread's every fetch catches up from the last page first, then +// continues its history (lib/forumWalk.ts): there is no separate backfill. +export const FORUM_BACKFILL_REFUSAL = + "A forum thread has no separate backfill: every Fetch posts catches up from the last page, then continues the history where it stopped."; + +export const X_SEARCH_BACKFILL_REFUSAL = + "An X search channel has one walk, its search windows: there is no timeline backfill to resume."; + +// Why `backfill` cannot run on this channel's state, or null. Shared with the +// server action, so a refusal comes before any job exists. +export function resumeBackfillProblem( + state: Parameters<typeof timelineWalks>[0], +): string | null { + return timelineWalks(state).backfill ? null : NO_BACKFILL_TO_RESUME; +} + // Why this fetcher cannot fetch older posts, or null when it can. export function olderPostsProblem( fetcher: Pick<SocialFetcher, "label" | "fetchOlder"> | undefined, @@ -160,11 +200,11 @@ export const EMPTY_ACCOUNT_OLDER_REFUSAL = export function emptyAccountOlderProblem( archived: number, - state: Pick<PostFetchState, "lastFetchedCount" | "cursor" | "lastError" | "needsCookies"> | null, + state: Pick<PostFetchState, "lastFetchedCount" | "cursor" | "backfill" | "sync" | "lastError" | "needsCookies"> | null, ): string | null { if (archived > 0 || !state) return null; if (state.lastFetchedCount !== 0) return null; - if (state.cursor || state.lastError || state.needsCookies) return null; + if (hasTimelineResumePoint(state) || state.lastError || state.needsCookies) return null; return EMPTY_ACCOUNT_OLDER_REFUSAL; } @@ -194,6 +234,12 @@ export async function fetchPosts( if (opts.full && opts.older) { return { ok: false, written: 0, skipped: 0, complete: false, error: FULL_AND_OLDER_REFUSAL }; } + if (opts.backfill && opts.full) { + return { ok: false, written: 0, skipped: 0, complete: false, error: BACKFILL_AND_FULL_REFUSAL }; + } + if (opts.backfill && opts.older) { + return { ok: false, written: 0, skipped: 0, complete: false, error: BACKFILL_AND_OLDER_REFUSAL }; + } for (const [name, day] of [["from", opts.from]] as const) { if (day !== undefined && !isUtcDay(day)) { return { ok: false, written: 0, skipped: 0, complete: false, error: `"${day}" is not a date (YYYY-MM-DD) for "${name}"` }; @@ -250,6 +296,9 @@ export async function fetchPosts( if (opts.older) { return { ok: false, written: 0, skipped: 0, complete: false, error: X_SEARCH_OLDER_REFUSAL }; } + if (opts.backfill) { + return { ok: false, written: 0, skipped: 0, complete: false, error: X_SEARCH_BACKFILL_REFUSAL }; + } if (opts.drain?.aborted) { log("Drained before the fetch started; nothing was read."); return { ok: true, written: 0, skipped: 0, complete: false, drained: true }; @@ -290,8 +339,16 @@ export async function fetchPosts( return { ok: true, written: 0, skipped: 0, complete: false, drained: true }; } + if (opts.backfill && fetcher.platform === "xenforo") { + return { ok: false, written: 0, skipped: 0, complete: false, error: FORUM_BACKFILL_REFUSAL }; + } + const seenIds = await readSeenPostIds(channelRoot); const priorState = await readPostFetchState(channelRoot); + if (opts.backfill) { + const problem = resumeBackfillProblem(priorState); + if (problem) return { ok: false, written: 0, skipped: 0, complete: false, error: problem }; + } if (opts.older) { const problem = olderPostsProblem(fetcher); @@ -415,22 +472,35 @@ async function fetchTimeline(ctx: { // A FORUM THREAD keeps two positions (lib/forumWalk.ts), re-derived from the // archived posts' pages every run; its walk needs neither a cursor nor a - // watermark. Every other fetcher: a stored cursor means the previous run - // stopped early (hit its limit, or was cancelled) — resume the backfill from - // there rather than applying the watermark, which would otherwise leave that - // history permanently missing. --full discards the cursor and re-walks from - // the top. + // watermark. Every other fetcher keeps the timeline's two walks + // (lib/timelineWalk.ts): SYNC NEW (the default) walks from the top down to + // the newest archived post — or continues its own unfinished sync down to + // the watermark that sync began with — and never reads or clears the + // backfill's resume point; RESUME BACKFILL (`backfill`) continues the + // full-history walk from that point, with no watermark; --full re-walks + // from the top. let forumWalk: ForumWalkState | undefined; if (forum) { const derived = deriveForumWalk(priorState?.forum, priorState?.cursor, await heldForumPages(channelRoot)); forumWalk = derived.walk; for (const note of derived.notes) log(note); } - const resumeCursor = opts.full || forum ? undefined : priorState?.cursor; - const since = - opts.full || resumeCursor || forum - ? undefined - : ((await latestPostCreatedAt(channelRoot)) ?? undefined); + const mode: TimelineMode = opts.full ? "full" : opts.backfill ? "backfill" : "sync"; + let walks: TimelineWalks = forum ? {} : timelineWalks(priorState); + let plan: TimelineRunPlan | undefined; + if (!forum) { + const watermark = mode === "sync" ? await latestPostCreatedAt(channelRoot) : undefined; + const planned = planTimelineRun(mode, walks, watermark); + if ("error" in planned) { + return { ok: false, written: 0, skipped: 0, complete: false, error: planned.error }; + } + plan = planned; + if (walks.migrated) { + log("Read the old single resume point (posts-state.json's `cursor`) as the backfill's."); + } + } + const resumeCursor = plan?.cursor; + const since = plan?.since; const policy = resolveCookiePolicy(settings, config); const cookies = alwaysCookies(policy); // An X fetcher's login source (social.x.cookieSource, xCookieSource.ts), @@ -447,13 +517,15 @@ async function fetchTimeline(ctx: { ? opts.full ? " — a full re-walk" : ` — ${forumWalkStartLine(forumWalk ?? {})}` - : resumeCursor - ? " — resuming an unfinished backfill" - : since - ? ` since ${since}` - : " — full history") + + : ` — ${timelineRunLine(plan!)}`) + `; ${seenIds.size} already archived.`, ); + if (plan?.mode === "sync" && walks.backfill) { + log( + `A backfill is unfinished (${seenIds.size} archived; its resume point is kept): this run syncs new posts only. ` + + 'Resume backfill (fetch-posts "backfill": true, or the ops action resume-backfill) continues it.', + ); + } // A managed job's cancel/drain arrives as an AbortSignal; the fetcher // interface requires one, so synthesize a never-aborting signal when the @@ -495,11 +567,13 @@ async function fetchTimeline(ctx: { checkpointSkipped += w.skipped; for (const shard of w.shards) shards.add(shard); if (forum && cp.forumWalk) state.forum = cp.forumWalk; + const next = plan ? withResumePoint(plan, walks, cp.cursor, new Date().toISOString()) : walks; await writePostFetchState(channelRoot, { ...state, - ...(forum ? {} : { cursor: cp.cursor }), + ...timelineWalkFields(next), lastFetchedCount: checkpointWritten, }); + walks = next; if (w.written > 0) { log(`Saved ${w.written} new post(s) (${checkpointWritten} so far this run); resume point recorded.`); } @@ -534,9 +608,10 @@ async function fetchTimeline(ctx: { log(`[error] ${message}`); state.lastError = message; // Whatever was checkpointed is on disk; keep the resume point that covers - // it rather than dropping back to the watermark. - const prior = await readPostFetchState(channelRoot); - if (!forum && prior?.cursor) state.cursor = prior.cursor; + // it (and the other walk's, untouched) rather than dropping back to the + // watermark. + if (!forum) Object.assign(state, timelineWalkFields(walks)); + const prior = forum ? await readPostFetchState(channelRoot) : null; if (forum && prior?.forum) state.forum = prior.forum; if (checkpointWritten > 0) state.lastFetchedCount = checkpointWritten; await writePostFetchState(channelRoot, state); @@ -559,7 +634,11 @@ async function fetchTimeline(ctx: { `Wrote ${written.written} new post(s), skipped ${written.skipped} already archived` + (upsert ? `, updated ${updated} edited` : "") + (shards.size > 0 ? ` (shards: ${[...shards].join(", ")})` : "") + - (result.complete ? "." : " — more history remains."), + (result.complete + ? "." + : plan?.saveTo === "sync" + ? " — the sync stopped part-way; the next Sync new continues it." + : " — more history remains."), ); if (result.notSeen?.length) { log( @@ -573,8 +652,9 @@ async function fetchTimeline(ctx: { state.lastFetchedCount = written.written; if (forum) { if (result.forumWalk) state.forum = result.forumWalk; - } else if (result.cursor && !result.complete) { - state.cursor = result.cursor; + } else if (plan) { + walks = settleTimelineRun(plan, walks, result, new Date().toISOString()); + Object.assign(state, timelineWalkFields(walks)); } if (result.needsCookies) state.needsCookies = true; // A FORUM's browser check or login wall is the forum session's cookies: the diff --git a/common/lib/posts-server.ts b/common/lib/posts-server.ts @@ -14,6 +14,7 @@ import { writeJsonAtomic } from "./jsonFile-server"; import path from "node:path"; import type { ForumWalkState } from "./forumWalk"; +import type { TimelineBackfillState, TimelineSyncState } from "./timelineWalk"; import { readdir, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { appendFile } from "node:fs/promises"; import { mergePageRecord } from "./waybackPages/toPost"; @@ -495,13 +496,21 @@ export type PostFetchState = { // the post-corpus analogue of the video pipeline's needs_auth outcome. needsCookies?: boolean; lastFetchedCount?: number; - // The TIMELINE walk's resume point (gallery-dl's cursor). Only a normal fetch - // reads it; the older-posts backfill keeps its own position in `older`. + // LEGACY (before 2026-11-06): the one TIMELINE resume point a sync and the + // history backfill shared. Read as `backfill`'s (lib/timelineWalk.ts) and + // dropped on the next timeline write; still read by a forum thread's walk + // as its pre-release-37 history position (lib/forumWalk.ts). cursor?: string; - // The older-posts backfill (a fetcher's `fetchOlder`), which walks the - // account's history backwards through search windows. Kept apart from - // `cursor` so a normal fetch never resumes backwards, and carried through - // every write a normal fetch makes. + // The timeline's two walks (lib/timelineWalk.ts): the full-history + // backfill's resume point — continued only by Resume backfill — and an + // unfinished sync's, with the watermark it walks down to. A sync never + // reads or clears `backfill`; a backfill never touches `sync`. + backfill?: TimelineBackfillState; + sync?: TimelineSyncState; + // The older-posts walk (a fetcher's `fetchOlder`), which walks the + // account's history backwards through search windows. Kept apart from the + // timeline's positions so a normal fetch never resumes backwards, and + // carried through every write a normal fetch makes. older?: OlderBackfillState; // A FORUM THREAD's two walks (release 37 lane G, lib/forumWalk.ts): the // catch-up's mark and resume point, and the history walk's position — in diff --git a/common/lib/timelineWalk.test.ts b/common/lib/timelineWalk.test.ts @@ -0,0 +1,147 @@ +// The timeline's two walks — sync new and resume backfill — as pure +// decisions, and the read of a posts-state.json written before they split. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/timelineWalk.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + describeTimelineBackfill, + describeTimelineSync, + hasTimelineResumePoint, + NO_BACKFILL_TO_RESUME, + planTimelineRun, + settleTimelineRun, + timelineRunLine, + timelineWalkFields, + timelineWalks, + withResumePoint, + type TimelineRunPlan, +} from "./timelineWalk"; + +const NOW = "2026-11-06T12:00:00.000Z"; +const WATERMARK = "2026-11-01T08:00:00.000Z"; + +test("MIGRATION: a legacy `cursor` is read as the backfill's position, and never written back", () => { + // The madamsavvy-x shape: a state from before the split, an unfinished + // backfill's cursor beside the rest. + const legacy = { lastFetchedAt: "2026-11-05T00:00:00.000Z", lastFetchedCount: 0, cursor: "1/LEGACY" }; + const walks = timelineWalks(legacy); + assert.deepEqual(walks, { backfill: { cursor: "1/LEGACY" }, migrated: true }); + assert.equal(hasTimelineResumePoint(legacy), true); + // What is written: the backfill, no `cursor`, no `migrated` marker. + assert.deepEqual(timelineWalkFields(walks), { backfill: { cursor: "1/LEGACY" } }); + // And read back, it is the same position — not migrated again. + assert.deepEqual(timelineWalks(timelineWalkFields(walks)), { backfill: { cursor: "1/LEGACY" } }); +}); + +test("MIGRATION: a `backfill` already present wins over a stray legacy `cursor`; empty values are nothing", () => { + assert.deepEqual(timelineWalks({ cursor: "1/OLD", backfill: { cursor: "1/NEW" } }), { + backfill: { cursor: "1/NEW" }, + }); + assert.deepEqual(timelineWalks({ cursor: "" }), {}); + assert.deepEqual(timelineWalks({ backfill: { cursor: "" }, sync: { cursor: "" } }), {}); + assert.deepEqual(timelineWalks(null), {}); + assert.deepEqual(timelineWalks({}), {}); + assert.equal(hasTimelineResumePoint({}), false); + assert.equal(hasTimelineResumePoint({ sync: { cursor: "1/S", since: WATERMARK } }), true); +}); + +test("SYNC NEW walks from the top down to the watermark, past an unfinished backfill it does not read", () => { + const walks = timelineWalks({ cursor: "1/LEGACY" }); + const plan = planTimelineRun("sync", walks, WATERMARK); + assert.deepEqual(plan, { mode: "sync", since: WATERMARK, saveTo: "sync" }); + // It finishes ("caught up"): the backfill's position is exactly as it was. + const after = settleTimelineRun(plan as TimelineRunPlan, walks, { complete: true }, NOW); + assert.deepEqual(after.backfill, { cursor: "1/LEGACY" }); + assert.equal(after.sync, undefined); +}); + +test("SYNC NEW that stops part-way keeps its own resume point with the watermark it began with", () => { + const walks = timelineWalks({ backfill: { cursor: "1/BF" } }); + const plan = planTimelineRun("sync", walks, WATERMARK) as TimelineRunPlan; + const stopped = settleTimelineRun(plan, walks, { complete: false, cursor: "1/S-P3" }, NOW); + assert.deepEqual(stopped, { + backfill: { cursor: "1/BF" }, + sync: { cursor: "1/S-P3", since: WATERMARK, savedAt: NOW }, + }); + // The next sync continues it, down to THAT watermark — not the newer one + // the posts it just wrote would make. + const next = planTimelineRun("sync", stopped, "2026-11-06T09:00:00.000Z"); + assert.deepEqual(next, { mode: "sync", cursor: "1/S-P3", since: WATERMARK, saveTo: "sync" }); + assert.match(timelineRunLine(next as TimelineRunPlan), /continuing the unfinished sync down to 2026-11-01/); + // Finished, the sync's slot clears; the backfill's stays. + assert.deepEqual(settleTimelineRun(next as TimelineRunPlan, stopped, { complete: true }, NOW), { + backfill: { cursor: "1/BF" }, + }); +}); + +test("SYNC NEW with nothing archived is the first full-history walk: an unfinished one leaves a BACKFILL", () => { + const plan = planTimelineRun("sync", {}, null) as TimelineRunPlan; + assert.deepEqual(plan, { mode: "sync", saveTo: "backfill" }); + assert.match(timelineRunLine(plan), /first full-history walk/); + const after = settleTimelineRun(plan, {}, { complete: false, cursor: "1/FIRST-P2" }, NOW); + assert.deepEqual(after, { backfill: { cursor: "1/FIRST-P2", savedAt: NOW } }); + // The next plain fetch (posts now archived) syncs new; it does not resume it. + assert.deepEqual(planTimelineRun("sync", after, WATERMARK), { mode: "sync", since: WATERMARK, saveTo: "sync" }); +}); + +test("RESUME BACKFILL continues the saved point with no watermark, and never touches the sync's", () => { + const walks = timelineWalks({ + backfill: { cursor: "1/BF" }, + sync: { cursor: "1/S", since: WATERMARK }, + }); + const plan = planTimelineRun("backfill", walks, WATERMARK) as TimelineRunPlan; + assert.deepEqual(plan, { mode: "backfill", cursor: "1/BF", saveTo: "backfill" }); + assert.match(timelineRunLine(plan), /^resume backfill/); + const further = settleTimelineRun(plan, walks, { complete: false, cursor: "1/BF-2" }, NOW); + assert.deepEqual(further.sync, { cursor: "1/S", since: WATERMARK }); + assert.deepEqual(further.backfill, { cursor: "1/BF-2", savedAt: NOW }); + const done = settleTimelineRun(plan, further, { complete: true }, NOW); + assert.deepEqual(done, { sync: { cursor: "1/S", since: WATERMARK } }); +}); + +test("RESUME BACKFILL with no backfill part-way is refused", () => { + assert.deepEqual(planTimelineRun("backfill", {}, WATERMARK), { error: NO_BACKFILL_TO_RESUME }); + assert.deepEqual(planTimelineRun("backfill", { sync: { cursor: "1/S", since: WATERMARK } }, WATERMARK), { + error: NO_BACKFILL_TO_RESUME, + }); +}); + +test("a run that stops with no resume point keeps the one it had", () => { + const walks = { backfill: { cursor: "1/BF" } }; + const plan = planTimelineRun("backfill", walks, null) as TimelineRunPlan; + assert.deepEqual(settleTimelineRun(plan, walks, { complete: false }, NOW), walks); +}); + +test("FULL re-walks from the top; unfinished it replaces the backfill's point, finished it clears both", () => { + const walks = { backfill: { cursor: "1/BF" }, sync: { cursor: "1/S", since: WATERMARK } }; + const plan = planTimelineRun("full", walks, WATERMARK) as TimelineRunPlan; + assert.deepEqual(plan, { mode: "full", saveTo: "backfill" }); + assert.deepEqual(settleTimelineRun(plan, walks, { complete: false, cursor: "1/F" }, NOW), { + backfill: { cursor: "1/F", savedAt: NOW }, + sync: { cursor: "1/S", since: WATERMARK }, + }); + assert.deepEqual(settleTimelineRun(plan, walks, { complete: true }, NOW), {}); +}); + +test("a checkpoint saves into the run's own slot", () => { + const walks = { backfill: { cursor: "1/BF" } }; + const sync = planTimelineRun("sync", walks, WATERMARK) as TimelineRunPlan; + assert.deepEqual(withResumePoint(sync, walks, "1/CP", NOW), { + backfill: { cursor: "1/BF" }, + sync: { cursor: "1/CP", since: WATERMARK, savedAt: NOW }, + }); + const bf = planTimelineRun("backfill", walks, null) as TimelineRunPlan; + assert.deepEqual(withResumePoint(bf, walks, "1/CP", NOW), { backfill: { cursor: "1/CP", savedAt: NOW } }); +}); + +test("the status lines say a backfill is unfinished, and what continues a stopped sync", () => { + assert.equal( + describeTimelineBackfill({ backfill: { cursor: "1/BF" } }, 9936), + "backfill unfinished — 9936 archived; Resume backfill continues it", + ); + assert.equal(describeTimelineBackfill({}, 10), "no backfill part-way"); + assert.equal(describeTimelineSync({}), null); + assert.match(describeTimelineSync({ sync: { cursor: "1/S", since: WATERMARK } }) ?? "", /down to 2026-11-01/); +}); diff --git a/common/lib/timelineWalk.ts b/common/lib/timelineWalk.ts @@ -0,0 +1,231 @@ +// WHERE A SOCIAL TIMELINE'S TWO WALKS STAND (X, Bluesky, Nitter) — +// `posts-state.json`'s `backfill` and `sync`. Pure: no fs, client-safe (the +// channel page's status line reads it). +// +// Two actions, for two purposes (operator, 6 Nov 2026: "We should have +// distinct 'sync new' and 'resume backfill' actions, they are different +// actions for different purposes"): +// +// SYNC NEW — from the top of the timeline down to the newest archived post +// (the `since` watermark). What a plain fetch-posts, the scheduler and the +// Sync button run. It never reads the backfill's resume point and never +// clears it. A sync that stops part-way (its budget, a cancel, a drain, a +// cap) keeps ITS OWN resume point in `sync`, with the watermark it was +// walking down to: the next sync continues there, down to that same +// watermark, rather than stopping at the posts it just wrote and leaving +// the gap between them and the archive unread. +// +// RESUME BACKFILL — the full-history walk continued from its saved resume +// point (`backfill.cursor`), with no watermark. Run only when asked +// (fetch-posts "backfill": true, the ops action resume-backfill, the channel +// page's Resume backfill). It never touches the sync's position. +// +// The backfill's resume point is written by a FULL-HISTORY walk that did not +// finish: a channel's first fetch (nothing archived, so no watermark), a +// --full re-walk, or a resumed backfill. +// +// One field, `cursor`, used to serve both: a stored cursor made the next +// plain fetch resume the backfill and skip the watermark — so a fetch meant +// for new posts walked old history, missed the new ones, and on finishing +// cleared the cursor (2026-11-06, madamsavvy-x: "resuming an unfinished +// backfill; 9936 already archived … 0 new", 85 newer posts missed). A state +// written before the split has only `cursor`; it is read as the BACKFILL's +// position (timelineWalks), which is what it most often was, and is dropped +// from the file on the next timeline write. Read so, nothing is lost: were it +// really an unfinished sync's, resuming the backfill from it walks the same +// gap down to the archive. +// +// The older-posts walk (`older`, search windows below the oldest archived +// post) and a forum thread's two walks (`forum`, lib/forumWalk.ts) are their +// own and untouched by this. + +// The full-history walk's resume point. +export type TimelineBackfillState = { + // The fetcher's opaque resume point (gallery-dl's extractor cursor, a + // Bluesky feed cursor, a Nitter "Load more" cursor). + cursor: string; + // When the point was saved. + savedAt?: string; +}; + +// An unfinished sync's resume point, and the watermark it walks down to. +export type TimelineSyncState = { + cursor: string; + // The newest archived post's time when the sync started (ISO): the walk + // ends there. Absent only for a state no sync wrote. + since?: string; + savedAt?: string; +}; + +export type TimelineWalkFields = { + // LEGACY (before 2026-11-06): the one resume point both walks shared. + cursor?: string; + backfill?: TimelineBackfillState; + sync?: TimelineSyncState; +}; + +export type TimelineWalks = { + backfill?: TimelineBackfillState; + sync?: TimelineSyncState; + // The backfill came from the legacy `cursor`. + migrated?: boolean; +}; + +const cursorOf = (v: unknown): string | undefined => + typeof v === "string" && v.length > 0 ? v : undefined; + +// The two positions a state holds, with a legacy `cursor` read as the +// backfill's. A `backfill` already present wins over a stray `cursor` (only an +// older build, run after this one, would write both). +export function timelineWalks(state: TimelineWalkFields | null | undefined): TimelineWalks { + if (!state) return {}; + const out: TimelineWalks = {}; + const backfill = state.backfill && cursorOf(state.backfill.cursor) ? state.backfill : undefined; + if (backfill) out.backfill = { ...backfill }; + else { + const legacy = cursorOf(state.cursor); + if (legacy) { + out.backfill = { cursor: legacy }; + out.migrated = true; + } + } + if (state.sync && cursorOf(state.sync.cursor)) out.sync = { ...state.sync }; + return out; +} + +// The two positions as fields to write: `cursor` is never written again. +export function timelineWalkFields(walks: TimelineWalks): Pick<TimelineWalkFields, "backfill" | "sync"> { + return { + ...(walks.backfill ? { backfill: walks.backfill } : {}), + ...(walks.sync ? { sync: walks.sync } : {}), + }; +} + +// Whether a state holds any timeline resume point (either walk's, or the +// legacy one). +export function hasTimelineResumePoint(state: TimelineWalkFields | null | undefined): boolean { + const w = timelineWalks(state); + return Boolean(w.backfill || w.sync); +} + +export type TimelineMode = "sync" | "backfill" | "full"; + +export const NO_BACKFILL_TO_RESUME = + "There is no unfinished backfill to resume: the timeline's full-history walk is not part-way. " + + 'A plain fetch-posts syncs new posts; "full": true re-walks the whole timeline; "older": true walks back below the oldest archived post.'; + +export const BACKFILL_AND_FULL_REFUSAL = + 'Resume backfill continues the saved history walk; a full re-walk ("full") starts it over — run one.'; + +export const BACKFILL_AND_OLDER_REFUSAL = + 'Resume backfill continues the timeline\'s history walk; "older" is the search walk below the oldest archived post — run one at a time.'; + +// What one run reads from and where an unfinished run's resume point goes. +export type TimelineRunPlan = { + mode: TimelineMode; + // The resume point handed to the fetcher (none: from the top). + cursor?: string; + // The watermark handed to the fetcher (none: no stop below). + since?: string; + // Where this run's resume point is saved when it stops part-way. + saveTo: "sync" | "backfill"; +}; + +// The run a mode makes, given the positions and the newest archived post's +// time (`watermark`; null/undefined when nothing is archived). +export function planTimelineRun( + mode: TimelineMode, + walks: TimelineWalks, + watermark: string | null | undefined, +): TimelineRunPlan | { error: string } { + if (mode === "full") return { mode, saveTo: "backfill" }; + if (mode === "backfill") { + if (!walks.backfill) return { error: NO_BACKFILL_TO_RESUME }; + return { mode, cursor: walks.backfill.cursor, saveTo: "backfill" }; + } + // SYNC NEW: an unfinished sync continues down to the watermark it began + // with; else from the top down to the newest archived post. Nothing + // archived: the walk is the channel's first full-history walk, and its + // resume point is the backfill's. + if (walks.sync) { + const since = walks.sync.since ?? watermark ?? undefined; + return since + ? { mode, cursor: walks.sync.cursor, since, saveTo: "sync" } + : { mode, cursor: walks.sync.cursor, saveTo: "backfill" }; + } + return watermark ? { mode, since: watermark, saveTo: "sync" } : { mode, saveTo: "backfill" }; +} + +// The positions after a run, from the fetcher's outcome. A run that finished +// 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. +export function settleTimelineRun( + plan: TimelineRunPlan, + prior: TimelineWalks, + outcome: { complete: boolean; cursor?: string }, + now: string, +): TimelineWalks { + const next: TimelineWalks = { + ...(prior.backfill ? { backfill: prior.backfill } : {}), + ...(prior.sync ? { sync: prior.sync } : {}), + }; + if (outcome.complete) { + if (plan.mode === "full") return {}; + if (plan.saveTo === "sync") delete next.sync; + else delete next.backfill; + // A sync that had no watermark (nothing archived) and finished walked the + // whole timeline: an old sync position under it is spent too. + if (plan.mode === "sync" && plan.saveTo === "backfill") delete next.sync; + return next; + } + const cursor = cursorOf(outcome.cursor); + if (!cursor) return next; + return withResumePoint(plan, next, cursor, now); +} + +// A resume point saved mid-run (a checkpoint) or at its end. +export function withResumePoint( + plan: TimelineRunPlan, + walks: TimelineWalks, + cursor: string, + now: string, +): TimelineWalks { + const next: TimelineWalks = { + ...(walks.backfill ? { backfill: walks.backfill } : {}), + ...(walks.sync ? { sync: walks.sync } : {}), + }; + if (plan.saveTo === "sync") next.sync = { cursor, ...(plan.since ? { since: plan.since } : {}), savedAt: now }; + else { + next.backfill = { cursor, savedAt: now }; + // A first walk (sync with no watermark) that left a backfill behind has + // no sync of its own to continue. + if (plan.mode === "sync") delete next.sync; + } + return next; +} + +// The job log's opening words for a run: the mode, named. +export function timelineRunLine(plan: TimelineRunPlan): string { + if (plan.mode === "full") return "full re-walk of the timeline, from the top"; + if (plan.mode === "backfill") return "resume backfill, from its saved resume point"; + if (plan.cursor && plan.since) return `sync new, continuing the unfinished sync down to ${plan.since}`; + if (plan.since) return `sync new, since ${plan.since}`; + return "sync new — nothing archived yet, so this is the first full-history walk"; +} + +// The channel page's status line for the timeline's history walk. +export function describeTimelineBackfill(walks: TimelineWalks, archived: number): string { + if (walks.backfill) { + return `backfill unfinished — ${archived} archived; Resume backfill continues it`; + } + return "no backfill part-way"; +} + +// The channel page's line for an unfinished sync, or null. +export function describeTimelineSync(walks: TimelineWalks): string | null { + if (!walks.sync) return null; + return walks.sync.since + ? `a sync stopped part-way; the next Sync new continues it down to ${walks.sync.since}` + : "a sync stopped part-way; the next Sync new continues it"; +} diff --git a/common/social/blueskyFetcher.ts b/common/social/blueskyFetcher.ts @@ -411,15 +411,16 @@ export const blueskyFetcher: SocialFetcher = { async fetch(input: PostFetchInput): Promise<PostFetchResult> { const { handle, channelSlug, since, seenIds, limit, signal, onLog } = input; const posts: Post[] = []; - // Resuming an unfinished backfill: continue from the stored cursor and - // ignore the watermark, otherwise the first page (all already-archived) - // would stop the run before it reached the missing history. + // A saved resume point: continue from it. The controller decides the + // watermark (lib/timelineWalk.ts): RESUME BACKFILL passes none, so only an + // already-archived post stops it; an unfinished SYNC NEW passes the + // watermark it began with, so it stops there and not before. let cursor: string | undefined = input.cursor; const resuming = Boolean(input.cursor); - const watermark = resuming ? undefined : since; + const watermark = since; let complete = false; if (resuming) { - onLog?.(`Resuming backfill from cursor ${cursor}`); + onLog?.(`Continuing from the saved resume point (cursor ${cursor})`); } for (let page = 0; page < MAX_PAGES; page++) { diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -29,13 +29,15 @@ export type PostFetchInput = { // The channel slug the produced posts belong to. channelSlug: string; // ISO watermark: stop once posts older than this are reached. Absent on a - // first (full-backfill) run AND whenever a previous run stopped early — see - // `cursor`, which resumes the backfill instead. + // full-history walk: a first run, a --full re-walk, and RESUME BACKFILL. + // Given WITH `cursor` on an unfinished sync that continues: it walks on down + // to the watermark it began with (lib/timelineWalk.ts). since?: string; // Opaque resume point from a previous run that did not finish (hit its - // limit, or was cancelled). When set, the fetcher continues paging from here - // rather than from the top of the timeline, so a capped first run does not - // leave a permanent hole in the archived history. + // limit, or was cancelled) — the backfill's, or an unfinished sync's; the + // controller picks which by the run's mode. When set, the fetcher continues + // paging from here rather than from the top of the timeline, so a capped + // run does not leave a permanent hole in the archived history. cursor?: string; // Post ids already on disk. Paging stops at the first page containing one, // mirroring how sync() stops at the first already-archived video.