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
23 changes: 23 additions & 0 deletions docs/internals/performance-regressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,29 @@ catalog digests and status deltas gets the provider list of its first config in
provider with 250 slash commands and 200 skills. The lists load with the first cwd snapshot, and a
machine refresh sends back an empty provider list.

## Server process metrics

`node scripts/server-metrics.ts run --out <file>` starts a checkout's server against throwaway
state, a fake Anthropic API and the real `claude` CLI, and records server CPU, wakeups, RSS and
heap at rest, with quiet Claude threads and with 5 streaming, plus how long a new thread takes to
reach the API. Only the server process is measured.

- Compare refs with `ab <checkoutA> <checkoutB>`, not with two files from different times. It
alternates the two on one machine, and `compare` flags a metric only when the bootstrap interval
of the median difference clears both the threshold and the noise floor. Single runs on a busy
machine differ by more than most regressions.
- Read per-thread cost from `scaling`, a fit over 5 to 20 open threads. It separates what each
open thread costs from the fixed cost of the server, which the absolute numbers mix.
- `--soak <minutes>` reports heap and RSS slopes in MB per hour and the constructors that grew.
A rising heap floor is a leak; a high but flat one is not.
- The quiet and streaming windows save a CPU and an allocation profile, so a regression comes with
the functions that cost it.

Run it on macOS and Windows too, and on Linux with `--no-agent-scope`. Only Linux has agent
scopes, so other platforms take per-process paths a Linux server with a systemd user manager never
runs. A one-second `ps -A` poll per Claude session cost 0.1.11 about 18% of a core with 20 open
threads on macOS and went unnoticed on Linux.

## Event store and startup

Sequence cursors must seek an index rather than scan retained history. The application sequence
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"tc": "vp run -r --cache --concurrency-limit 4 typecheck",
"check:changed": "node scripts/check-changed.ts",
"report:renders": "node scripts/render-metrics.ts",
"report:server": "node scripts/server-metrics.ts",
"lint": "vp lint --report-unused-disable-directives",
"i18n:untranslated": "node scripts/i18n-untranslated.ts",
"knip": "knip --preprocessor ./scripts/knip-schemas.ts",
Expand Down
2 changes: 1 addition & 1 deletion scripts/scenarios/shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const run = Effect.fn("scenario.run")(
);
if (!(options.allowExit ?? [0]).includes(exitCode)) {
return yield* new ScenarioError({
message: `${program} ${args.slice(0, 3).join(" ")} exited with ${exitCode}: ${stderr.trim().slice(-600)}`,
message: `${program} ${args.slice(0, 3).join(" ")} exited with ${exitCode}: ${(stderr.trim() || stdout.trim()).slice(-600)}`,
});
}
return { stdout, stderr, exitCode: Number(exitCode) };
Expand Down
339 changes: 339 additions & 0 deletions scripts/server-metrics-report.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,339 @@
// The pure half of scripts/server-metrics.ts: the JSON it writes, and how two of them compare.
import * as Schema from "effect/Schema";

const Window = Schema.Struct({
cpuPct: Schema.Number,
wakeupsPerSec: Schema.NullOr(Schema.Number),
rssPeakMB: Schema.Number,
rssMB: Schema.Number,
heapAfterGcMB: Schema.Number,
});
export type Window = typeof Window.Type;
const Spread = Schema.Struct({ median: Schema.Number, p90: Schema.Number });
const FirstWord = Schema.Struct({ toRequestMs: Spread, toDoneMs: Spread });
export type FirstWord = typeof FirstWord.Type;
const Scaling = Schema.Struct({
heapMBPerThread: Schema.Number,
rssMBPerThread: Schema.Number,
cpuPctPerThread: Schema.Number,
wakeupsPerThread: Schema.NullOr(Schema.Number),
/** Each measured point as [threads, cpuPct, wakeupsPerSec, rssMB, heapAfterGcMB]; not compared. */
points: Schema.Array(Schema.Array(Schema.NullOr(Schema.Number))),
});
const Soak = Schema.Struct({
minutes: Schema.Number,
heapMBPerHour: Schema.Number,
rssMBPerHour: Schema.Number,
});

/** One pass over the scenarios. */
export const Measured = Schema.Struct({
startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })),
rest: Schema.optional(Window),
firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })),
quiet: Schema.optional(Window),
scaling: Schema.optional(Scaling),
streaming: Schema.optional(Window),
soak: Schema.optional(Soak),
});
export type Measured = typeof Measured.Type;

const Hotspot = Schema.Struct({ frame: Schema.String, value: Schema.Number });
export type Hotspot = typeof Hotspot.Type;
const ProfileSummary = Schema.Struct({
cpuMs: Schema.Array(Hotspot),
allocatedMB: Schema.Array(Hotspot),
});
export type ProfileSummary = typeof ProfileSummary.Type;
export const HeapGrowth = Schema.Struct({
constructor: Schema.String,
count: Schema.Number,
MB: Schema.Number,
});

export const ServerMetrics = Schema.Struct({
meta: Schema.Record(
Schema.String,
Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]),
),
runs: Schema.Array(Measured),
/** Top CPU self time (ms) and allocated MB by function, from the last run. */
profiles: Schema.optional(Schema.Record(Schema.String, ProfileSummary)),
soakHeapGrowth: Schema.optional(Schema.Array(HeapGrowth)),
});
export type ServerMetrics = typeof ServerMetrics.Type;

export const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits;

/** `ps -o time=` CPU time, `[[dd-]hh:]mm:ss[.ss]`, in seconds; NaN for anything else. */
export function parsePsCpuTime(text: string) {
const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(text.trim());
if (match === null) return Number.NaN;
const [, days = "0", hours = "0", minutes = "0", seconds = "0"] = match;
return ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
}

/**
* `--only`, `--threads` and `--soak` as run options. Thread counts must ascend because threads stay
* open, so a lower count after a higher one would mislabel its window. A soak alone runs nothing else.
*/
export function parseRunSelection(input: {
readonly only: string;
readonly threads: string;
readonly soak: number;
readonly scenarios: ReadonlyArray<string>;
}):
| { readonly only: ReadonlyArray<string>; readonly threads: ReadonlyArray<number> }
| { readonly error: string } {
const only = input.only.split(",").filter(Boolean);
const unknown = only.filter((name) => !input.scenarios.includes(name));
if (unknown.length > 0) return { error: `unknown scenario: ${unknown.join(", ")}` };
const threads = input.threads
.split(",")
.map((count) => (count.trim() === "" ? Number.NaN : Number(count)));
if (
threads.some(
(count, index) => !Number.isInteger(count) || count < 0 || count < (threads[index - 1] ?? 0),
)
) {
return { error: "--threads takes ascending counts such as 0,5,10,20" };
}
if (!Number.isInteger(input.soak) || input.soak < 0)
return { error: "--soak takes minutes, 0 for none" };
return { only: input.soak > 0 && only.length === 0 ? ["none"] : only, threads };
}

export function spread(values: ReadonlyArray<number>) {
const sorted = values.toSorted((a, b) => a - b);
const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)];
return { median: Math.round(at(0.5) ?? 0), p90: Math.round(at(0.9) ?? 0) };
}

/** Least-squares slope of y over x. */
export function slope(points: ReadonlyArray<readonly [number, number]>) {
const n = points.length;
if (n < 2) return 0;
const mx = points.reduce((sum, [x]) => sum + x, 0) / n;
const my = points.reduce((sum, [, y]) => sum + y, 0) / n;
let numerator = 0;
let denominator = 0;
for (const [x, y] of points) {
numerator += (x - mx) * (y - my);
denominator += (x - mx) ** 2;
}
return denominator === 0 ? 0 : numerator / denominator;
}

/** Numeric leaves by dotted path, such as `quiet.cpuPct` or `firstWord.worktree.toRequestMs.p90`. */
export function flatten(measured: Measured): Map<string, number> {
const values = new Map<string, number>();
const visit = (value: unknown, path: string) => {
if (typeof value === "number") values.set(path, value);
else if (value && typeof value === "object") {
for (const [key, child] of Object.entries(value)) visit(child, path ? `${path}.${key}` : key);
}
};
visit(measured, "");
return values;
}

function noiseFloor(metric: string) {
if (metric.startsWith("scaling.")) return metric.endsWith("cpuPctPerThread") ? 0.2 : 2;
if (metric.startsWith("soak.")) return 20;
if (metric.endsWith("cpuPct")) return 1;
if (metric.endsWith("wakeupsPerSec")) return 20;
if (metric.endsWith("MB")) return 15;
return 300;
}

const median = (values: ReadonlyArray<number>) => {
const sorted = values.toSorted((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;
};

/** 95% bootstrap interval of median(b) - median(a), with a fixed seed so reruns agree. */
export function bootstrapMedianDifference(a: ReadonlyArray<number>, b: ReadonlyArray<number>) {
let seed = 0x5eed;
const random = () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
};
const resample = (values: ReadonlyArray<number>) =>
median(Array.from(values, () => values[Math.floor(random() * values.length)]!));
const differences = Array.from({ length: 2_000 }, () => resample(b) - resample(a)).toSorted(
(x, y) => x - y,
);
return [differences[49]!, differences[1_949]!] as const;
}

export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) {
const collect = (metrics: ServerMetrics) => {
const values = new Map<string, number[]>();
for (const run of metrics.runs) {
for (const [metric, value] of flatten(run)) {
values.set(metric, [...(values.get(metric) ?? []), value]);
}
}
return values;
};
const a = collect(before);
const b = collect(after);
const lines = [
"### Server metrics (lower is better)",
"",
`before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs), ${after.meta.platform}${after.meta.noAgentScope ? ", no agent scope" : ""}`,
"",
"| metric | before | after | change | 95% interval | |",
"| :-- | --: | --: | --: | --: | :-- |",
];
const regressed: string[] = [];
const improved: string[] = [];
let compared = 0;
for (const metric of new Set([...a.keys(), ...b.keys()])) {
if (metric === "soak.minutes" || metric.startsWith("scaling.points")) continue;
const x = a.get(metric);
const y = b.get(metric);
if (!x || !y) {
lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`);
continue;
Comment thread
juliusmarminge marked this conversation as resolved.
Resolved
}
compared++;
const mx = median(x);
const my = median(y);
// A change counts only past both the relative threshold and the absolute noise floor.
const limit = Math.max(noiseFloor(metric), (Math.abs(mx) * threshold) / 100);
const repeated = x.length > 1 && y.length > 1;
const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx];
const verdict = low > limit ? "worse" : high < -limit ? "better" : "";
if (verdict === "worse") regressed.push(metric);
if (verdict === "better") improved.push(metric);
const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100;
const shown = Number.isFinite(percent)
? `${percent > 0 ? "+" : ""}${Math.round(percent)}%`
: "new";
const interval = repeated ? `${round(low, 2)} to ${round(high, 2)}` : "";
lines.push(
`| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`,
);
}
return { table: lines.join("\n"), regressed, improved, compared };
}

const CallFrame = Schema.Struct({
functionName: Schema.String,
url: Schema.String,
lineNumber: Schema.Number,
});
type CallFrame = typeof CallFrame.Type;
export const CpuProfile = Schema.Struct({
nodes: Schema.Array(
Schema.Struct({ callFrame: CallFrame, hitCount: Schema.optional(Schema.Number) }),
),
samples: Schema.optional(Schema.Array(Schema.Number)),
startTime: Schema.Number,
endTime: Schema.Number,
});
interface HeapProfileNode {
readonly callFrame: CallFrame;
readonly selfSize: number;
readonly children: ReadonlyArray<HeapProfileNode>;
}
const HeapProfileNode: Schema.Codec<HeapProfileNode> = Schema.Struct({
callFrame: CallFrame,
selfSize: Schema.Number,
children: Schema.Array(Schema.suspend(() => HeapProfileNode)),
});
export const HeapProfile = Schema.Struct({ head: HeapProfileNode });

const shortUrl = (url: string) =>
url
.replace(/^file:\/\//, "")
.split(/[\\/]/)
.slice(-3)
.join("/");
const frameName = (frame: CallFrame) =>
`${frame.functionName || "(anonymous)"} ${frame.url ? `${shortUrl(frame.url)}:${frame.lineNumber + 1}` : ""}`.trim();
const top = (totals: Map<string, number>, digits: number): Hotspot[] =>
[...totals]
.toSorted((a, b) => b[1] - a[1])
.slice(0, 10)
.map(([frame, value]) => ({ frame, value: round(value, digits) }));

/** Top CPU self time in ms and allocated MB, by function. */
export function summarizeProfiles(
cpu: typeof CpuProfile.Type,
heap: typeof HeapProfile.Type,
): ProfileSummary {
const perSampleMs = (cpu.endTime - cpu.startTime) / 1_000 / Math.max(1, cpu.samples?.length ?? 1);
const cpuTotals = new Map<string, number>();
for (const node of cpu.nodes) {
if (!node.hitCount || node.callFrame.functionName === "(idle)") continue;
const name = frameName(node.callFrame);
cpuTotals.set(name, (cpuTotals.get(name) ?? 0) + node.hitCount * perSampleMs);
}
const allocations = new Map<string, number>();
const visit = (node: HeapProfileNode) => {
const name = frameName(node.callFrame);
allocations.set(name, (allocations.get(name) ?? 0) + node.selfSize / 1e6);
for (const child of node.children) visit(child);
};
visit(heap.head);
return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) };
}

export const HeapSnapshot = Schema.Struct({
snapshot: Schema.Struct({
meta: Schema.Struct({
node_fields: Schema.Array(Schema.String),
node_types: Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])),
}),
}),
nodes: Schema.Array(Schema.Number),
strings: Schema.Array(Schema.String),
});

/** Self size by constructor from a V8 heap snapshot. */
export function heapByConstructor(snapshot: typeof HeapSnapshot.Type) {
const fields = snapshot.snapshot.meta.node_fields;
const typeNames = snapshot.snapshot.meta.node_types[0];
const types = Array.isArray(typeNames) ? typeNames : [];
const typeAt = fields.indexOf("type");
const nameAt = fields.indexOf("name");
const sizeAt = fields.indexOf("self_size");
const totals = new Map<string, { count: number; bytes: number }>();
for (let index = 0; index < snapshot.nodes.length; index += fields.length) {
const type = types[snapshot.nodes[index + typeAt]!] ?? "?";
const label = snapshot.strings[snapshot.nodes[index + nameAt]!] ?? "";
const name =
type === "object"
? label.slice(0, 80)
: type === "closure"
? `(closure) ${label.slice(0, 60)}`
: `(${type.replace(/^(concatenated|sliced) /, "")})`;
const entry = totals.get(name) ?? { count: 0, bytes: 0 };
entry.count++;
entry.bytes += snapshot.nodes[index + sizeAt]!;
totals.set(name, entry);
}
return totals;
}

/** The constructors whose heap grew most from one snapshot to the next. */
export function heapGrowth(
before: ReturnType<typeof heapByConstructor>,
after: ReturnType<typeof heapByConstructor>,
) {
return [...after]
.map(([name, { count, bytes }]) => ({
constructor: name,
count: count - (before.get(name)?.count ?? 0),
bytes: bytes - (before.get(name)?.bytes ?? 0),
}))
.filter((entry) => entry.bytes > 0)
.toSorted((a, b) => b.bytes - a.bytes)
.slice(0, 25)
.map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) }));
}
Loading
Loading