Skip to content

Open source alternative to Semrush and Ahrefs

perf(audit): store each page's link targets as one JSON row in the scratchpad DO (#568)

Ben Senescu78a7e283ace5
diff --git a/src/server/features/audit/AuditScratchpad.test.ts b/src/server/features/audit/AuditScratchpad.test.ts
new file mode 100644
index 00000000..381183d5
--- /dev/null
+++ b/src/server/features/audit/AuditScratchpad.test.ts
@@ -0,0 +1,252 @@
+/**
+ * The scratchpad's finalize queries run against a real SQLite engine here —
+ * node:sqlite ships the same JSON1 functions the Durable Object's SQLite
+ * exposes, so the exact query strings the DO executes can be exercised
+ * without a Workers runtime.
+ */
+import { DatabaseSync } from "node:sqlite";
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ BROKEN_LINKS_SQL,
+ ORPHAN_PAGES_SQL,
+ SCRATCHPAD_SCHEMA_SQL,
+} from "@/server/features/audit/scratchpad-sql";
+
+const START = "https://site.test/";
+
+let db: DatabaseSync;
+
+function addPage(
+ pageId: string,
+ url: string,
+ opts: {
+ status?: number;
+ fetchClass?: string;
+ redirectUrl?: string | null;
+ } = {},
+) {
+ db.prepare(
+ `INSERT INTO page_mirror (page_id, url, status_code, fetch_class, redirect_url)
+ VALUES (?, ?, ?, ?, ?)`,
+ ).run(
+ pageId,
+ url,
+ opts.status ?? 200,
+ opts.fetchClass ?? "ok",
+ opts.redirectUrl ?? null,
+ );
+}
+
+function addLinks(pageId: string, url: string, targets: string[]) {
+ db.prepare(
+ `INSERT OR REPLACE INTO page_links (page_id, url, targets_json) VALUES (?, ?, ?)`,
+ ).run(pageId, url, JSON.stringify(targets));
+}
+
+function addLegacyLinks(pageId: string, url: string, targets: string[]) {
+ for (const target of targets) {
+ db.prepare(
+ `INSERT OR IGNORE INTO links (source_page_id, source_url, target_url) VALUES (?, ?, ?)`,
+ ).run(pageId, url, target);
+ }
+}
+
+function brokenLinks(limit = 100) {
+ return db.prepare(BROKEN_LINKS_SQL).all(limit);
+}
+
+function orphanPages() {
+ return db.prepare(ORPHAN_PAGES_SQL).all(START);
+}
+
+beforeEach(() => {
+ db = new DatabaseSync(":memory:");
+ db.exec(SCRATCHPAD_SCHEMA_SQL);
+});
+
+describe("broken internal links", () => {
+ it("reports a crawled-and-failed target once, with its status", () => {
+ addPage("p1", START);
+ addPage("p2", "https://site.test/gone", { status: 404 });
+ addLinks("p1", START, ["https://site.test/gone"]);
+
+ expect(brokenLinks()).toEqual([
+ {
+ source_page_id: "p1",
+ source_url: START,
+ target_url: "https://site.test/gone",
+ target_status: 404,
+ },
+ ]);
+ });
+
+ it("ignores targets that were never crawled and targets that are fine", () => {
+ addPage("p1", START);
+ addPage("p2", "https://site.test/ok");
+ addLinks("p1", START, [
+ "https://site.test/ok",
+ "https://site.test/never-crawled",
+ ]);
+
+ expect(brokenLinks()).toEqual([]);
+ });
+
+ it("ignores WAF-blocked 4xx targets", () => {
+ addPage("p1", START);
+ addPage("p2", "https://site.test/waf", {
+ status: 403,
+ fetchClass: "blocked",
+ });
+ addLinks("p1", START, ["https://site.test/waf"]);
+
+ expect(brokenLinks()).toEqual([]);
+ });
+
+ it("includes legacy per-edge rows from a crawl that predates the JSON layout", () => {
+ addPage("p1", START);
+ addPage("p2", "https://site.test/two");
+ addPage("p3", "https://site.test/gone", { status: 500 });
+ addLegacyLinks("p1", START, ["https://site.test/gone"]);
+ addLinks("p2", "https://site.test/two", ["https://site.test/gone"]);
+
+ expect(brokenLinks().map((row) => row.source_page_id)).toEqual([
+ "p1",
+ "p2",
+ ]);
+ });
+
+ it("respects the row limit and orders deterministically", () => {
+ addPage("p1", START);
+ for (let i = 0; i < 5; i += 1) {
+ addPage(`b${i}`, `https://site.test/gone-${i}`, { status: 404 });
+ }
+ addLinks(
+ "p1",
+ START,
+ Array.from({ length: 5 }, (_, i) => `https://site.test/gone-${i}`),
+ );
+
+ expect(brokenLinks(2).map((row) => row.target_url)).toEqual([
+ "https://site.test/gone-0",
+ "https://site.test/gone-1",
+ ]);
+ });
+});
+
+describe("orphan pages", () => {
+ it("flags a 2xx page nothing links to", () => {
+ addPage("p1", START);
+ addPage("p2", "https://site.test/lonely");
+ addLinks("p1", START, ["https://site.test/other"]);
+
+ expect(orphanPages()).toEqual([
+ { page_id: "p2", url: "https://site.test/lonely" },
+ ]);
+ });
+
+ it("does not rescue a page that only links to itself", () => {
+ addPage("p1", START);
+ addPage("p2", "https://site.test/lonely");
+ addLinks("p2", "https://site.test/lonely", ["https://site.test/lonely"]);
+
+ expect(orphanPages()).toEqual([
+ { page_id: "p2", url: "https://site.test/lonely" },
+ ]);
+ });
+
+ it("does not flag a page linked from another page", () => {
+ addPage("p1", START);
+ addPage("p2", "https://site.test/linked");
+ addLinks("p1", START, ["https://site.test/linked"]);
+
+ expect(orphanPages()).toEqual([]);
+ });
+
+ it("does not flag a page something redirects to", () => {
+ addPage("p1", START);
+ addPage("p2", "https://site.test/target");
+ addPage("p3", "https://site.test/old", {
+ status: 301,
+ redirectUrl: "https://site.test/target",
+ });
+
+ expect(orphanPages()).toEqual([]);
+ });
+
+ it("never flags the start URL", () => {
+ addPage("p1", START);
+
+ expect(orphanPages()).toEqual([]);
+ });
+
+ it("ignores non-2xx and blocked pages", () => {
+ addPage("p1", START);
+ addPage("p2", "https://site.test/gone", { status: 404 });
+ addPage("p3", "https://site.test/waf", {
+ status: 200,
+ fetchClass: "blocked",
+ });
+
+ expect(orphanPages()).toEqual([]);
+ });
+
+ it("counts legacy per-edge rows as inbound links", () => {
+ addPage("p1", START);
+ addPage("p2", "https://site.test/linked");
+ addPage("p3", "https://site.test/self");
+ addLegacyLinks("p1", START, ["https://site.test/linked"]);
+ addLegacyLinks("p3", "https://site.test/self", ["https://site.test/self"]);
+
+ expect(orphanPages()).toEqual([
+ { page_id: "p3", url: "https://site.test/self" },
+ ]);
+ });
+});
+
+describe("query plans", () => {
+ /**
+ * Both checks must stay linear in link count. The failure mode to guard is
+ * page_mirror (or the inbound set) being rescanned inside a per-row loop,
+ * which is what an unhinted join order or a correlated NOT EXISTS produces.
+ */
+ function plan(sql: string, param: string | number): string[] {
+ return db
+ .prepare(`EXPLAIN QUERY PLAN ${sql}`)
+ .all(param)
+ .map((row) => String(row["detail"]));
+ }
+
+ beforeEach(() => {
+ for (let i = 0; i < 50; i += 1) {
+ addPage(`p${i}`, `https://site.test/${i}`);
+ addLinks(
+ `p${i}`,
+ `https://site.test/${i}`,
+ Array.from(
+ { length: 10 },
+ (_, k) => `https://site.test/${(i + k) % 50}`,
+ ),
+ );
+ }
+ });
+
+ it("seeks page_mirror by url for every link target", () => {
+ const detail = plan(BROKEN_LINKS_SQL, 100);
+ expect(detail).toContain(
+ "SEARCH m USING INDEX sqlite_autoindex_page_mirror_2 (url=?)",
+ );
+ expect(detail.some((line) => /SCAN m\b/.test(line))).toBe(false);
+ });
+
+ it("materializes the inbound set once and probes it by index", () => {
+ const detail = plan(ORPHAN_PAGES_SQL, START);
+ expect(detail).toContain("MATERIALIZE inbound");
+ expect(
+ detail.some((line) =>
+ line.includes("SEARCH inbound USING AUTOMATIC COVERING INDEX"),
+ ),
+ ).toBe(true);
+ // page_mirror is scanned once as the outer loop, never per inbound row.
+ expect(detail.filter((line) => /SCAN m\b/.test(line))).toHaveLength(1);
+ });
+});
diff --git a/src/server/features/audit/AuditScratchpad.ts b/src/server/features/audit/AuditScratchpad.ts
index 59ff6e8d..d473f21c 100644
--- a/src/server/features/audit/AuditScratchpad.ts
+++ b/src/server/features/audit/AuditScratchpad.ts
@@ -2,10 +2,11 @@
* Per-audit crawl scratchpad — a SQLite-backed Durable Object.
*
* Holds all transient crawl state for one audit (id = auditId): the frontier
- * (URL queue + seen-set), the internal-link edges, and a slim mirror of page
- * rows. This keeps chatty crawl-loop writes off Postgres, removes the ~1MiB
- * Workflow step-output limits (nothing large flows through step returns
- * anymore), and gives the finalize link checks a local SQL database.
+ * (URL queue + seen-set), each page's internal link targets, and a slim
+ * mirror of page rows. This keeps chatty crawl-loop writes off Postgres,
+ * removes the ~1MiB Workflow step-output limits (nothing large flows through
+ * step returns anymore), and gives the finalize link checks a local SQL
+ * database.
*
* Lifecycle: seeded by the discover-urls step, read/written by every crawl
* chunk, queried once at finalize, then destroyed on success. A self-cleanup
@@ -18,6 +19,11 @@
* every insert is OR IGNORE / OR REPLACE on a stable key.
*/
import { DurableObject, env } from "cloudflare:workers";
+import {
+ BROKEN_LINKS_SQL,
+ ORPHAN_PAGES_SQL,
+ SCRATCHPAD_SCHEMA_SQL,
+} from "@/server/features/audit/scratchpad-sql";
export interface ClaimedUrl {
url: string;
@@ -54,19 +60,19 @@ interface ScratchpadPageRow {
redirectUrl: string | null;
}
-export interface ScratchpadLinkRow {
- sourcePageId: string;
- sourceUrl: string;
- targetUrl: string;
- anchor: string | null;
- isNofollow: boolean;
+/** One crawled page's internal link targets — the whole row is one write. */
+export interface ScratchpadPageLinksRow {
+ pageId: string;
+ url: string;
+ /** Same-origin link targets, already deduped by the page analyzer. */
+ targets: string[];
}
interface RecordBatchInput {
/** URLs whose crawl attempt finished (successfully or not). */
crawledUrls: string[];
pages: ScratchpadPageRow[];
- links: ScratchpadLinkRow[];
+ links: ScratchpadPageLinksRow[];
/** Newly discovered same-origin URLs to enqueue (already policy-filtered). */
discovered: Array<{ url: string; depth: number | null }>;
}
@@ -86,10 +92,10 @@ interface OrphanPageRow {
const BROKEN_LINK_ISSUE_CAP = 2_000;
const CLEANUP_AFTER_MS = 7 * 24 * 60 * 60 * 1000;
/**
- * Stop storing link edges once the database reaches this size. Link rows are
- * the only unbounded-per-page data; a pathological link-dense site could
- * otherwise hit the platform's per-object SQLite cap (1 GB on the free plan
- * self-hosters may run on) and fail the crawl with SQLITE_FULL. Past the
+ * Stop storing link targets once the database reaches this size. The link
+ * arrays are the only unbounded-per-page data; a pathological link-dense site
+ * could otherwise hit the platform's per-object SQLite cap (1 GB on the free
+ * plan self-hosters may run on) and fail the crawl with SQLITE_FULL. Past the
* budget the crawl continues — the audit just loses link-graph issues.
*/
const LINK_STORAGE_BUDGET_BYTES = 500 * 1024 * 1024;
@@ -97,37 +103,10 @@ const LINK_STORAGE_BUDGET_BYTES = 500 * 1024 * 1024;
export class AuditScratchpad extends DurableObject {
constructor(ctx: DurableObjectState, workerEnv: Env) {
super(ctx, workerEnv);
- this.ctx.storage.sql.exec(`
- CREATE TABLE IF NOT EXISTS frontier (
- url TEXT PRIMARY KEY,
- depth INTEGER,
- source TEXT NOT NULL,
- in_sitemap INTEGER NOT NULL DEFAULT 0,
- state TEXT NOT NULL DEFAULT 'pending',
- chunk_no INTEGER
- );
- CREATE INDEX IF NOT EXISTS frontier_claim_idx ON frontier (state, source);
- CREATE TABLE IF NOT EXISTS links (
- source_page_id TEXT NOT NULL,
- source_url TEXT NOT NULL,
- target_url TEXT NOT NULL,
- anchor TEXT,
- is_nofollow INTEGER NOT NULL DEFAULT 0,
- PRIMARY KEY (source_page_id, target_url)
- );
- CREATE INDEX IF NOT EXISTS links_target_idx ON links (target_url);
- CREATE TABLE IF NOT EXISTS page_mirror (
- page_id TEXT PRIMARY KEY,
- url TEXT NOT NULL UNIQUE,
- status_code INTEGER,
- fetch_class TEXT NOT NULL,
- redirect_url TEXT
- );
- CREATE INDEX IF NOT EXISTS page_mirror_redirect_idx ON page_mirror (redirect_url);
- `);
+ this.ctx.storage.sql.exec(SCRATCHPAD_SCHEMA_SQL);
// Guarantee the cleanup alarm on EVERY instantiation, not just at seed:
// any RPC (even one racing in right after destroy()) re-creates the
- // tables above, and without an alarm that storage would leak forever.
+ // schema, and without an alarm that storage would leak forever.
// blockConcurrencyWhile gates RPC delivery on its own; the returned
// promise doesn't need observing (constructors can't await).
void this.ctx.blockConcurrencyWhile(() => this.ensureCleanupAlarm());
@@ -216,15 +195,12 @@ export class AuditScratchpad extends DurableObject {
// once the budget trips it stays tripped — runFinalizeChecks uses the
// same comparison to know the link graph is incomplete.
if (this.ctx.storage.sql.databaseSize < LINK_STORAGE_BUDGET_BYTES) {
- for (const link of input.links) {
+ for (const page of input.links) {
this.ctx.storage.sql.exec(
- `INSERT OR IGNORE INTO links (source_page_id, source_url, target_url, anchor, is_nofollow)
- VALUES (?, ?, ?, ?, ?)`,
- link.sourcePageId,
- link.sourceUrl,
- link.targetUrl,
- link.anchor,
- link.isNofollow ? 1 : 0,
+ `INSERT OR REPLACE INTO page_links (page_id, url, targets_json) VALUES (?, ?, ?)`,
+ page.pageId,
+ page.url,
+ JSON.stringify(page.targets),
);
}
}
@@ -271,14 +247,7 @@ export class AuditScratchpad extends DurableObject {
source_url: string;
target_url: string;
target_status: number;
- }>(
- `SELECT l.source_page_id, l.source_url, l.target_url, m.status_code AS target_status
- FROM links l JOIN page_mirror m ON m.url = l.target_url
- WHERE m.status_code >= 400 AND m.fetch_class = 'ok'
- ORDER BY l.source_page_id, l.target_url
- LIMIT ?`,
- BROKEN_LINK_ISSUE_CAP,
- )
+ }>(BROKEN_LINKS_SQL, BROKEN_LINK_ISSUE_CAP)
.toArray()
.map((row) => ({
sourcePageId: row.source_page_id,
@@ -296,20 +265,10 @@ export class AuditScratchpad extends DurableObject {
const orphanPages =
input.crawlCompleted && linkGraphComplete
? this.ctx.storage.sql
- .exec<{ page_id: string; url: string }>(
- `SELECT m.page_id, m.url FROM page_mirror m
- WHERE m.url != ?
- AND m.fetch_class = 'ok'
- AND m.status_code >= 200 AND m.status_code < 300
- AND NOT EXISTS (
- SELECT 1 FROM links l
- WHERE l.target_url = m.url AND l.source_page_id != m.page_id
- )
- AND NOT EXISTS (
- SELECT 1 FROM page_mirror r WHERE r.redirect_url = m.url
- )`,
- input.startUrl,
- )
+ .exec<{
+ page_id: string;
+ url: string;
+ }>(ORPHAN_PAGES_SQL, input.startUrl)
.toArray()
.map((row) => ({ pageId: row.page_id, url: row.url }))
: [];
diff --git a/src/server/features/audit/scratchpad-sql.ts b/src/server/features/audit/scratchpad-sql.ts
new file mode 100644
index 00000000..2b0eaaa7
--- /dev/null
+++ b/src/server/features/audit/scratchpad-sql.ts
@@ -0,0 +1,103 @@
+/**
+ * The scratchpad's SQLite schema and its two finalize link queries, kept in a
+ * plain module (no `cloudflare:workers` import) so they can be exercised
+ * against a real SQLite engine in tests as well as inside the Durable Object.
+ */
+
+/**
+ * `page_links` holds one row per crawled page — its internal link targets as
+ * a JSON array of URL strings — instead of one row per edge. Rows written is
+ * the DO SQLite billing unit, and link edges dominate an audit's writes.
+ * WITHOUT ROWID keeps the TEXT primary key as the table itself, so a page
+ * costs exactly one row written rather than a row plus an autoindex entry.
+ *
+ * The legacy per-edge `links` table is still declared (without its target
+ * index, which nothing queries any more) so an audit that was mid-crawl when
+ * the JSON layout shipped can still be finalized from the rows its earlier
+ * chunks wrote. Delete the table and the UNION ALL branches in the queries
+ * below after 2026-09-10: the 7-day cleanup alarm guarantees every such
+ * object is finished or wiped by then.
+ */
+export const SCRATCHPAD_SCHEMA_SQL = `
+ CREATE TABLE IF NOT EXISTS frontier (
+ url TEXT PRIMARY KEY,
+ depth INTEGER,
+ source TEXT NOT NULL,
+ in_sitemap INTEGER NOT NULL DEFAULT 0,
+ state TEXT NOT NULL DEFAULT 'pending',
+ chunk_no INTEGER
+ );
+ CREATE INDEX IF NOT EXISTS frontier_claim_idx ON frontier (state, source);
+ CREATE TABLE IF NOT EXISTS page_links (
+ page_id TEXT PRIMARY KEY,
+ url TEXT NOT NULL,
+ targets_json TEXT NOT NULL
+ ) WITHOUT ROWID;
+ CREATE TABLE IF NOT EXISTS links (
+ source_page_id TEXT NOT NULL,
+ source_url TEXT NOT NULL,
+ target_url TEXT NOT NULL,
+ PRIMARY KEY (source_page_id, target_url)
+ );
+ CREATE TABLE IF NOT EXISTS page_mirror (
+ page_id TEXT PRIMARY KEY,
+ url TEXT NOT NULL UNIQUE,
+ status_code INTEGER,
+ fetch_class TEXT NOT NULL,
+ redirect_url TEXT
+ );
+ CREATE INDEX IF NOT EXISTS page_mirror_redirect_idx ON page_mirror (redirect_url);
+`;
+
+/**
+ * Every internal link whose target we crawled and saw fail. `json_each`
+ * expands a page's target array into one row per edge; the join is on
+ * page_mirror's UNIQUE url, so it stays an index seek per link. CROSS JOIN
+ * pins that order — left to itself the planner drives page_mirror off
+ * `fetch_class` via an automatic index and re-expands the JSON array per
+ * candidate, which is quadratic in page count. Takes the issue cap as its
+ * only parameter.
+ */
+export const BROKEN_LINKS_SQL = `
+ SELECT source_page_id, source_url, target_url, target_status FROM (
+ SELECT p.page_id AS source_page_id, p.url AS source_url, j.value AS target_url,
+ m.status_code AS target_status
+ FROM page_links p, json_each(p.targets_json) AS j
+ CROSS JOIN page_mirror m ON m.url = j.value
+ WHERE m.status_code >= 400 AND m.fetch_class = 'ok'
+ UNION ALL
+ SELECT l.source_page_id, l.source_url, l.target_url, m.status_code AS target_status
+ FROM links l JOIN page_mirror m ON m.url = l.target_url
+ WHERE m.status_code >= 400 AND m.fetch_class = 'ok'
+ )
+ ORDER BY source_page_id, target_url
+ LIMIT ?
+`;
+
+/**
+ * Pages nothing links to. The inbound set is built once and anti-joined,
+ * rather than probed per page: without the old per-edge target index a
+ * correlated NOT EXISTS would rescan the whole edge set for every page.
+ * Self-links don't count (a page linking to itself doesn't rescue it), and
+ * page_id is 1:1 with url in page_mirror, so comparing URLs is the same test
+ * the per-edge form made on ids. Takes the start URL as its only parameter.
+ */
+export const ORPHAN_PAGES_SQL = `
+ SELECT m.page_id, m.url FROM page_mirror m
+ LEFT JOIN (
+ SELECT DISTINCT j.value AS target_url
+ FROM page_links p, json_each(p.targets_json) AS j
+ WHERE j.value != p.url
+ UNION ALL
+ SELECT DISTINCT l.target_url
+ FROM links l
+ WHERE l.target_url != l.source_url
+ ) inbound ON inbound.target_url = m.url
+ WHERE m.url != ?
+ AND m.fetch_class = 'ok'
+ AND m.status_code >= 200 AND m.status_code < 300
+ AND inbound.target_url IS NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM page_mirror r WHERE r.redirect_url = m.url
+ )
+`;
diff --git a/src/server/workflows/siteAuditWorkflowCrawl.ts b/src/server/workflows/siteAuditWorkflowCrawl.ts
index b090955f..1e04354d 100644
--- a/src/server/workflows/siteAuditWorkflowCrawl.ts
+++ b/src/server/workflows/siteAuditWorkflowCrawl.ts
@@ -10,7 +10,7 @@ import {
getAuditScratchpad,
type ClaimedUrl,
type FrontierStats,
- type ScratchpadLinkRow,
+ type ScratchpadPageLinksRow,
} from "@/server/features/audit/AuditScratchpad";
import { AuditProgressKV } from "@/server/lib/audit/progress-kv";
import {
@@ -54,7 +54,8 @@ const MAX_QUEUED_PERSIST_BATCHES = 2;
/**
* Mega-menu/footer-heavy sites can carry 1000+ links per page; cap what we
- * record so a 10k-page crawl can't produce tens of millions of link rows.
+ * record so a 10k-page crawl can't produce tens of millions of link targets
+ * to scan at finalize.
*/
const MAX_STORED_LINKS_PER_PAGE = 500;
/**
@@ -302,24 +303,17 @@ async function persistCrawledPages(input: {
const issues = pages.flatMap((page) => runPageReporters(page));
await AuditRepository.insertCrawledBatch(auditId, pages, issues);
- const links: ScratchpadLinkRow[] = [];
+ const links: ScratchpadPageLinksRow[] = [];
const discovered = new Map<string, number | null>();
for (const page of pages) {
const pageDepth = depthByUrl.get(page.url) ?? null;
const childDepth = pageDepth === null ? null : pageDepth + 1;
- let storedForPage = 0;
+ const targets: string[] = [];
for (const link of page.links) {
if (!link.isInternal) continue;
- if (storedForPage < MAX_STORED_LINKS_PER_PAGE) {
- storedForPage += 1;
- links.push({
- sourcePageId: page.id,
- sourceUrl: page.url,
- targetUrl: link.targetUrl,
- anchor: link.anchor,
- isNofollow: link.isNofollow,
- });
+ if (targets.length < MAX_STORED_LINKS_PER_PAGE) {
+ targets.push(link.targetUrl);
}
if (
discovered.size < MAX_DISCOVERED_PER_BATCH &&
@@ -329,6 +323,9 @@ async function persistCrawledPages(input: {
discovered.set(link.targetUrl, childDepth);
}
}
+ if (targets.length > 0) {
+ links.push({ pageId: page.id, url: page.url, targets });
+ }
// Redirect targets continue the same navigation path: same depth.
if (