Repository navigation
Description
Before submitting
- I searched existing issues and did not find a duplicate.
- I included enough detail to reproduce or investigate the problem.
Area
apps/server
Steps to reproduce
No provider sign-in required. Windows dependency setup took about 2 minutes, synthetic seeding about 1 minute, and the five-trial Windows run about 8 minutes on the busy test host.
-
Save the four scripts below into an empty directory. Create a
sourcesubdirectory from clean upstream commitf58085a1c2e5bea0b020ee2d4d69f8768b7b228d. -
Install the frozen dependencies and find the pinned Node binary.
git clone https://github.com/pingdotgg/t3code.git source git -C source checkout --detach f58085a1c2e5bea0b020ee2d4d69f8768b7b228d cd source vp env exec pnpm --filter t3... install --frozen-lockfile vp env which node cd ..
-
Use that Node binary in the following commands. The seed is fully synthetic. The Windows cold-file run starts a new process for each trial and uses
robocopy /Jto prepare a fresh copy of the fixture. Run in ordinary Windows conditions and record host load. In the observed run, sampled system CPU was 98–100%. No load generator was used.node platform-repro.mjs seed source coordinator-matched.sqlite coordinator node compare-runtime.mjs source coordinator-matched.sqlite windows-cold.json 5 cold-file
-
Observe
budgetExceededin the summary and thefresh-connectionrows in the output JSON. For the Linux control, copy the same SQLite file and its.fixture.jsonsidecar. Run the same command withlinux-cold.jsonas the output. The Linux helper uses Python 3 to verify that the scratch copy has zero resident database pages before opening it.
Expected behavior
The first older-history page completes within the client’s six-second budget. A bounded page should avoid reading unrelated run-attempt rows just to find superseded attempts.
Actual behavior
The real ProjectionStore.getThreadHistoryPage path exceeded six seconds on all five Windows first-page loads from fresh copies. First-page times were 23.66, 28.05, 9.65, 6.10, and 11.66 s. This batch had 11 of 60 pages above six seconds. A Windows batch without the fresh-copy step had 3 of 60 above six seconds. The Linux control had 0 of 120 above six seconds and a maximum of 0.75 s.
The input database is 320 MiB with 2,855 attempts, 919 canceled runs, zero superseded attempts, and 19,601 target timeline items. The two systems used identical SQLite database bytes and returned the same pages. The superseded-attempt lookup executed 14,285 SQLite VM steps and returned zero rows on both. The hidden conversation candidate lookup executed 70,577 VM steps and returned one row on both.
The slowest Windows request took 85.74 s, including 20.88 s in ProjectionStore.openLocalTimeline and 12.37 s in the superseded-attempt lookup. The latter query uses the (thread_id, run_id) index and filters on status. The fixture compares projection calls against the client deadline. It does not run HTTP, the relay, or browser cancellation. Windows residency could not be measured. These measurements establish a repeatable slow path on the tested Windows host. The role of the OS, filesystem, hardware and host load remains open.
Impact
Major degradation or frequent failure.
Version or commit
Upstream f58085a1c2e5bea0b020ee2d4d69f8768b7b228d. The tested server history code, client timeout, and SQLite schema were unchanged at the subsequent upstream check, 0ea0db39e272a472f26b97e9bfc3a6c7805112f2.
Environment
Windows build 26200, native Node 26.13.1, SQLite 3.54.1, AMD Ryzen 5 5600, NTFS on NVMe. Linux control on kernel 5.15, the same Node and SQLite versions, Intel Core i5-11600K, ext4. No provider session required.
Logs or stack traces
Windows, fresh copies 11 / 60 beyond 6000 ms max 28052.311 ms
Windows, existing file 3 / 60 beyond 6000 ms max 85737.553 ms
Linux, verified cold 0 / 60 beyond 6000 ms max 745.465 ms
Linux, existing file 0 / 60 beyond 6000 ms max 310.652 ms
The earlier snapshot and cancellation report #17765 used different history preparation. This fixture exercises the bounded local timeline.
Reproduction files
platform-repro.mjs
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { copyFileSync, existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { resolve } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { pathToFileURL } from "node:url";
import { seedCoordinator } from "./coordinator-data.mjs";
const [action, sourceArgument, databaseArgument, ...args] = process.argv.slice(2);
if (!["seed", "index", "page", "probe"].includes(action) || !sourceArgument || !databaseArgument) {
throw new Error("Usage: node history-repro.mjs <seed|index|page|probe> <upstream-source> <synthetic.sqlite> [arguments]");
}
const source = resolve(sourceArgument);
const database = resolve(databaseArgument);
const fixturePath = database + ".fixture.json";
const threadId = "synthetic-history-target";
const modelSelection = { instanceId: "codex", model: "synthetic-model" };
const providerThreadId = "synthetic-provider-thread";
const supersededIndex = "synthetic_attempts_superseded";
const variant = "work-deferred";
const clientBudgetMs = 6_000;
const serverRequire = createRequire(resolve(source, "apps/server/package.json"));
const importPackage = (id) => import(pathToFileURL(serverRequire.resolve(id)).href);
const importServer = (path) => import(pathToFileURL(resolve(source, "apps/server/src", path)).href);
const json = JSON.stringify;
const rounded = (time) => Number(time.toFixed(3));
if (action === "index") {
const destination = resolve(args[0]);
assert(!existsSync(destination) && !existsSync(destination + ".fixture.json"));
assert(!existsSync(database + "-wal"), "Checkpoint and close the source first");
copyFileSync(database, destination);
copyFileSync(fixturePath, destination + ".fixture.json");
using db = new DatabaseSync(destination);
db.exec("CREATE INDEX " + supersededIndex
+ " ON orchestration_v2_projection_run_attempts(thread_id,run_id,root_node_id)"
+ " WHERE status='superseded'");
} else if (action === "probe") {
const fixture = readFixture();
const trace = JSON.parse(readFileSync(args[0], "utf8"));
using db = new DatabaseSync(database, { readOnly: true });
const heldRunIds = db.prepare(`SELECT run_id FROM orchestration_v2_projection_runs
WHERE thread_id = ? AND (status = 'queued'
OR (status = 'cancelled' AND json_extract(payload_json, '$.startedAt') IS NULL))`)
.all(threadId).map(({ run_id }) => run_id);
const heldInputs = db.prepare(`SELECT COUNT(*) n FROM orchestration_v2_projection_turn_items
WHERE thread_id=? AND type='user_message' AND run_id IN (SELECT value FROM json_each(?))`).get(threadId, json(heldRunIds)).n;
for (const [key, bindings, expected] of [
["supersededAttempts", [threadId], fixture.steeredRunIds.length],
["hiddenConversation", [threadId, json(heldRunIds), json(fixture.steeredRunIds)], heldInputs + fixture.steeredRunIds.length],
]) {
const sql = trace[key];
const plan = db.prepare("EXPLAIN QUERY PLAN " + sql).all(...bindings).map(({ detail }) => detail);
const stmt = db.prepare(sql);
const start = performance.now();
const rows = stmt.all(...bindings);
const ms = rounded(performance.now() - start);
assert.equal(rows.length, expected, key);
const vmSteps = stmt.stat("vmStep");
const patched = db.prepare("SELECT 1 FROM sqlite_schema WHERE name=?").get(supersededIndex) !== undefined;
if (key === "supersededAttempts") {
assert(plan.some((line) => line.includes(patched
? supersededIndex : "orchestration_v2_projection_run_attempts_thread_idx")));
assert(patched ? vmSteps < 100 : vmSteps > fixture.runs * 4, "unexpected attempt scan cost");
} else {
assert(plan.some((line) => line.includes("orchestration_v2_projection_turn_items_conversation_idx")));
assert(vmSteps > fixture.runs * 4, "unexpected conversation candidate scan cost");
}
console.log(json({ databaseBytes: statSync(database).size, key, plan, vmSteps, ms, rows }));
}
} else {
const [Effect, Layer, DateTime, Tracer, NodeServices, Store, Persistence, History] = await Promise.all([
importPackage("effect/Effect"),
importPackage("effect/Layer"),
importPackage("effect/DateTime"),
importPackage("effect/Tracer"),
importPackage("@effect/platform-node/NodeServices"),
importServer("orchestration-v2/ProjectionStore.ts"),
importServer("persistence/Sqlite.ts"),
importServer("orchestration-v2/threadHistoryPaging.ts"),
]);
const useStore = (program) => Effect.runPromise(program.pipe(Effect.provide(
Store.layer.pipe(Layer.provide(Persistence.layerFromPath(database)), Layer.provide(NodeServices.layer)),
)));
if (action === "seed") {
const coordinator = args[0] === "coordinator";
const runs = Number(args[0]);
const steers = Number(args[1]);
if (!coordinator) {
assert(Number.isInteger(runs) && runs >= 100 && runs <= 12_000);
assert(Number.isInteger(steers) && steers >= 1 && steers <= 8);
}
assert(!existsSync(database) && !existsSync(fixturePath));
const now = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z");
await useStore(Effect.gen(function* () {
const store = yield* Store.ProjectionStoreV2;
yield* store.apply({
id: "synthetic-thread-created",
type: "thread.created",
threadId,
occurredAt: now,
payload: {
createdBy: "user", creationSource: "web", id: threadId, projectId: "synthetic-project",
title: coordinator ? "Synthetic coordinator history" : "Synthetic long history",
providerInstanceId: modelSelection.instanceId, modelSelection,
runtimeMode: "full-access", interactionMode: "default", branch: null, worktreePath: null,
activeProviderThreadId: null,
lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
forkedFrom: null, createdAt: now, updatedAt: now, archivedAt: null, settledOverride: null,
settledAt: null, lastVisitedAt: null, deletedAt: null,
},
});
}));
const fixture = coordinator ? seedCoordinator(database, threadId) : seedRows(runs, steers);
const window = await useStore(Effect.gen(function* () {
const store = yield* Store.ProjectionStoreV2;
return yield* store.getThreadSnapshotWindow(threadId, {
rowLimit: History.THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
userTurnLimit: History.THREAD_HISTORY_PAGE_POLICY.maxUserTurns,
deferWork: true,
});
}));
const bounded = History.buildBoundedThreadProjection({
projection: window.projection,
snapshotSequence: window.snapshotSequence,
});
assert(bounded.hasMoreHistory && bounded.historyCursor);
writeFileSync(fixturePath, json({ ...fixture, cursor: bounded.historyCursor,
snapshotSequence: window.snapshotSequence }) + "\n", { flag: "wx" });
console.log(json({ ...fixture, databaseBytes: statSync(database).size, node: process.version,
sqlite: process.versions.sqlite, snapshotSequence: window.snapshotSequence }));
} else {
const fixture = readFixture();
const tracePath = args[0];
const repeatPages = Number(args[1] ?? 10);
assert(Number.isInteger(repeatPages) && repeatPages >= 0 && repeatPages <= 10);
const sql = {};
await useStore(Effect.gen(function* () {
const store = yield* Store.ProjectionStoreV2;
function timedPage(cursor) {
const spans = {};
const tracer = Tracer.make({
span(options) {
const span = new Tracer.NativeSpan(options);
const end = span.end.bind(span);
span.end = (endTime, exit) => {
end(endTime, exit);
const query = span.attributes.get("db.query.text");
let key;
if (typeof query === "string") {
if (/FROM orchestration_v2_projection_run_attempts\s+WHERE thread_id = \? AND status = 'superseded'/.test(query)) {
key = "supersededAttempts";
} else if (query.includes("orchestration_v2_projection_turn_items_conversation_idx")
&& query.includes("item.type = 'run_interrupt_result'")) {
key = "hiddenConversation";
}
}
if (span.name === "ProjectionStore.openLocalTimeline") key = "openLocalTimeline";
if (span.name === "ProjectionStore.readSnapshotTimelineIndex") key = "fullTimeline";
if (key === undefined) return;
(spans[key] ??= []).push(rounded(Number(endTime - span.startTime) / 1e6));
if (typeof query === "string") sql[key] = query;
};
return span;
},
});
return Effect.gen(function* () {
const start = performance.now();
const page = yield* store.getThreadHistoryPage(threadId, cursor, undefined, false, "deferred")
.pipe(Effect.withTracer(tracer));
const wallMs = rounded(performance.now() - start);
assert(!spans.fullTimeline && spans.openLocalTimeline?.length === 1
&& spans.supersededAttempts?.length === 1 && spans.hiddenConversation?.length === 1,
"Expected one bounded local open with both traced SQL statements");
assert(page.items.length > 0);
assert(page.items.some(({ item }) => item.type === "user_message"));
assert(page.items.every(({ item }) => item.type !== "run_interrupt_result"),
"Superseded attempt stops should be hidden");
assert(page.items.every(({ sourceThreadId }) => sourceThreadId === threadId));
assert(!page.hasMoreHistory || (page.nextCursor && page.nextCursor !== cursor));
return { page, wallMs, spans };
});
}
const log = (phase, { page, wallMs, spans }) => {
console.log(json({ phase, runs: fixture.runs, variant, wallMs,
exceedsClientBudget: wallMs >= clientBudgetMs, spans, items: page.items.length,
userTurns: page.items.filter(({ item }) => item.type === "user_message").length,
firstItem: page.items[0].sourceItemId, lastItem: page.items.at(-1).sourceItemId,
firstPosition: page.items[0].position, lastPosition: page.items.at(-1).position }));
};
const cold = yield* timedPage(fixture.cursor);
log("fresh-connection", cold);
const warm = yield* timedPage(fixture.cursor);
log("warm-same-page", warm);
assert.deepEqual(warm.page, cold.page);
let lastPage = warm.page;
for (let i = 1; i <= repeatPages && lastPage.hasMoreHistory; i++) {
const result = yield* timedPage(lastPage.nextCursor);
const previousOldest = lastPage.items[0].item.ordinal;
assert(result.page.items.at(-1).item.ordinal < previousOldest, "History must get older");
log("warm-earlier-" + i, result);
lastPage = result.page;
}
}));
if (tracePath) writeFileSync(tracePath, json(sql) + "\n", { flag: "wx" });
}
}
function readFixture() {
return JSON.parse(readFileSync(fixturePath, "utf8"));
}
function seedRows(runs, steers) {
const hash = (n) => createHash("sha256").update("synthetic-run:" + n).digest("hex").slice(0, 32);
const steered = new Set(Array.from({ length: steers }, (_, i) => Math.floor((i + 1) * runs / (steers + 1))));
// Include one replacement in the first history page to exercise hiding on that page.
steered.delete([...steered].at(-1));
steered.add(runs - 16);
const steeredRunIds = [];
const output = Array.from({ length: 14 }, (_, i) =>
"synthetic test " + i + " passed: fixture setup, input parsing and result validation").join("\n");
using db = new DatabaseSync(database);
db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; BEGIN IMMEDIATE");
const run = db.prepare(`
INSERT INTO orchestration_v2_projection_runs
(run_id,thread_id,ordinal,provider,provider_thread_id,status,requested_at,completed_at,payload_json)
VALUES (?, ?, ?, 'codex', ?, 'completed', ?, ?, ?)`);
const attempt = db.prepare(`
INSERT INTO orchestration_v2_projection_run_attempts
(attempt_id,thread_id,run_id,attempt_ordinal,root_node_id,provider,provider_thread_id,provider_turn_id,status,payload_json)
VALUES (?, ?, ?, ?, ?, 'codex', ?, NULL, ?, ?)`);
const node = db.prepare(`
INSERT INTO orchestration_v2_projection_nodes
(node_id,thread_id,run_id,parent_node_id,root_node_id,kind,status,provider_thread_id,started_at,completed_at,payload_json)
VALUES (?, ?, ?, NULL, ?, 'root_turn', ?, ?, ?, ?, ?)`);
const turn = db.prepare(`
INSERT INTO orchestration_v2_projection_turn_items
(turn_item_id,thread_id,run_id,node_id,provider_thread_id,provider_turn_id,parent_item_id,
ordinal,type,status,updated_at,payload_json,inline_work_output)
VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, ?, 'completed', ?, ?, 0)`);
let ordinal = 0;
for (let n = 1; n <= runs; n++) {
const runId = "run:" + hash(n);
const replaced = steered.has(n);
const startedAt = new Date(Date.UTC(2026, 0, 1) + n * 900_000).toISOString();
const completedAt = new Date(Date.parse(startedAt) + 120_000).toISOString();
const root = "root:" + runId;
const activeRoot = root + (replaced ? ":2" : ":1");
const messageId = "user:" + runId;
run.run(runId, threadId, n, providerThreadId, startedAt, completedAt, json({
id: runId, threadId, ordinal: n, providerInstanceId: modelSelection.instanceId, modelSelection,
providerThreadId, userMessageId: messageId, rootNodeId: activeRoot,
activeAttemptId: "attempt:" + activeRoot, status: "completed", requestedAt: startedAt, startedAt,
completedAt, checkpointId: null, contextHandoffId: null,
}));
for (let i = 1; i <= (replaced ? 2 : 1); i++) {
const nodeId = root + ":" + i;
const superseded = replaced && i === 1;
const reason = i === 1 ? "initial" : "steering_restart";
const id = "attempt:" + nodeId;
const status = superseded ? "superseded" : "completed";
attempt.run(id, threadId, runId, i, nodeId, providerThreadId, status, json({
id, runId, attemptOrdinal: i, rootNodeId: nodeId, providerInstanceId: modelSelection.instanceId,
providerThreadId, providerTurnId: null, reason, status, startedAt, completedAt,
}));
const nodeStatus = superseded ? "interrupted" : "completed";
node.run(nodeId, threadId, runId, nodeId, nodeStatus, providerThreadId, startedAt, completedAt, json({
id: nodeId, threadId, runId, parentNodeId: null, rootNodeId: nodeId, kind: "root_turn",
status: nodeStatus, countsForRun: true, providerThreadId, providerTurnId: null,
nativeItemRef: null, runtimeRequestId: null, checkpointScopeId: null, startedAt, completedAt,
}));
}
const add = (type, fields, nodeId = activeRoot) => {
const id = "item:" + (++ordinal);
turn.run(id, threadId, runId, nodeId, providerThreadId, ordinal, type, completedAt, json({
id, threadId, runId, nodeId, providerThreadId, providerTurnId: null,
nativeItemRef: null, parentItemId: null, ordinal, type, status: "completed",
title: null, startedAt, completedAt, updatedAt: completedAt, ...fields,
}));
};
add("user_message", {
messageId, createdBy: "user", creationSource: "web", inputIntent: "turn_start", attachments: [],
text: "Inspect the synthetic component and verify its boundary cases. Turn " + n + ".",
}, null);
if (replaced) {
steeredRunIds.push(runId);
add("run_interrupt_result", { message: "Synthetic attempt replaced by steering" }, root + ":1");
}
for (let i = 0; i < 16; i++) {
if (i % 4 === 0) add("reasoning", { text: "Check the next synthetic case.", streaming: false });
else add("command_execution", { input: "synthetic-test case-" + i, output, exitCode: 0 });
}
add("assistant_message", {
messageId: "assistant:" + runId, text: "Synthetic component verified. All fixture cases passed.",
phase: "final_answer", streaming: false,
});
}
db.exec("COMMIT; PRAGMA wal_checkpoint(TRUNCATE)");
return { threadId, runs, steeredRunIds, attempts: runs + steeredRunIds.length, turnItems: ordinal };
}coordinator-data.mjs
import { createHash } from "node:crypto";
import { DatabaseSync } from "node:sqlite";
const completedRuns = 1934;
const cancelledRuns = 919;
const totalRuns = completedRuns + cancelledRuns + 2;
// Counts and approximate UTF-8 sizes from aggregate projection metadata. All values are invented.
const completedItems = [
["user_message", 1259, 2585, "turn_start"],
["user_message", 358, 2585, "queued_turn"],
["reasoning", 4742, 1693],
["command_execution", 4723, 3249],
["dynamic_tool", 2611, 8718],
["user_message", 601, 2585, "promoted_queued_to_steer"],
["notification", 615, 1496],
["subagent", 583, 4544],
["compaction", 65, 1273],
["system_notice", 19, 1880],
["file_change", 15, 2890],
["web_search", 2, 1967],
["user_input_request", 2, 5600],
["assistant_message", 2048, 2036],
["checkpoint", 1934, 1347],
];
const cancelledItems = [
["user_message", 1, 1114, "queued_turn"],
["command_execution", 5, 1761],
["reasoning", 4, 1684],
["system_notice", 2, 1059],
["notification", 1, 1394],
];
const failedItems = [
["user_message", 1, 6183, "queued_turn"],
["reasoning", 1, 1831],
["command_execution", 1, 2527],
["dynamic_tool", 2, 3864],
["error", 1, 1449],
];
const runningItems = [
["user_message", 1, 2948, "turn_start"],
["reasoning", 2, 1841],
["command_execution", 2, 3776],
];
function scheduledItems(entries, total, position) {
return entries.flatMap(([type, count, bytes, intent]) => {
const occurrences = Math.floor(position * count / total) - Math.floor((position - 1) * count / total);
return Array.from({ length: occurrences }, () => ({ type, bytes, intent }));
});
}
function content(type, id, inputIntent) {
const stub = "Synthetic activity " + id;
switch (type) {
case "user_message": return { messageId: "message:" + id, createdBy: "agent", creationSource: "mcp", inputIntent, attachments: [], text: stub };
case "assistant_message": return { messageId: "message:" + id, text: stub, phase: "final_answer", streaming: false };
case "reasoning": return { text: stub, streaming: false };
case "command_execution": return { input: "synthetic-check", output: stub, exitCode: 0 };
case "dynamic_tool": return { toolName: "synthetic_check", input: { item: id }, output: { text: stub } };
case "notification": return { source: { kind: "system" }, outcome: "completed", summary: stub, detail: stub };
case "subagent": return { subagentId: "node:" + id, origin: "app_owned", driver: "claudeAgent", providerInstanceId: "claudeAgent", childThreadId: null, prompt: stub, result: stub };
case "compaction": return { driver: "claudeAgent", summary: stub };
case "system_notice": return { message: stub };
case "file_change": return { fileName: "synthetic.txt", diffStr: stub };
case "web_search": return { patterns: [stub], results: [] };
case "user_input_request": return { requestId: "request:" + id, questions: [{ id, header: "Synthetic", question: stub, options: [] }] };
case "checkpoint": return { checkpointId: "checkpoint:" + id, scopeId: "synthetic-scope", files: [] };
case "error": return { failure: { class: "provider_error", message: stub, code: null, retryable: false } };
default: throw new Error("Unknown item type " + type);
}
}
function sizedPayload(item, bytes) {
const padding = "x".repeat(Math.max(0, bytes - JSON.stringify(item).length - 20));
if (typeof item.text === "string") item.text += padding;
else if (typeof item.output === "string") item.output += padding;
else if (item.type === "dynamic_tool") item.output.text += padding;
else if (typeof item.result === "string") item.result += padding;
else if (typeof item.summary === "string") item.summary += padding;
else item.syntheticPadding = padding;
return JSON.stringify(item);
}
export function seedCoordinator(database, threadId) {
using db = new DatabaseSync(database);
db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; BEGIN IMMEDIATE");
const run = db.prepare(`
INSERT INTO orchestration_v2_projection_runs
(run_id,thread_id,ordinal,provider,provider_thread_id,status,requested_at,completed_at,payload_json)
VALUES (?, ?, ?, 'claudeAgent', ?, ?, ?, ?, ?)`);
const attempt = db.prepare(`
INSERT INTO orchestration_v2_projection_run_attempts
(attempt_id,thread_id,run_id,attempt_ordinal,root_node_id,provider,provider_thread_id,provider_turn_id,status,payload_json)
VALUES (?, ?, ?, 1, ?, 'claudeAgent', ?, NULL, ?, ?)`);
const node = db.prepare(`
INSERT INTO orchestration_v2_projection_nodes
(node_id,thread_id,run_id,parent_node_id,root_node_id,kind,status,provider_thread_id,started_at,completed_at,payload_json)
VALUES (?, ?, ?, NULL, ?, 'root_turn', ?, ?, ?, ?, ?)`);
const turn = db.prepare(`
INSERT INTO orchestration_v2_projection_turn_items
(turn_item_id,thread_id,run_id,node_id,provider_thread_id,provider_turn_id,parent_item_id,
ordinal,type,status,updated_at,payload_json,inline_work_output)
VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, ?, 'completed', ?, ?, ?)`);
const providerThreadId = "synthetic-provider-thread";
const modelSelection = { instanceId: "claudeAgent", model: "synthetic-model" };
const backgroundThread = "synthetic-background-thread";
let completed = 0;
let cancelled = 0;
let inline = 0;
let toolItems = 0;
let itemCount = 0;
for (let ordinal = 1; ordinal <= totalRuns; ordinal++) {
const stem = createHash("sha256").update("synthetic-coordinator:" + ordinal).digest("hex");
const runId = "run:" + stem;
const nodeId = "root:" + stem;
const attemptId = "attempt:" + stem;
const startedAt = new Date(Date.UTC(2026, 0, 1) + ordinal * 30 * 60_000).toISOString();
const endedAt = new Date(Date.parse(startedAt) + 120_000).toISOString();
let status;
let items;
if (ordinal === totalRuns) {
status = "running";
items = scheduledItems(runningItems, 1, 1);
} else if (ordinal === totalRuns - 1) {
status = "failed";
items = scheduledItems(failedItems, 1, 1);
} else if (Math.floor(ordinal * cancelledRuns / (totalRuns - 2)) > cancelled) {
status = "cancelled";
items = scheduledItems(cancelledItems, cancelledRuns, ++cancelled);
} else {
status = "completed";
const start = Math.floor(completed * 1617 / completedRuns);
const next = Math.floor(++completed * 1617 / completedRuns);
items = scheduledItems(completedItems.slice(2), completedRuns, completed);
if (next > start) {
const queued = Math.floor(next * 358 / 1617) > Math.floor(start * 358 / 1617);
const [type, , bytes, intent] = completedItems[queued ? 1 : 0];
items.unshift({ type, bytes, intent });
}
}
const completedAt = status === "running" ? null : endedAt;
const runStartedAt = status === "cancelled" && cancelled > 2 ? null : startedAt;
const firstPrompt = items.findIndex(({ type }) => type === "user_message");
const messageId = firstPrompt === -1 ? null : "message:item:" + stem + ":" + firstPrompt;
run.run(runId, threadId, ordinal, providerThreadId, status, startedAt, completedAt, JSON.stringify({
id: runId, threadId, ordinal, providerInstanceId: modelSelection.instanceId, modelSelection,
providerThreadId, userMessageId: messageId, rootNodeId: nodeId, activeAttemptId: attemptId,
status, requestedAt: startedAt, startedAt: runStartedAt, completedAt,
checkpointId: null, contextHandoffId: null,
}));
const attemptBody = JSON.stringify({
id: attemptId, runId, attemptOrdinal: 1, rootNodeId: nodeId, providerInstanceId: modelSelection.instanceId,
providerThreadId, providerTurnId: null, reason: "initial", status, startedAt, completedAt,
syntheticPadding: "a".repeat(300),
});
attempt.run(attemptId, threadId, runId, nodeId, providerThreadId, status, attemptBody);
if (ordinal % 20 !== 0) {
attempt.run("background:" + attemptId, backgroundThread, "background:" + runId, "background:" + nodeId,
"synthetic-background-provider", "completed", JSON.stringify({ syntheticPadding: "b".repeat(800) }));
}
const nodeStatus = status === "cancelled" ? "interrupted" : status;
node.run(nodeId, threadId, runId, nodeId, nodeStatus, providerThreadId, startedAt, completedAt, JSON.stringify({
id: nodeId, threadId, runId, parentNodeId: null, rootNodeId: nodeId, kind: "root_turn", status: nodeStatus,
countsForRun: true, providerThreadId, providerTurnId: null, nativeItemRef: null, runtimeRequestId: null,
checkpointScopeId: null, startedAt, completedAt,
}));
items.forEach(({ type, bytes, intent }, i) => {
const id = "item:" + stem + ":" + i;
const itemNode = type === "user_message" ? null : nodeId;
const itemOrdinal = ordinal * 1_000_000 + i + 1;
const item = {
id, threadId, runId, nodeId: itemNode, providerThreadId, providerTurnId: null, nativeItemRef: null,
parentItemId: null, ordinal: itemOrdinal, type, status: "completed", title: null, startedAt,
completedAt: endedAt, updatedAt: endedAt, ...content(type, id, intent),
};
if (type === "dynamic_tool") toolItems++;
const inlineOutput = type === "dynamic_tool" && toolItems % 9 === 0 && inline < 272 ? 1 : 0;
inline += inlineOutput;
turn.run(id, threadId, runId, itemNode, providerThreadId, itemOrdinal, type, endedAt, sizedPayload(item, bytes), inlineOutput);
itemCount++;
for (let n = 0; n < 6; n++) {
const backgroundId = "background:" + id + ":" + n;
turn.run(backgroundId, backgroundThread, null, null, null, itemOrdinal * 6 + n,
"reasoning", endedAt, JSON.stringify({ text: "b".repeat(1024) }), 0);
}
});
}
db.exec("COMMIT; PRAGMA wal_checkpoint(TRUNCATE)");
return { threadId, runs: totalRuns, attempts: totalRuns, steeredRunIds: [], completed, cancelled, turnItems: itemCount, inline };
}compare-runtime.mjs
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { copyFileSync, createReadStream, mkdirSync, writeFileSync } from "node:fs";
import { cpus, release } from "node:os";
import { basename, dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const [source, database, destination, count = "5", cacheMode = "warm-file"] = process.argv.slice(2);
assert(source && database && destination,
"Usage: node compare-runtime.mjs <source> <database> <result.json> [trials] [warm-file|cold-file]");
assert(["warm-file", "cold-file"].includes(cacheMode));
const trials = Number(count);
assert(Number.isSafeInteger(trials) && trials > 0 && trials <= 10);
const harness = fileURLToPath(new URL("./platform-repro.mjs", import.meta.url));
async function hash(path) {
const hash = createHash("sha256");
for await (const data of createReadStream(path)) hash.update(data);
return hash.digest("hex");
}
const fixtureHash = await hash(database);
const pages = [];
const probes = [];
const cachePreparation = [];
function fixtureForTrial(i) {
if (cacheMode === "warm-file") return database;
const target = resolve(destination + ".trial-" + i);
mkdirSync(target);
const trialDatabase = resolve(target, basename(database));
copyFileSync(database + ".fixture.json", trialDatabase + ".fixture.json");
if (process.platform === "linux") {
copyFileSync(database, trialDatabase);
const evict = fileURLToPath(new URL("./evict-fixture-linux.py", import.meta.url));
const residency = JSON.parse(execFileSync("python3", [evict, trialDatabase], { encoding: "utf8" }));
assert.equal(residency.residentAfter, 0, "Linux fixture must start with no resident pages");
cachePreparation.push(residency);
return trialDatabase;
}
assert.equal(process.platform, "win32");
const result = spawnSync("robocopy.exe", [
dirname(resolve(database)), target, basename(database), "/J", "/R:0", "/W:0", "/NFL", "/NDL",
], { encoding: "utf8" });
if (result.error) throw result.error;
assert.equal(result.status, 1, result.stdout + result.stderr);
cachePreparation.push({ trial: i, method: "unbuffered copy to a fresh file", residencyVerified: false });
return trialDatabase;
}
for (let i = 1; i <= trials; i++) {
const trialDatabase = fixtureForTrial(i);
const trace = resolve(destination + ".sql-" + i + ".json");
const output = execFileSync(process.execPath, [harness, "page", source, trialDatabase, trace, "10"], {
encoding: "utf8",
maxBuffer: 1024 * 1024,
});
pages.push(...output.trim().split("\n").map((line) => ({ trial: i, ...JSON.parse(line) })));
if (trialDatabase !== database) assert.equal(await hash(trialDatabase), fixtureHash);
}
const probe = execFileSync(process.execPath, [harness, "probe", source, database, resolve(destination + ".sql-1.json")],
{ encoding: "utf8", maxBuffer: 1024 * 1024 });
probes.push(...probe.trim().split("\n").map(JSON.parse));
assert.equal(await hash(database), fixtureHash,
"Read-only benches must leave the SQLite database bytes unchanged");
const report = {
platform: process.platform, release: release(), cpu: cpus()[0].model,
node: process.version, sqlite: process.versions.sqlite, fixtureHash, trials, cacheMode,
cachePreparation, pages, probes,
};
writeFileSync(destination, JSON.stringify(report, null, 2) + "\n", { flag: "wx" });
console.log(JSON.stringify({
platform: report.platform, node: report.node, sqlite: report.sqlite, fixtureHash, trials,
pages: pages.length, budgetExceeded: pages.filter((row) => row.exceedsClientBudget).length,
maxPageMs: Math.max(...pages.map((row) => row.wallMs)),
probes: probes.map(({ key, vmSteps, rows }) => ({ key, vmSteps, matches: rows.length })),
}));evict-fixture-linux.py
"""Ask Linux to evict one owned, closed synthetic DB and report its resident pages."""
import ctypes
import json
import mmap
import os
from pathlib import Path
import sys
db = Path(sys.argv[1])
fixture = json.loads(Path(str(db) + ".fixture.json").read_text())
if fixture.get("threadId") != "synthetic-history-target":
raise ValueError("Expected a synthetic fixture")
if Path(str(db) + "-wal").exists():
raise ValueError("Close and checkpoint all connections first")
libc = ctypes.CDLL(None, use_errno=True)
with db.open("rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_COPY) as view:
os.fsync(f.fileno())
page_size = os.sysconf("SC_PAGESIZE")
count = (len(view) + page_size - 1) // page_size
vector = (ctypes.c_ubyte * count)()
address = ctypes.addressof(ctypes.c_char.from_buffer(view))
def resident():
if libc.mincore(ctypes.c_void_p(address), ctypes.c_size_t(len(view)), vector):
raise OSError(ctypes.get_errno(), "mincore")
return sum(bool(page & 1) for page in vector)
before = resident()
os.posix_fadvise(f.fileno(), 0, 0, os.POSIX_FADV_DONTNEED)
print(json.dumps(dict(pages=count, residentBefore=before, residentAfter=resident())))
Activity
Alb11747 commentedon Nov 23, 2026
The same synthetic history exceeded the six-second budget on Linux when other runnable workers competed for the container's CPU quota.
I ran the same upstream commit and SQLite fixture in a Linux Docker container with cgroup v2, Node 26.13.1, and SQLite 3.54.1. The database was on tmpfs. Each trial opened a fresh reader, loaded the first older-history page, then requested the same page again. The competing workers ran arithmetic loops in the same cgroup during both reads. All runs returned the same pages, and no OOM kills occurred.
The three loaded first pages at 0.13 CPU took 15.593, 18.093, and 20.705 seconds. Docker was invoked with
--cpus 0.125and reportedcpu.max = 13000 100000. The first pages were throttled in 547 of 547 active CPU periods with the workers and 47 of 47 without them. The shorter control times show why the throttling indicator alone does not explain the delay.CPU contention is sufficient to reproduce the server-side delay on Linux under these conditions. The test measures the projection call against the client budget. It leaves the cause of the original Windows incident and HTTP cancellation behavior open.
Posted by GPT-6.2 Sol on behalf of Alb11747.