Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions docs/rollouts/2026-12-03-plan-keepers-table.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# The plan read 142 GB to join against a window function

**Date:** 2026-12-03 **Seat:** ZC **Session:** `sess_6ab61beb-b36e-4e27-b44f-5bf2948f67d3`
**Files:** `scripts/plan-claude-cross-host-duplicate-cleanup.mjs`,
`scripts/__tests__/claude-cross-host-duplicate-cleanup.test.mjs`
**Rows:** UM-1689 (follow-up)

## What was wrong

The plan finds each group's keeper with a window function over every eligible row, and
then joins each candidate row to its group's keeper.  SQLite cannot look a group up
inside a query that computes `ROW_NUMBER()` over it, because there is no index on that
query's result, so the join became a nested loop that scanned the whole set once for
every row.  On the production ledger - about 900k eligible rows over 551k groups - the
plan read 142 GB and never finished.  The same query with the keepers materialized into
a table with an index on the group read 3.5 GB and finished in minutes.

The plan was correct throughout.  It was the shape of the query that was wrong, and it
was wrong in a way that only shows up at production scale: a ledger of a few thousand rows
answers the same question in the same time.

## The fix

The keepers are materialized into a temporary table with an index on the group, and the
join looks the keeper up in it.  A temporary table lives in SQLite's own temp store, so
a connection opened read-only can still hold one, and the plan's read-only connection
never writes the ledger.

Two details matter inside the query.  The partition keys are compared with `=` and not
with `IS`, because `IS` cannot use an index and the session id and the message id are
never null.  The label may be null, so it is compared with `IS` and the index is used
for the two keys that precede it.

A test reads the query plan and asserts that the keeper is looked up through an index
rather than scanned, so the shape cannot quietly go back to a scan.

## What did not change

The plan's results are the same.  The same 448,977 candidates, the same four manifests,
the same keeper for each group, and the same rows left alone.
69 changes: 68 additions & 1 deletion scripts/__tests__/claude-cross-host-duplicate-cleanup.test.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import test from "node:test";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync, mkdirSync, readFileSync, rmSync } from "node:fs";
import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { DatabaseSync } from "node:sqlite";
import {
GROUP_QUERY,
KEEPERS_INDEX,
KEEPERS_TABLE,
WINDOW_INDEX,
WINDOW_TABLE,
groupRows,
isCopyOfKeeper,
planGroups,
Expand Down Expand Up @@ -469,6 +474,68 @@ test("the plan refuses to run without a bounded window", () => {
}
});

test("the plan's query looks the keeper up rather than scanning for it", () => {
// A join against a query that computes ROW_NUMBER() has nothing to look the
// group up by, so SQLite scans it once for every row of the ledger: on the
// production ledger that read 142 GB and never finished. The keepers live in
// an indexed table for that reason, and the plan says so.
const base = mkdtempSync(join(tmpdir(), "cross-host-plan-"));
try {
const db = ledger(join(base, "ledger.sqlite"));
db.exec(KEEPERS_TABLE);
db.exec(KEEPERS_INDEX);
db.exec(WINDOW_TABLE);
db.exec(WINDOW_INDEX);
const steps = db.prepare("EXPLAIN QUERY PLAN " + GROUP_QUERY).all();
const detail = steps.map((row) => row.detail).join(" | ");
assert.match(detail, /SEARCH k USING/, "the keeper is looked up through an index");
assert.doesNotMatch(detail, /SCAN k\b/, "and not scanned once for every row of the ledger");
db.close();
} finally {
rmSync(base, { recursive: true, force: true });
}
});

test("a label the window does not hold is not a label the plan reports", () => {
// The labels the manifests are opened for decide two things: how many
// manifest files a run writes, and whether the run fits the cleanup CLI's
// bound of eight. Both belong to the window the plan was asked about, so a
// ledger that holds more labels than the window does must not stop a narrow
// run from being planned, and must not leave a manifest behind for a label
// the run never touched.
const base = mkdtempSync(join(tmpdir(), "cross-host-plan-"));
try {
const database = join(base, "ledger.sqlite");
const manifestDir = join(base, "manifests");
mkdirSync(manifestDir);
const db = ledger(database);
// Nine labels outside the window, so the whole ledger holds more labels
// than the cleanup CLI reads.
for (let index = 0; index < 9; index += 1) {
insertRow(db, `outside-${index}`, {
label: `token:outside-${index}`,
sessionId: `session-outside-${index}`,
callId: `call-outside-${index}`,
createdAt: "2026-12-02T18:15:03.410+00:00",
});
}
// One cross-host pair inside the window.
insertRow(db, "mac-copy", { host: "Mac.Jays.Services", createdAt: "2026-12-01T18:15:03.410+00:00" });
insertRow(db, "server-copy", { host: "fleet-hetzner-nbg1", createdAt: "2026-12-01T19:35:44.000+00:00" });
db.close();
const summary = planLedger(database, {
since: "2026-12-01T00:00:00.000Z",
until: "2026-12-02T00:00:00.000Z",
manifestDir,
});
assert.equal(summary.candidates, 1, "the pair in the window is planned");
assert.deepEqual(summary.manifests.map((entry) => entry.label), ["token:input"], "only the label the window holds is reported");
assert.deepEqual(readdirSync(manifestDir), ["cross-host-token_input.json"], "and no manifest is left for a label the window does not hold");
} finally {
rmSync(base, { recursive: true, force: true });
}
});

test("the plan's query and the library agree on the shape of a row", () => {
// The plan nominates the keeper and counts the candidates; the library is
// what approves them. If the two disagree on the shape of a row, the plan
Expand Down
163 changes: 111 additions & 52 deletions scripts/plan-claude-cross-host-duplicate-cleanup.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -91,27 +91,95 @@ const ROW_COLUMNS = `
/**
* The rows the plan considers, each with the keeper of its group.
*
* `eligible` is every row of the shape the cleanup library approves, and
* `ranked` numbers the rows of each group from the newest, so the keeper is
* the group's newest row whichever side of the window it was written on. The
* window is applied last, to the candidate side only.
* `eligible` is every row of the shape the cleanup library approves, and the
* keeper of a group is the group's newest row whichever side of the window it
* was written on. The window is applied last, to the candidate side only.
*/
const GROUP_QUERY = `
WITH eligible AS (
const ELIGIBLE_QUERY = `
SELECT${ROW_COLUMNS}
FROM "ExternalUsageEvent"
WHERE ${storedRowPredicateSql()}
AND json_extract("metadata", '$."session.id"') IS NOT NULL
AND json_extract("metadata", '$."call.id"') IS NOT NULL
),
ranked AS (
SELECT eligible.*,
ROW_NUMBER() OVER (
PARTITION BY "sessionId", "callId", "label"
ORDER BY "createdAt" DESC, "idempotencyKey" DESC
) AS "keeperRank"
FROM eligible
)
`;

/**
* The keeper of every group, as a table the plan can join against.
*
* The keepers live in a temporary table with an index on the group, because a
* join against a query with a window function in it has nothing to look the
* group up by: SQLite scans the whole set once per row, which on a ledger of
* this size does not finish. The temporary table is SQLite's own temp store,
* so it never touches the ledger's file.
*/
export const KEEPERS_TABLE = `
CREATE TEMP TABLE "planKeepers" (
"sessionId" TEXT, "callId" TEXT, "label" TEXT, "idempotencyKey" TEXT,
"occurredAt" TEXT, "createdAt" TEXT, "keyRef" TEXT, "quantity" REAL,
"model" TEXT, "hostName" TEXT, "instanceId" TEXT, "project" TEXT,
"projectName" TEXT, "projectNameAlias" TEXT, "projectId" TEXT,
"environment" TEXT, "collector" TEXT
)
`;

const KEEPERS_INSERT = `
INSERT INTO "planKeepers"
SELECT "sessionId", "callId", "label", "idempotencyKey", "occurredAt", "createdAt",
"keyRef", "quantity", "model", "hostName", "instanceId", "project", "projectName",
"projectNameAlias", "projectId", "environment", "collector"
FROM (
SELECT eligible.*,
ROW_NUMBER() OVER (
PARTITION BY "sessionId", "callId", "label"
ORDER BY "createdAt" DESC, "idempotencyKey" DESC
) AS "keeperRank"
FROM (${ELIGIBLE_QUERY}) eligible
) ranked
WHERE "keeperRank" = 1
`;

export const KEEPERS_INDEX = `
CREATE INDEX "planKeepersGroup" ON "planKeepers" ("sessionId", "callId", "label")
`;

/**
* The rows the window holds, as a table the plan reads the labels from and
* joins the keepers against.
*
* The window's rows live in a temporary table for the same reason the keepers
* do: the plan joins two sets by the call they belong to, and a set that only
* exists as a query has nothing to look a group up by. The window's rows are
* also the only rows the plan may touch, so the labels the manifests are
* opened for are read from here. A label no row of the window carries is not
* a label this plan has anything to say about: a manifest for it would be an
* empty file, and a plan bounded to a window must not fail because the ledger
* holds labels the window does not.
*/
export const WINDOW_TABLE = `
CREATE TEMP TABLE "planWindow" (
"id" TEXT, "idempotencyKey" TEXT, "label" TEXT, "keyRef" TEXT, "quantity" REAL,
"occurredAt" TEXT, "createdAt" TEXT, "projectId" TEXT, "environment" TEXT,
"sessionId" TEXT, "callId" TEXT, "hostName" TEXT, "instanceId" TEXT,
"collector" TEXT, "model" TEXT, "project" TEXT, "projectName" TEXT,
"projectNameAlias" TEXT
)
`;

const WINDOW_INSERT = `
INSERT INTO "planWindow"
SELECT${ROW_COLUMNS}
FROM "ExternalUsageEvent"
WHERE ${storedRowPredicateSql()}
AND json_extract("metadata", '$."session.id"') IS NOT NULL
AND json_extract("metadata", '$."call.id"') IS NOT NULL
AND "createdAt" >= ? AND "createdAt" < ?
`;

export const WINDOW_INDEX = `
CREATE INDEX "planWindowGroup" ON "planWindow" ("sessionId", "callId", "label")
`;

export const GROUP_QUERY = `
SELECT
e."id" AS id,
e."idempotencyKey" AS idempotencyKey,
Expand Down Expand Up @@ -143,25 +211,17 @@ SELECT
k."projectNameAlias" AS "keeperProjectNameAlias",
k."projectId" AS "keeperProjectId",
k."environment" AS "keeperEnvironment"
FROM eligible e
JOIN ranked k
ON k."sessionId" IS e."sessionId"
AND k."callId" IS e."callId"
FROM "planWindow" e
CROSS JOIN "planKeepers" k
ON k."sessionId" = e."sessionId"
AND k."callId" = e."callId"
AND k."label" IS e."label"
AND k."keeperRank" = 1
WHERE e."createdAt" >= ? AND e."createdAt" < ?
ORDER BY e."createdAt", e."idempotencyKey"
`;

/** The labels the window holds, so the manifests can be opened before the rows. */
const LABEL_QUERY = `
SELECT DISTINCT "label" AS label
FROM "ExternalUsageEvent"
WHERE ${storedRowPredicateSql()}
AND "label" IS NOT NULL
AND json_extract("metadata", '$."session.id"') IS NOT NULL
AND json_extract("metadata", '$."call.id"') IS NOT NULL
AND "createdAt" >= ? AND "createdAt" < ?
export const LABEL_QUERY = `
SELECT DISTINCT "label" AS label FROM "planWindow" WHERE "label" IS NOT NULL
`;

/** The host and project metadata of one row, as the plan compares them. */
Expand Down Expand Up @@ -259,36 +319,29 @@ export function groupRows(rows) {
}

/**
* The rows the window holds, each with the keeper of its group.
* Open the ledger read-only and prepare the keepers and the window's rows.
*
* The rows are streamed: the statement is iterated rather than collected, so
* the plan never holds the window in memory at once. The caller closes the
* database when it has read them all.
* Both sets live in SQLite's temporary store, which is a database of its own,
* so a connection that may not write the ledger can still hold them. The
* keepers are every group's newest row, whichever side of the window it was
* written on; the window's rows are the only rows the plan may touch.
*/
function readRows(databasePath, { since, until }) {
function openLedger(databasePath, { since, until }) {
const db = new DatabaseSync(databasePath, { readOnly: true, timeout: 60_000 });
try {
const rows = db.prepare(GROUP_QUERY).iterate(new Date(since).toISOString(), new Date(until).toISOString());
return { rows, close: () => db.close() };
db.exec(KEEPERS_TABLE);
db.exec(KEEPERS_INSERT);
db.exec(KEEPERS_INDEX);
db.exec(WINDOW_TABLE);
db.prepare(WINDOW_INSERT).run(new Date(since).toISOString(), new Date(until).toISOString());
db.exec(WINDOW_INDEX);
return db;
} catch (error) {
db.close();
throw error;
}
}

/** The labels the window holds. */
function readLabels(databasePath, { since, until }) {
const db = new DatabaseSync(databasePath, { readOnly: true, timeout: 60_000 });
try {
return db
.prepare(LABEL_QUERY)
.all(new Date(since).toISOString(), new Date(until).toISOString())
.map((row) => row.label);
} finally {
db.close();
}
}

/** The manifest a label's proofs are written into. */
function manifestHeader(label) {
return `{"version":1,"mode":"proof-only-no-database-mutation","label":${JSON.stringify(label)},"candidates":[`;
Expand Down Expand Up @@ -320,7 +373,11 @@ async function main() {
if (!databaseUrl) throw new Error("DATABASE_URL is required");
const databasePath = parseSqliteDatabasePath(databaseUrl);

const labels = readLabels(databasePath, { since, until });
const db = openLedger(databasePath, { since, until });
const labels = db
.prepare(LABEL_QUERY)
.all()
.map((row) => row.label);
if (labels.length > MAX_MANIFESTS) {
throw new Error(`The cleanup CLI reads at most ${MAX_MANIFESTS} manifests and this plan needs ${labels.length}`);
}
Expand Down Expand Up @@ -349,7 +406,9 @@ async function main() {
let candidates = 0;
let groups = 0;
const seenGroups = new Set();
const { rows, close } = readRows(databasePath, { since, until });
const rows = db
.prepare(GROUP_QUERY)
.iterate();
try {
for (const row of rows) {
const groupKey = `${row.sessionId}\x00${row.callId}\x00${row.label}`;
Expand Down Expand Up @@ -398,7 +457,7 @@ async function main() {
}
} finally {
rows.return?.();
close();
db.close();
}

const summary = [];
Expand Down
Loading