Archilyzer · Source

archilyzer

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

commit 98ae1d91620d26caa0741686e7e252c9359c1bcb
parent ab4d9dba9b001a834ba8f4aaeb2f6efa9324c2f5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 15:34:57 -0500

channels: account activity off the page's critical path -- a cached light read, memoised, streamed; bogus dates left out

The page parsed every post shard (readAllPosts) on every render of a posts
channel: ~1 s on kf-quartering-thread (66 MB, 37,802 posts), ~0.45 s on
hasanthehun-x (145 shards). lib/postTimes-server.ts keeps each shard's light
rows (id, createdAt, author, url, first line) keyed by mtime and size, and
memoises the activity per channel by the shards' signature; the panel streams
behind its own Suspense boundary. Measured read-only on the real corpus:
warm 2-7 ms (was 980 / 440 ms every render), cold once per changed shard.
accountActivity drops dates outside 2006-01-01 .. now+1 d, so one bogus date
cannot stretch the strip to millions of days.

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

Diffstat:
Mcommon/lib/accountActivity.test.ts | 16++++++++++++++++
Mcommon/lib/accountActivity.ts | 9+++++++--
Acommon/lib/postTimes-server.test.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/postTimes-server.ts | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/AccountActivityPanel.tsx | 31+++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/page.tsx | 27+++++++++++++++------------
6 files changed, 278 insertions(+), 14 deletions(-)

diff --git a/common/lib/accountActivity.test.ts b/common/lib/accountActivity.test.ts @@ -113,3 +113,19 @@ test("the words", () => { assert.equal(medianText(13), "13 min"); assert.equal(medianText(150), "2.5 h"); }); + +test("a bogus date is left out: before 2006 or more than a day ahead never stretches the strip", () => { + const now = Date.parse("2026-11-09T12:00:00Z"); + const a = accountActivity( + [ + post("0", "1970-01-01T00:00:00Z"), + post("1", "2026-11-01T00:00:00Z"), + post("2", "2026-11-02T00:00:00Z"), + post("3", "9999-12-31T00:00:00Z"), + ], + { now }, + )!; + assert.equal(a.posts, 2); + assert.equal(a.days.length, 2); + assert.equal(accountActivity([post("0", "1970-01-01T00:00:00Z"), post("3", "9999-12-31T00:00:00Z")], { now }), null); +}); diff --git a/common/lib/accountActivity.ts b/common/lib/accountActivity.ts @@ -21,6 +21,10 @@ export const SILENCE_MEDIAN_FACTOR = 3; export const SILENCE_MIN_HOURS = 48; +// A post dated outside 2006-01-01 (X's first year) … a day from now is a +// bogus date, not activity: one such date would stretch the strip to millions +// of days. It is left out. +export const ACTIVITY_EARLIEST = Date.parse("2006-01-01T00:00:00Z"); export type ActivityPost = { id: string; @@ -101,16 +105,17 @@ function utcDay(ms: number): string { // search channel's many accounts, a forum thread): every post counts. export function accountActivity( input: readonly ActivityPost[], - opts: { asOf?: string; minHours?: number; factor?: number; author?: string } = {}, + opts: { asOf?: string; minHours?: number; factor?: number; author?: string; now?: number } = {}, ): AccountActivity | null { const minHours = opts.minHours ?? SILENCE_MIN_HOURS; const factor = opts.factor ?? SILENCE_MEDIAN_FACTOR; const who = opts.author?.replace(/^@/, "").toLowerCase(); const own = who ? input.filter((p) => p.author?.replace(/^@/, "").toLowerCase() === who) : []; const author = own.length > 0 ? opts.author!.replace(/^@/, "") : null; + const latest = (opts.now ?? Date.now()) + DAY; const posts = (own.length > 0 ? own : input) .map((p) => ({ p, t: Date.parse(p.createdAt) })) - .filter((x) => Number.isFinite(x.t)) + .filter((x) => Number.isFinite(x.t) && x.t >= ACTIVITY_EARLIEST && x.t <= latest) .sort((a, b) => a.t - b.t || a.p.id.localeCompare(b.p.id)); if (posts.length < 2) return null; const gaps: number[] = []; diff --git a/common/lib/postTimes-server.test.ts b/common/lib/postTimes-server.test.ts @@ -0,0 +1,61 @@ +// The account activity's cheap read (lane x-console): each shard's light rows, +// cached by mtime and size, deduped by id, a missing permalink derived. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/postTimes-server.test.ts + +import test, { after } from "node:test"; +import assert from "node:assert/strict"; +import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { clearPostTimesCache, readChannelActivity, readPostTimes } from "./postTimes-server"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "post-times-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); +const channel = path.join(ROOT, "demo-x"); +mkdirSync(path.join(channel, "posts"), { recursive: true }); +const line = (id: string, createdAt: string, extra: Record<string, unknown> = {}) => + JSON.stringify({ id, channelSlug: "demo-x", createdAt, author: "demo", platform: "twitter", text: `first line ${id}\nsecond`, isReply: false, isRepost: false, links: [], url: `https://x.com/demo/status/${id}`, ...extra }) + "\n"; + +test("light rows from every shard, deduped by id, a missing url derived, a bad line skipped", async () => { + clearPostTimesCache(); + writeFileSync(path.join(channel, "posts", "2026-10.jsonl"), line("1", "2026-10-01T00:00:00Z") + "{not json\n" + line("2", "2026-10-02T00:00:00Z")); + writeFileSync(path.join(channel, "posts", "2026-11.jsonl"), line("2", "2026-10-02T00:00:00Z") + line("3", "2026-11-01T00:00:00Z", { url: undefined })); + const rows = await readPostTimes(channel); + assert.deepEqual( + rows.map((r) => [r.id, r.createdAt, r.author, r.url, r.text]).sort(), + [ + ["1", "2026-10-01T00:00:00Z", "demo", "https://x.com/demo/status/1", "first line 1"], + ["2", "2026-10-02T00:00:00Z", "demo", "https://x.com/demo/status/2", "first line 2"], + ["3", "2026-11-01T00:00:00Z", "demo", "https://x.com/demo/status/3", "first line 3"], + ], + ); +}); + +test("a shard a fetch appended to is re-read; the others come from the cache", async () => { + await readPostTimes(channel); + const oct = path.join(channel, "posts", "2026-10.jsonl"); + const nov = path.join(channel, "posts", "2026-11.jsonl"); + const octRows = globalThis.__yttPostTimes__!.get(oct)!.rows; + const novRows = globalThis.__yttPostTimes__!.get(nov)!.rows; + appendFileSync(nov, line("4", "2026-11-02T00:00:00Z")); + const rows = await readPostTimes(channel); + assert.deepEqual(rows.map((r) => r.id).sort(), ["1", "2", "3", "4"]); + // October was not re-read (the same rows); November was. + assert.equal(globalThis.__yttPostTimes__!.get(oct)!.rows, octRows); + assert.notEqual(globalThis.__yttPostTimes__!.get(nov)!.rows, novRows); + // No shards: nothing. + assert.deepEqual(await readPostTimes(path.join(ROOT, "nope")), []); +}); + +test("the activity is memoised by the shards' signature: the same object until a shard changes", async () => { + const one = await readChannelActivity(channel, { author: "demo" }); + assert.ok(one); + assert.equal(await readChannelActivity(channel, { author: "demo" }), one); + // Other options are another key. + assert.notEqual(await readChannelActivity(channel, { author: "demo", asOf: "2026-12-01T00:00:00Z" }), one); + appendFileSync(path.join(channel, "posts", "2026-11.jsonl"), line("5", "2026-11-03T00:00:00Z")); + const two = await readChannelActivity(channel, { author: "demo" }); + assert.notEqual(two, one); + assert.equal(two!.posts, one!.posts + 1); +}); diff --git a/common/lib/postTimes-server.ts b/common/lib/postTimes-server.ts @@ -0,0 +1,148 @@ +// A POSTS CHANNEL'S TIMES, CHEAPLY (lane x-console): what the account +// activity panel needs of every archived post — id, createdAt, author, +// permalink and a short first line — without materialising whole posts. +// +// readAllPosts parses, validates and sorts every post on every call: ~1 s for +// the largest posts channel (kf-quartering-thread, 66 MB, 37,802 posts) on +// every render of its page. This keeps each SHARD's light rows in memory, +// keyed by the shard's path and re-read only when its mtime or size changes +// (a fetch appends to the newest shard; the rest never change), so a render +// re-reads at most the shard a fetch just wrote. +// +// Dedupe by id across shards, as readAllPosts does (an interrupted archive +// write can leave one post in two shards). Unordered: accountActivity sorts. + +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { channelPostsDir, listPostShards } from "./posts-server"; +import { parsePost } from "./posts"; +import { accountActivity, type AccountActivity, type ActivityPost } from "./accountActivity"; + +type ShardRows = { mtimeMs: number; size: number; rows: ActivityPost[] }; + +// Shards kept, process-wide; the oldest entry goes first past this. +const MAX_SHARDS = 4000; + +declare global { + // eslint-disable-next-line no-var + var __yttPostTimes__: Map<string, ShardRows> | undefined; +} + +function cache(): Map<string, ShardRows> { + return (globalThis.__yttPostTimes__ ??= new Map()); +} + +export function clearPostTimesCache(): void { + globalThis.__yttPostTimes__?.clear(); + globalThis.__yttActivityMemo__?.clear(); +} + +function snippet(text: unknown): string | undefined { + if (typeof text !== "string") return undefined; + const first = text.split("\n", 8).find((l) => l.trim()); + if (!first) return undefined; + const t = first.trim(); + return t.length > 90 ? `${t.slice(0, 89)}…` : t; +} + +function rowsOf(text: string, channelSlug: string): ActivityPost[] { + const rows: ActivityPost[] = []; + for (const line of text.split("\n")) { + if (!line.trim()) continue; + let raw: Record<string, unknown>; + try { + raw = JSON.parse(line) as Record<string, unknown>; + } catch { + continue; + } + if (!raw || typeof raw !== "object") continue; + const { id, createdAt } = raw; + if (typeof id !== "string" || !id || typeof createdAt !== "string" || !createdAt) continue; + let url = typeof raw.url === "string" ? raw.url : ""; + // A record stored without its permalink: the full parse derives it (a + // forum post's needs its forum's origin). + if (!url) url = parsePost({ ...raw, channelSlug })?.url ?? ""; + rows.push({ + id, + createdAt, + url, + ...(typeof raw.author === "string" ? { author: raw.author } : {}), + ...(snippet(raw.text) ? { text: snippet(raw.text) } : {}), + }); + } + return rows; +} + +// The shards' identity: when no shard changed, nothing derived from them did. +async function shardSignature(channelRoot: string): Promise<string> { + const dir = channelPostsDir(channelRoot); + const parts: string[] = []; + for (const shard of await listPostShards(channelRoot)) { + try { + const st = await stat(path.join(dir, `${shard}.jsonl`)); + parts.push(`${shard}:${st.mtimeMs}:${st.size}`); + } catch { + // gone between the listing and the stat + } + } + return parts.join("|"); +} + +type ActivityMemo = { key: string; activity: AccountActivity | null }; + +declare global { + // eslint-disable-next-line no-var + var __yttActivityMemo__: Map<string, ActivityMemo> | undefined; +} + +// THE PANEL'S DATA: accountActivity over readPostTimes, memoised per channel +// by the shards' signature and the options — an unchanged channel costs one +// stat per shard (sorting 37,802 posts' dates is ~100 ms; a render should not +// pay it twice). A day's turn is part of the key too, so a bogus date's +// "a day from now" bound moves. +export async function readChannelActivity( + channelRoot: string, + opts: { asOf?: string; author?: string } = {}, +): Promise<AccountActivity | null> { + const memo = (globalThis.__yttActivityMemo__ ??= new Map()); + const key = `${await shardSignature(channelRoot)}#${opts.asOf ?? ""}#${opts.author ?? ""}#${new Date().toISOString().slice(0, 10)}`; + const hit = memo.get(channelRoot); + if (hit && hit.key === key) return hit.activity; + const activity = accountActivity(await readPostTimes(channelRoot), opts); + memo.delete(channelRoot); + memo.set(channelRoot, { key, activity }); + while (memo.size > 500) memo.delete(memo.keys().next().value!); + return activity; +} + +export async function readPostTimes(channelRoot: string): Promise<ActivityPost[]> { + const shards = await listPostShards(channelRoot); + const dir = channelPostsDir(channelRoot); + const channelSlug = path.basename(channelRoot); + const c = cache(); + const byId = new Map<string, ActivityPost>(); + for (const shard of shards) { + const file = path.join(dir, `${shard}.jsonl`); + let st; + try { + st = await stat(file); + } catch { + continue; + } + let hit = c.get(file); + if (!hit || hit.mtimeMs !== st.mtimeMs || hit.size !== st.size) { + let text: string; + try { + text = await readFile(file, "utf8"); + } catch { + continue; + } + hit = { mtimeMs: st.mtimeMs, size: st.size, rows: rowsOf(text, channelSlug) }; + c.delete(file); + c.set(file, hit); + while (c.size > MAX_SHARDS) c.delete(c.keys().next().value!); + } + for (const row of hit.rows) byId.set(row.id, row); + } + return [...byId.values()]; +} diff --git a/editor/app/channels/[slug]/components/AccountActivityPanel.tsx b/editor/app/channels/[slug]/components/AccountActivityPanel.tsx @@ -5,6 +5,7 @@ // the post before it and the post after. Read from the stored posts; a server // component, no client code. +import { readChannelActivity } from "yt-dlp-transcript-common/lib/postTimes-server"; import { medianText, spanHours, @@ -166,3 +167,33 @@ export function AccountActivityPanel({ activity }: { activity: AccountActivity } </section> ); } + +// The panel as the page streams it: the posts read through the cached light +// reader and the result memoised by the shards' signature +// (lib/postTimes-server.ts), behind the page's Suspense boundary. +export async function AccountActivitySection({ + channelRoot, + asOf, + author, +}: { + channelRoot: string; + asOf?: string; + author?: string; +}) { + const activity = await readChannelActivity(channelRoot, { + ...(asOf ? { asOf } : {}), + ...(author ? { author } : {}), + }); + return activity ? <AccountActivityPanel activity={activity} /> : null; +} + +export function AccountActivityLoading() { + return ( + <section + aria-label="account activity loading" + className="rounded-lg border border-border bg-card p-4 text-xs text-muted-foreground" + > + Reading the archived posts… + </section> + ); +} diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -1,5 +1,5 @@ import path from "node:path"; -import type { ReactNode } from "react"; +import { Suspense, type ReactNode } from "react"; import type { Metadata } from "next"; import { notFound } from "next/navigation"; import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; @@ -33,8 +33,7 @@ import { meanPagePauseSeconds, } from "yt-dlp-transcript-common/lib/forumWalk"; import { SocialChannelPanel } from "./components/SocialChannelPanel"; -import { AccountActivityPanel } from "./components/AccountActivityPanel"; -import { accountActivity } from "yt-dlp-transcript-common/lib/accountActivity"; +import { AccountActivityLoading, AccountActivitySection } from "./components/AccountActivityPanel"; import { WaybackPagesPanel } from "./components/WaybackPagesPanel"; import { WaybackLivePanel } from "./components/WaybackLivePanel"; import { waybackLiveState } from "./waybackLiveState"; @@ -248,14 +247,10 @@ export default async function ChannelDetailPage({ // ACCOUNT ACTIVITY (lane x-console): posts per day and the long silences, // from the stored posts — every posts channel but a Wayback pages one // (its records are captures) and an X search (its posts are many - // accounts' answers to a query, not one account's activity). - const activity = - !isWaybackPagesChannel(config) && !xSearch && postCount >= 2 - ? accountActivity(await readAllPosts(channelRoot), { - ...(fetchState?.lastFetchedAt ? { asOf: fetchState.lastFetchedAt } : {}), - ...(config.socialHandle ? { author: config.socialHandle } : {}), - }) - : null; + // accounts' answers to a query, not one account's activity). Streamed + // behind its own Suspense boundary, read through the cached light reader + // (lib/postTimes-server.ts), so the page never waits on the posts. + const showActivity = !isWaybackPagesChannel(config) && !xSearch && postCount >= 2; return ( <div className="flex flex-col gap-6"> <RunningJobsList jobs={socialRunningJobs} hideChannelSlug /> @@ -333,7 +328,15 @@ export default async function ChannelDetailPage({ }} /> )} - {activity && <AccountActivityPanel activity={activity} />} + {showActivity && ( + <Suspense fallback={<AccountActivityLoading />}> + <AccountActivitySection + channelRoot={channelRoot} + asOf={fetchState?.lastFetchedAt} + author={config.socialHandle} + /> + </Suspense> + )} {leads && leads.ok && <XSearchLeadsPanel slug={slug} leads={leads} />} {/* THE SAME DANGER ZONE A VIDEO CHANNEL HAS, which a social channel used to lack entirely: this branch returns before the stage list,