Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
183 lines
10 KiB
TypeScript
183 lines
10 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import { spawnSync } from "node:child_process";
|
|
import { fileURLToPath } from "node:url";
|
|
import test from "node:test";
|
|
|
|
import { buildLongformOutline } from "../src/lib/personal-report-longform-outline";
|
|
import { dataChapters, readerMarkdown } from "../src/lib/personal-report-outline-view";
|
|
|
|
// BUG-2175 (left over from BUG-2138): every single-chapter read loaded and cut the whole stored text
|
|
// (≈3 MB). Chapters now come from a bounded in-process cache checked against the stored text's
|
|
// version, after the same sign-in, origin and ownership checks. Fictional filler only (AGENTS §7-6).
|
|
|
|
const frontendRoot = fileURLToPath(new URL("../", import.meta.url));
|
|
const REPORT_ID = "00000000-0000-4000-8000-000000002175";
|
|
|
|
function pagedMarkdown(mark: string): string {
|
|
const chapters = [0, 1, 2, 3].map((index) => [
|
|
`## 第${index + 1}章 虚构章节`,
|
|
`第${index + 1}章开头${mark}。`,
|
|
Array.from({ length: 1500 }, (_, line) => `第${index + 1}章虚构的第${line + 1}段文字,没有任何真实的人。`).join("\n\n"),
|
|
].join("\n\n"));
|
|
return ["# 虚构星盘报告", ...chapters].join("\n\n");
|
|
}
|
|
const ZH = pagedMarkdown("");
|
|
const ZH_NEW = pagedMarkdown("(新)");
|
|
const EN = ["# Fictional chart report", ...[0, 1, 2].map((index) => [
|
|
`## Chapter ${index + 1} fictional`,
|
|
Array.from({ length: 3000 }, (_, line) => `Fictional paragraph ${line + 1} of chapter ${index + 1}, about nobody real.`).join("\n\n"),
|
|
].join("\n\n"))].join("\n\n");
|
|
|
|
test("BUG-2175 the chapter cache keeps at most its entries and characters, drops a stale version, never keeps an oversized edition", async () => {
|
|
const { createChapterCache, CHAPTER_CACHE_MAX_CHARS, CHAPTER_CACHE_MAX_ENTRIES, storedTextChapters } = await import("../src/lib/personal-report-chapter-cache");
|
|
assert.ok(CHAPTER_CACHE_MAX_ENTRIES <= 8 && CHAPTER_CACHE_MAX_CHARS <= 12_000_000, "a hard cap for the 4 GB host");
|
|
const chapter = (chars: number) => [{ id: "a", title: "t", markdown: "x".repeat(chars) }];
|
|
const cache = createChapterCache({ maxEntries: 3, maxChars: 1000 });
|
|
cache.set("1", "v1", chapter(100));
|
|
cache.set("2", "v1", chapter(100));
|
|
cache.set("3", "v1", chapter(100));
|
|
assert.ok(cache.get("1", "v1"), "read: now the most recent");
|
|
cache.set("4", "v1", chapter(100));
|
|
assert.equal(cache.get("2", "v1"), null, "the least recently read goes first");
|
|
assert.equal(cache.stats().entries, 3);
|
|
cache.set("5", "v1", chapter(800));
|
|
assert.ok(cache.stats().chars <= 1000, `chars ${cache.stats().chars}`);
|
|
cache.set("6", "v1", chapter(2000));
|
|
assert.equal(cache.get("6", "v1"), null, "an edition over the whole budget is not kept");
|
|
assert.ok(cache.stats().chars <= 1000);
|
|
assert.equal(cache.get("5", "v2"), null, "another version of the stored text is a miss");
|
|
assert.equal(cache.get("5", "v1"), null, "and the stale entry is gone");
|
|
// The cut is the page's own cut.
|
|
assert.deepEqual(storedTextChapters(ZH, "zh").map((c) => c.markdown), dataChapters(buildLongformOutline(readerMarkdown(ZH))).map((c) => c.markdown));
|
|
});
|
|
|
|
type Read = { name: string; status: number; markdown?: string; selects: string[] };
|
|
|
|
function probe(): Read[] {
|
|
const script = String.raw`
|
|
import { mock } from "node:test";
|
|
import { pathToFileURL } from "node:url";
|
|
const moduleUrl = (path) => pathToFileURL(process.cwd() + "/" + path).href;
|
|
const OWNER = "00000000-0000-4000-8000-0000000000aa";
|
|
const STRANGER = "00000000-0000-4000-8000-0000000000bb";
|
|
const REPORT = ${JSON.stringify(REPORT_ID)};
|
|
const TEXTS = { old: ${JSON.stringify(ZH)}, fresh: ${JSON.stringify(ZH_NEW)} };
|
|
const EN = ${JSON.stringify(EN)};
|
|
let snapshotReads = 0;
|
|
mock.module("@/lib/personal-report-longform-snapshot", { namedExports: {
|
|
LONGFORM_SNAPSHOT_SECTION_ID: "longform-calculation-snapshot-v1",
|
|
readLongformSnapshot: async () => {
|
|
snapshotReads += 1;
|
|
return { status: "ready", snapshot: { version: 2, english: { markdown: EN, factTables: [] }, reading: null } };
|
|
},
|
|
}});
|
|
let stored = { markdown: TEXTS.old, sha: "1".repeat(64) };
|
|
let user = OWNER;
|
|
let selects = [];
|
|
mock.module("server-only", { namedExports: {} });
|
|
const chain = (table) => {
|
|
const filters = {};
|
|
let columns = "*";
|
|
const result = () => {
|
|
if (table === "personal_report_sections" && filters.user_id === OWNER && filters.section_id === "longform-calculation-snapshot-v1") {
|
|
return { data: { status: "ready", updated_at: "2026-11-22T00:10:00.000Z" }, error: null };
|
|
}
|
|
if (table !== "personal_report_longform_appendices" || filters.user_id !== OWNER || filters.report_id !== REPORT) return { data: null, error: null };
|
|
const row = { report_id: REPORT, user_id: OWNER, request_id: "00000000-0000-4000-8000-0000000000cc", status: "ready", markdown: stored.markdown, content_sha256: stored.sha, attempt_count: 1, last_error_code: null };
|
|
return { data: Object.fromEntries(columns.split(",").map((c) => [c, row[c]])), error: null };
|
|
};
|
|
const proxy = new Proxy({}, {
|
|
get(_t, key) {
|
|
if (key === "then") return (resolve) => resolve({ data: [], error: null });
|
|
if (key === "maybeSingle" || key === "single") return async () => result();
|
|
if (key === "select") return (c) => { columns = c; selects.push(table + ":" + c); return proxy; };
|
|
if (key === "eq") return (c, v) => { filters[c] = v; return proxy; };
|
|
return () => proxy;
|
|
},
|
|
});
|
|
return proxy;
|
|
};
|
|
mock.module("@/lib/supabase/server", { namedExports: {
|
|
createServerSupabaseClient: async () => ({
|
|
auth: { getUser: async () => ({ data: { user: user ? { id: user } : null }, error: null }) },
|
|
from: (t) => chain(t),
|
|
rpc: async () => ({ data: null, error: null }),
|
|
}),
|
|
}});
|
|
let ownedReads = 0;
|
|
mock.module("@/lib/personal-report-service", { namedExports: {
|
|
createSupabasePersonalReportService: () => ({
|
|
getOwnedById: async (u, r) => {
|
|
ownedReads += 1;
|
|
return u === OWNER && r === REPORT ? {
|
|
id: REPORT, userId: OWNER, requestId: "00000000-0000-4000-8000-0000000000cc", reportType: "personal_full", presentationMode: "longform", depth: "full",
|
|
status: "ready", failureCode: null, createdAt: "2026-11-22T00:00:00.000Z", completedAt: "2026-11-22T00:10:00.000Z", reportDocument: {}, requestedThemes: [],
|
|
} : null;
|
|
},
|
|
}),
|
|
}});
|
|
mock.module("@/lib/personal-report-job-service", { namedExports: { createSupabasePersonalReportJobService: () => ({ getOwnedByRequestId: async () => null }) } });
|
|
mock.module("@/lib/personal-report-section-service", { namedExports: { createPersonalReportSectionService: () => ({ list: async () => [] }) } });
|
|
const chapter = await import(moduleUrl("src/app/api/reports/[reportId]/chapters/[index]/route.ts"));
|
|
const out = [];
|
|
async function call(name, index, query = "") {
|
|
selects = [];
|
|
ownedReads = 0;
|
|
snapshotReads = 0;
|
|
const response = await chapter.GET(new Request("https://staging.example/api/reports/" + REPORT + "/chapters/" + index + query), { params: Promise.resolve({ reportId: REPORT, index: String(index) }) });
|
|
const body = await response.json();
|
|
out.push({ name, status: response.status, markdown: body.markdown, selects: [...selects, "owned:" + ownedReads, "snapshot:" + snapshotReads] });
|
|
}
|
|
await call("cold", 1);
|
|
await call("warm", 3);
|
|
await call("warmOut", 9);
|
|
user = STRANGER;
|
|
await call("stranger", 1);
|
|
user = null;
|
|
await call("signedOut", 1);
|
|
user = OWNER;
|
|
stored = { markdown: TEXTS.fresh, sha: "2".repeat(64) };
|
|
await call("changed", 1);
|
|
await call("enCold", 1, "?lang=en");
|
|
await call("enWarm", 2, "?lang=en");
|
|
console.log("CACHE_RESULT " + JSON.stringify(out));
|
|
`;
|
|
const result = spawnSync(process.execPath, ["--experimental-test-module-mocks", "--import", "tsx", "--input-type=module", "-"], {
|
|
cwd: frontendRoot,
|
|
input: script,
|
|
encoding: "utf8",
|
|
maxBuffer: 64 * 1024 * 1024,
|
|
env: { ...process.env, NODE_NO_WARNINGS: "1" },
|
|
});
|
|
assert.equal(result.status, 0, result.stderr || result.stdout);
|
|
const line = result.stdout.split("\n").find((row) => row.startsWith("CACHE_RESULT "));
|
|
assert.ok(line, result.stdout + result.stderr);
|
|
return JSON.parse(line.slice("CACHE_RESULT ".length)) as Read[];
|
|
}
|
|
|
|
test("BUG-2175 a chapter read after the first reads one small version row, not the whole text; sign-in and ownership still come first", () => {
|
|
const reads = Object.fromEntries(probe().map((read) => [read.name, read]));
|
|
const page = dataChapters(buildLongformOutline(readerMarkdown(ZH)));
|
|
const textReads = (read: Read) => read.selects.filter((select) => select.includes("markdown")).length;
|
|
assert.equal(reads.cold!.status, 200);
|
|
assert.equal(reads.cold!.markdown, page[1]!.markdown);
|
|
assert.equal(textReads(reads.cold!), 1, "the first read reads the text once");
|
|
assert.ok(reads.cold!.selects.includes("owned:1"), `the owned row is read once per request: ${reads.cold!.selects.join(" ")}`);
|
|
assert.equal(reads.warm!.status, 200);
|
|
assert.equal(reads.warm!.markdown, page[3]!.markdown, "byte for byte the chapter the page cuts");
|
|
assert.equal(textReads(reads.warm!), 0, `no whole-text read: ${reads.warm!.selects.join(" ")}`);
|
|
assert.ok(reads.warm!.selects.includes("personal_report_longform_appendices:status,content_sha256"));
|
|
assert.equal(reads.warmOut!.status, 404);
|
|
assert.equal(reads.stranger!.status, 404, "another account never gets the cached chapter");
|
|
assert.equal(reads.stranger!.markdown, undefined);
|
|
assert.equal(reads.signedOut!.status, 401);
|
|
assert.equal(reads.changed!.status, 200);
|
|
assert.equal(reads.changed!.markdown, dataChapters(buildLongformOutline(readerMarkdown(ZH_NEW)))[1]!.markdown, "a new stored text is read again");
|
|
assert.equal(textReads(reads.changed!), 1);
|
|
const english = dataChapters(buildLongformOutline(readerMarkdown(EN, "en")));
|
|
assert.equal(reads.enCold!.markdown, english[1]!.markdown);
|
|
assert.ok(reads.enCold!.selects.includes("snapshot:1"));
|
|
assert.equal(reads.enWarm!.markdown, english[2]!.markdown);
|
|
assert.ok(reads.enWarm!.selects.includes("snapshot:0"), `an English chapter after the first skips the snapshot: ${reads.enWarm!.selects.join(" ")}`);
|
|
});
|