diff --git a/apps/server/scripts/migrate-dev-db.test.ts b/apps/server/scripts/migrate-dev-db.test.ts index c81b01b0fe604..d92b5e6a4aab8 100644 --- a/apps/server/scripts/migrate-dev-db.test.ts +++ b/apps/server/scripts/migrate-dev-db.test.ts @@ -7,7 +7,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import { runMigrations } from "../src/persistence/Migrations.ts"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; -import { runMigrateDevDb } from "./migrate-dev-db.ts"; +import { dropResumableFamilies, runMigrateDevDb } from "./migrate-dev-db.ts"; const withDatabase = ( databasePath: string, @@ -102,6 +102,8 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio ["subagent-parent", "project-kept", "completed", "{}", "2026-08-05"], ["subagent-child", "project-kept", "completed", subagentPayload, "2026-08-05"], ["deleted-project-thread", "project-deleted", "completed", "{}", "2026-08-05"], + // Finished, but startup recovery would deliver its unread steer and start a turn. + ["steer-thread", "project-kept", "completed", "{}", "2026-08-09"], ] as const; for (const [threadId, projectId, runStatus, payload, updatedAt] of threads) { yield* sql`INSERT INTO orchestration_v2_projection_threads @@ -114,6 +116,10 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio (event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json, application_event_version) VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}', 2)`; } + yield* sql`INSERT INTO orchestration_v2_projection_turn_items + (turn_item_id, thread_id, run_id, ordinal, type, status, updated_at, payload_json) + VALUES ('steer-item', 'steer-thread', 'run-steer-thread', 2, 'user_message', 'pending', + '2026-08-09', '{"inputIntent":"steer"}')`; // A V1 thread the server already imported must not trip the legacy guard. yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, runtime_mode, created_at, updated_at) @@ -244,6 +250,78 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { }), ); + it.effect("drops resumable families from a seed in place, the pending steer included", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-resumable-" }); + const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-home-" }); + const database = yield* createFixtureSource(dir); + + assert.equal(yield* dropResumableFamilies(database, { sharedHome }), 4); + const { threads, sessions } = yield* withDatabase( + database, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return { + threads: yield* sql<{ thread_id: string }>` + SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`, + sessions: yield* sql<{ provider_session_id: string }>` + SELECT provider_session_id FROM orchestration_v2_projection_provider_sessions`, + }; + }), + ); + assert.deepStrictEqual( + threads.map((row) => row.thread_id), + [ + "archived-thread", + "deleted-project-thread", + "fork-thread", + "settled-thread", + "stopped-thread", + ], + ); + assert.deepStrictEqual( + sessions.map((row) => row.provider_session_id), + ["session-shared"], + "a session the kept stopped-thread still binds stays with it", + ); + assert.equal(yield* dropResumableFamilies(database, { sharedHome }), 0); + }), + ); + + it.effect("refuses to drop from the shared database through a symlink or a hard link", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" }); + const elsewhere = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-link-" }); + const fixture = yield* createFixtureSource(sharedHome); + const live = path.join(sharedHome, "userdata", "statev2.sqlite"); + yield* fs.makeDirectory(path.dirname(live), { recursive: true }); + yield* fs.rename(fixture, live); + const symlink = path.join(elsewhere, "statev2.sqlite"); + yield* fs.symlink(live, symlink); + // A hard link has its own path; only the file's identity gives it away. + const hardLink = path.join(elsewhere, "copy.sqlite"); + yield* fs.link(live, hardLink); + + for (const link of [symlink, hardLink]) { + const refused = yield* Effect.flip(dropResumableFamilies(link, { sharedHome })); + assert.equal(refused._tag, "MigrateDevDbSharedHomeError", link); + } + const threads = yield* withDatabase( + live, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const [row] = yield* sql<{ n: number }>` + SELECT COUNT(*) AS n FROM orchestration_v2_projection_threads`; + return Number(row?.n ?? 0); + }), + ); + assert.equal(threads, 10, "the shared database is untouched"); + }), + ); + it.effect("never copies an archived thread, and new events append after the source's", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/scripts/migrate-dev-db.ts b/apps/server/scripts/migrate-dev-db.ts index b44e7c52ea14f..858806c1de706 100644 --- a/apps/server/scripts/migrate-dev-db.ts +++ b/apps/server/scripts/migrate-dev-db.ts @@ -18,6 +18,7 @@ import { Command, Flag } from "effect/cli"; import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts"; import { rebuildMessageSearch } from "../src/orchestration-v2/messageSearchIndex.ts"; import { runMigrations } from "../src/persistence/Migrations.ts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; export class MigrateDevDbNotInWorktreeError extends Schema.TaggedError()( @@ -195,12 +196,19 @@ const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath: } }); -const RECOVERY_KINDS: ReadonlyArray = [ - "queued-runs", - "runtime", - "subagent-results", - "delegated-completions", -]; +// Every kind startup recovery resumes, so a copied family never starts work by itself. The record +// fails typecheck when a kind is added and not listed here. +const RECOVERY_KIND_SET = { + "queued-runs": true, + runtime: true, + "restart-continuations": true, + "subagent-results": true, + "delegated-completions": true, + "unread-steers": true, +} satisfies Record; +const RECOVERY_KINDS = Object.keys( + RECOVERY_KIND_SET, +) as ReadonlyArray; const CLEARED_TABLES: ReadonlyArray = [ "scheduled_tasks", @@ -322,19 +330,17 @@ const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath: yield* sql`DETACH DATABASE src`; }); -const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) { +/** + * Threads a server started on this database would resume by itself: every startup recovery kind, + * plus latest-run failures and recovery choices, which usage-limit recovery can resume. + */ +export const resumableThreadIds = Effect.fn("resumableDevDbThreadIds")(function* () { const sql = yield* SqlClient.SqlClient; - - // Usage-limit recovery also depends on settings; exclude latest-run failures and recovery choices. const projections = yield* ProjectionStore.ProjectionStoreV2; - const recoveryThreadIds = yield* Effect.forEach(RECOVERY_KINDS, (kind) => + const recovery = yield* Effect.forEach(RECOVERY_KINDS, (kind) => projections.getRecoveryThreadIds(kind), ); - yield* sql`CREATE TEMP TABLE live_threads (thread_id TEXT PRIMARY KEY)`; - for (const threadId of new Set(recoveryThreadIds.flat())) { - yield* sql`INSERT INTO live_threads (thread_id) VALUES (${threadId})`; - } - yield* sql`INSERT OR IGNORE INTO live_threads (thread_id) + const failedOrRecovering = yield* sql<{ thread_id: string }>` SELECT r.thread_id FROM orchestration_v2_projection_runs r WHERE r.status = 'failed' AND r.ordinal = ( SELECT MAX(latest.ordinal) FROM orchestration_v2_projection_runs latest @@ -342,6 +348,121 @@ const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigra UNION SELECT thread_id FROM orchestration_v2_projection_threads WHERE json_extract(payload_json, '$.limitRecovery') IS NOT NULL`; + return [ + ...new Set([...recovery.flat(), ...failedOrRecovering.map((row) => row.thread_id)]), + ]; +}); + +export class MigrateDevDbResumableWorkError extends Schema.TaggedError()( + "MigrateDevDbResumableWorkError", + { databasePath: Schema.String, threads: Schema.Number }, +) { + override get message() { + return `${this.databasePath} still holds ${this.threads} threads a server would resume.`; + } +} + +/** + * Drops, in place, every thread family a server started on `databasePath` would resume, and fails + * if any remain. A database seeded by an older checkout can miss a recovery kind added since. + */ +export const dropResumableFamilies = Effect.fn("dropResumableDevDbFamilies")(function* ( + databasePath: string, + options: RunMigrateDevDbOptions = {}, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const platform = yield* HostProcess.Platform; + // A symlink, `..` or another letter case can name the live database; compare where they lead. + const resolve = (file: string) => + fs.realPath(file).pipe( + Effect.catch(() => + fs + .realPath(path.dirname(file)) + .pipe(Effect.map((dir) => path.join(dir, path.basename(file)))), + ), + Effect.orElseSucceed(() => path.resolve(file)), + ); + const comparable = (resolved: string) => + platform === "linux" ? resolved : resolved.toLowerCase(); + // A hard link has its own path, so the file itself is compared too. + const identity = (file: string) => + fs.stat(file).pipe( + Effect.map((info) => Option.map(info.ino, (ino) => `${info.dev}:${ino}`)), + Effect.orElseSucceed(() => Option.none()), + ); + const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3")); + const liveDatabase = path.join(sharedHome, "userdata", "statev2.sqlite"); + const [target, live] = yield* Effect.all([resolve(databasePath), resolve(liveDatabase)]); + const targetIdentity = yield* identity(target); + const liveIdentities = yield* Effect.forEach( + [liveDatabase, `${liveDatabase}-wal`, `${liveDatabase}-shm`], + identity, + ); + if ( + comparable(target) === comparable(live) || + (Option.isSome(targetIdentity) && + liveIdentities.some( + (candidate) => Option.isSome(candidate) && candidate.value === targetIdentity.value, + )) + ) { + return yield* new MigrateDevDbSharedHomeError(); + } + // Beside the real file, where a running server keeps its runtime state. + yield* ensureNotInUse(target); + return yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const resumable = yield* resumableThreadIds(); + if (resumable.length > 0) { + yield* sql`CREATE TEMP TABLE resumable_families (thread_id TEXT PRIMARY KEY)`; + yield* sql`INSERT OR IGNORE INTO resumable_families + SELECT family.thread_id FROM orchestration_v2_projection_threads family + WHERE COALESCE(json_extract(family.payload_json, '$.lineage.rootThreadId'), family.thread_id) IN ( + SELECT COALESCE(json_extract(payload_json, '$.lineage.rootThreadId'), thread_id) + FROM orchestration_v2_projection_threads WHERE thread_id IN ${sql.in(resumable)})`; + yield* sql.withTransaction( + Effect.gen(function* () { + for (const { name } of yield* sql<{ name: string }>` + SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c + WHERE m.type = 'table' AND c.name = 'thread_id' + AND m.name <> ${PROVIDER_SESSIONS_TABLE}`) { + yield* sql`DELETE FROM ${sql(name)} + WHERE thread_id IN (SELECT thread_id FROM resumable_families)`; + } + // A session a kept thread still binds stays, as pruning keeps it. + yield* sql`DELETE FROM ${sql(PROVIDER_SESSIONS_TABLE)} + WHERE thread_id IN (SELECT thread_id FROM resumable_families) + AND provider_session_id NOT IN ( + SELECT provider_session_id FROM orchestration_v2_projection_provider_session_bindings + WHERE thread_id NOT IN (SELECT thread_id FROM resumable_families) + )`; + yield* sql`DELETE FROM orchestration_v2_projection_context_transfers + WHERE source_thread_id IN (SELECT thread_id FROM resumable_families) + OR target_thread_id IN (SELECT thread_id FROM resumable_families)`; + yield* sql`DELETE FROM orchestration_events WHERE aggregate_kind = 'thread' + AND stream_id IN (SELECT thread_id FROM resumable_families)`; + }), + ); + } + const left = yield* resumableThreadIds(); + if (left.length > 0) { + return yield* new MigrateDevDbResumableWorkError({ databasePath, threads: left.length }); + } + return resumable.length; + }).pipe( + Effect.provide( + ProjectionStore.layer.pipe(Layer.provideMerge(NodeSqliteClient.layer({ filename: target }))), + ), + ); +}); + +const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) { + const sql = yield* SqlClient.SqlClient; + + yield* sql`CREATE TEMP TABLE live_threads (thread_id TEXT PRIMARY KEY)`; + for (const threadId of yield* resumableThreadIds()) { + yield* sql`INSERT INTO live_threads (thread_id) VALUES (${threadId})`; + } // Clone or drop whole thread families to preserve fork and subagent lineage reads. yield* sql`CREATE TEMP TABLE thread_families AS @@ -641,9 +762,20 @@ export const migrateDevDbCommand = Command.make( Flag.optional, Flag.withDescription("Source database. Defaults to ~/.t3/userdata/statev2.sqlite."), ), + dropResumable: Flag.String("drop-resumable").pipe( + Flag.optional, + Flag.withDescription( + "Only drop, in place, the thread families a server started on this database would resume, and fail if any remain. Copies only; never the live database.", + ), + ), }, - ({ projects, threadsPerProject, baseDir, source }) => + ({ projects, threadsPerProject, baseDir, source, dropResumable }) => Effect.gen(function* () { + if (Option.isSome(dropResumable)) { + const dropped = yield* dropResumableFamilies(dropResumable.value); + yield* Console.log(`Dropped ${dropped} resumable threads.`); + return; + } const result = yield* runMigrateDevDb({ projects, threadsPerProject, diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 95cd1c18f9fe8..3ccd4235244b5 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -48,6 +48,20 @@ export const Measured = Schema.Struct({ scaling: Schema.optional(Scaling), streaming: Schema.optional(Window), soak: Schema.optional(Soak), + /** A server on a copy of the developer's real database, its projects backed by clones. */ + busy: Schema.optional( + Schema.Struct({ + readyMs: Schema.Number, + projects: Schema.Number, + /** Off-heap MB the server held so its RSS is a long-lived server's; not compared. */ + ballastMB: Schema.Number, + rest: Window, + shellMs: Spread, + shellKB: Schema.Number, + /** Back-to-back turns in a clone, each ending in a checkpoint. */ + git: Window, + }), + ), }); export type Measured = typeof Measured.Type; @@ -156,6 +170,8 @@ function noiseFloor(metric: string) { if (metric.endsWith("cpuPct")) return 1; if (metric.endsWith("wakeupsPerSec")) return 20; if (metric.endsWith("MB")) return 15; + if (metric.endsWith("KB")) return 20; + if (metric.includes(".shellMs.")) return 50; if (metric.endsWith("loopDelayP50Ms")) return 2; if (metric.endsWith("loopDelayP99Ms")) return 5; if (metric.endsWith("loopDelayMaxMs")) return 20; @@ -214,6 +230,8 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre if ( metric === "soak.minutes" || metric.endsWith("loopSamples") || + metric === "busy.projects" || + metric === "busy.ballastMB" || metric.startsWith("scaling.points") ) { continue; @@ -374,3 +392,22 @@ export function heapGrowth( .slice(0, 25) .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) })); } + +const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.String)); +const spellings: ReadonlyArray<(path: string) => string> = [ + (path) => path, + // Inside a JSON string, with every escape JSON applies: backslashes, quotes, control characters. + (path) => encodeJsonString(path).slice(1, -1), + (path) => path.replaceAll("\\", "/"), +]; + +/** How a path can appear in a database's text: as written, JSON-escaped, with forward slashes. */ +export function pathSpellings(path: string) { + return [...new Set(spellings.map((spell) => spell(path)))]; +} + +/** Each spelling of `from` with the same spelling of `to`, for a textual rewrite. */ +export function pathRewrites(from: string, to: string) { + const pairs = new Map(spellings.map((spell) => [spell(from), spell(to)] as const)); + return [...pairs]; +} diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index addafee5461ec..8d4fe431fe7c7 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -6,6 +6,8 @@ import { heapGrowth, parsePsCpuTime, parseRunSelection, + pathRewrites, + pathSpellings, ServerMetrics, slope, } from "./server-metrics-report.ts"; @@ -125,6 +127,35 @@ describe("compareMetrics", () => { }); }); +describe("compareMetrics on the busy shell snapshot", () => { + const window = { cpuPct: 1, wakeupsPerSec: 10, rssPeakMB: 500, rssMB: 500, heapAfterGcMB: 200 }; + const busyRun = (shellMs: number, shellKB: number) => + ({ + meta, + runs: [ + { + busy: { + readyMs: 8_000, + projects: 9, + ballastMB: 768, + rest: window, + shellMs: { median: shellMs, p90: shellMs }, + shellKB, + git: window, + }, + }, + ], + }) satisfies ServerMetrics; + it.each([ + ["40 ms slower, under the 50 ms floor", busyRun(230, 100), []], + ["150 ms slower, past it", busyRun(340, 100), ["busy.shellMs.median", "busy.shellMs.p90"]], + ["15 KB larger, under the 20 KB floor", busyRun(190, 115), []], + ["40 KB larger, past it", busyRun(190, 140), ["busy.shellKB"]], + ])("%s", (_name, after, regressed) => { + expect(compareMetrics(busyRun(190, 100), after).regressed).toEqual(regressed); + }); +}); + describe("heapGrowth", () => { it("lists only constructors that grew, small growth included", () => { const before = new Map([ @@ -220,3 +251,56 @@ describe("parseRunSelection", () => { expect(parseRunSelection({ ...input, scenarios })).toEqual(expected); }); }); + +describe("pathSpellings", () => { + it.each([ + ["a POSIX path, one spelling", "/home/dev/repo", ["/home/dev/repo"]], + [ + "a Windows path as written, JSON-escaped, and with forward slashes", + "C:\\Users\\dev\\repo", + ["C:\\Users\\dev\\repo", "C:\\\\Users\\\\dev\\\\repo", "C:/Users/dev/repo"], + ], + [ + "a path with a quote, escaped the way JSON stores it", + '/mnt/dev/quote"repo', + ['/mnt/dev/quote"repo', '/mnt/dev/quote\\"repo'], + ], + [ + "a path with a control character, escaped the way JSON stores it", + "/mnt/dev/new\nline", + ["/mnt/dev/new\nline", "/mnt/dev/new\\nline"], + ], + ])("%s", (_name, path, spellings) => { + expect(pathSpellings(path)).toEqual(spellings); + }); +}); + +describe("pathRewrites", () => { + const rewrite = (text: string, from: string, to: string) => + pathRewrites(from, to).reduce((value, [a, b]) => value.replaceAll(a, b), text); + it.each([ + [ + "a POSIX path in JSON", + '{"cwd":"/home/dev/repo/x"}', + "/home/dev/repo", + "/tmp/run/gone/root-0", + '{"cwd":"/tmp/run/gone/root-0/x"}', + ], + [ + "a Windows path stored JSON-escaped", + '{"cwd":"C:\\\\Users\\\\dev\\\\repo\\\\x"}', + "C:\\Users\\dev\\repo", + "D:\\run\\gone\\root-0", + '{"cwd":"D:\\\\run\\\\gone\\\\root-0\\\\x"}', + ], + [ + "a Windows path written with forward slashes", + "see C:/Users/dev/repo/x", + "C:\\Users\\dev\\repo", + "D:\\run\\gone\\root-0", + "see D:/run/gone/root-0/x", + ], + ])("%s", (_name, text, from, to, expected) => { + expect(rewrite(text, from, to)).toBe(expected); + }); +}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index c447be05621a1..78e7dd87654e1 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -10,6 +10,7 @@ import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeSocket from "@effect/platform-node/NodeSocket"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; import * as Clock from "effect/Clock"; import * as Console from "effect/Console"; @@ -26,9 +27,20 @@ import * as Random from "effect/Random"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import { Argument, Command, Flag } from "effect/cli"; -import { HttpClient, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; +import { + ORCHESTRATION_PROTOCOL_HEADER, + ORCHESTRATION_PROTOCOL_VERSION_TEXT, +} from "@t3tools/contracts"; +import { + HttpClient, + HttpClientRequest, + HttpServer, + HttpServerRequest, + HttpServerResponse, +} from "effect/http"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as Socket from "effect/socket/Socket"; @@ -45,6 +57,8 @@ import { slope, spread, parsePsCpuTime, + pathRewrites, + pathSpellings, parseRunSelection, summarizeProfiles, type FirstWord, @@ -342,6 +356,11 @@ const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { Effect.flatMap(decodeLoop), Effect.map(({ result }) => result.value), ), + // Off-heap and touched, so it adds RSS (and page tables to copy on fork) but no GC work. + ballast: (mb: number) => + send("Runtime.evaluate", { + expression: `globalThis.__t3ServerMetricsBallast = Array.from({ length: ${mb} }, () => new Uint8Array(1 << 20).fill(1)), 0`, + }).pipe(Effect.asVoid), heapAfterGc: Effect.gen(function* () { yield* send("HeapProfiler.collectGarbage"); yield* send("HeapProfiler.collectGarbage"); @@ -454,8 +473,199 @@ interface Environment { readonly requests: ReadonlyArray; readonly noAgentScope: boolean; readonly serverDir: string; + /** The checkout whose clones back a seeded server's projects. */ + readonly checkout: string; } +interface ServerOptions { + /** A base dir `migrate-dev-db` prepared; the server starts on a copy of its database. */ + readonly seed?: string; +} + +/** Transcript text: paths there are words in a conversation, which the server never acts on. */ +const TRANSCRIPT_TABLES = new Set([ + "orchestration_events", + "orchestration_v2_events", + "orchestration_v2_projection_messages", + "orchestration_v2_projection_turn_items", + "projection_thread_messages", + "projection_thread_activities", + "checkpoint_diff_blobs", +]); +const TRANSCRIPT_COLUMNS = new Set(["title", "text", "last_error"]); + +/** + * Copies a seeded database into `directory` and makes it safe to serve: every path under the + * developer's home or a project root is moved under `directory/gone`, which does not exist, and + * every project points at a clone of `checkout`, so git runs on real-size trees and never on the + * developer's. Fails if a real path survives outside transcript text. + */ +const seedBaseDir = Effect.fn("serverMetrics.seedBaseDir")(function* ( + seed: string, + baseDir: string, + directory: string, + checkout: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const environment = yield* HostProcess.Environment; + const database = path.join(baseDir, "userdata/statev2.sqlite"); + const reposDir = path.join(directory, "repos"); + const gone = path.join(directory, "gone"); + yield* fs.copyFile(path.join(seed, "userdata/statev2.sqlite"), database); + // A seed made by an older checkout can still hold work startup would resume, so this checkout's + // migrate-dev-db drops it from the copy and fails if any remains. + const dropped = yield* run( + yield* HostProcess.ExecutablePath, + [ + path.join(import.meta.dirname, "../apps/server/scripts/migrate-dev-db.ts"), + "--drop-resumable", + database, + ], + { allowExit: [0, 1] }, + ); + if (dropped.exitCode !== 0) { + return yield* new MetricsError({ + message: `refusing to start on the seed: ${dropped.stderr.trim() || dropped.stdout.trim()}`, + }); + } + return yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const projects = yield* sql<{ project_id: string; deleted: number; workspace_root: string }>` + SELECT project_id, deleted_at IS NOT NULL AS deleted, workspace_root FROM projection_projects`; + const home = environment.HOME ?? environment.USERPROFILE; + const real = [ + ...new Set( + [...(home ? [home] : []), ...projects.map((project) => project.workspace_root)].map( + (prefix) => prefix.replace(/[\\/]+$/, ""), + ), + ), + ].filter((prefix) => prefix.length > 1); + // The run's own directory sits under home too, so it is taken out before a value is judged. + const withoutRun = (column: string) => + pathSpellings(directory).reduce( + (value, spelling) => sql`replace(${value}, ${spelling}, '')`, + sql`CAST(${sql(column)} AS TEXT)`, + ); + const mentionsReal = (column: string, prefix: string) => + sql.or( + pathSpellings(prefix).map((spelling) => sql`instr(${withoutRun(column)}, ${spelling}) > 0`), + ); + const columns: Array<{ table: string; column: string }> = []; + for (const { name } of yield* sql<{ name: string; virtual: number }>` + SELECT name FROM sqlite_master WHERE type = 'table' AND sql NOT LIKE 'CREATE VIRTUAL%'`) { + if (TRANSCRIPT_TABLES.has(name) || name.startsWith("sqlite_") || name.includes("search")) { + continue; + } + for (const column of yield* sql<{ name: string; type: string }>` + SELECT name, type FROM pragma_table_info(${name})`) { + if (/^(TEXT|)$/i.test(column.type) && !TRANSCRIPT_COLUMNS.has(column.name)) { + columns.push({ table: name, column: column.name }); + } + } + } + // Every occurrence, mid-string too: a prompt or preview inside state JSON can name a path. + // Longer prefixes first, so a project root is not cut by the home prefix inside it. + const longestFirst = real.toSorted((a, b) => b.length - a.length); + // Every spelling, since JSON keeps a Windows path's backslashes doubled. Each goes to a marker + // first: the destination sits under home too, and a later, shorter prefix would rewrite it. + const rewrites = longestFirst.flatMap((prefix, index) => + pathRewrites(prefix, path.join(gone, `root-${index}`)).map(([from, to], spelling) => ({ + from, + to, + marker: `«t3-bench-gone-${index}-${spelling}»`, + })), + ); + for (const { table, column } of columns) { + for (const [from, to] of [ + ...rewrites.map(({ from, marker }) => [from, marker] as const), + ...rewrites.map(({ marker, to }) => [marker, to] as const), + ]) { + yield* sql`UPDATE ${sql(table)} SET ${sql(column)} = replace(${sql(column)}, ${from}, ${to}) + WHERE instr(${sql(column)}, ${from}) > 0`; + } + } + const roots: string[] = []; + yield* Effect.forEach( + projects, + (project, index) => + Effect.gen(function* () { + const root = path.join(reposDir, `repo-${index}`); + if (!project.deleted) { + yield* run("git", ["clone", "--shared", "-q", checkout, root]); + roots.push(root); + } + yield* sql`UPDATE projection_projects SET workspace_root = ${root} + WHERE project_id = ${project.project_id}`; + }), + { concurrency: 4, discard: true }, + ); + yield* sql`UPDATE projection_projects SET tracked_folders_json = '[]', favicon_path = NULL`; + yield* sql`UPDATE orchestration_v2_projection_threads + SET payload_json = json_set(payload_json, '$.worktreePath', json('null')) + WHERE json_extract(payload_json, '$.worktreePath') IS NOT NULL`; + const tables = new Set( + (yield* sql<{ name: string }>`SELECT name FROM sqlite_master WHERE type = 'table'`).map( + (table) => table.name, + ), + ); + if (tables.has("projection_threads")) + yield* sql`UPDATE projection_threads SET worktree_path = NULL`; + // Durable workflows postdate migrate-dev-db's list of pending work, so none may resume here. + for (const table of tables) { + if (table === "task_folders" || table.startsWith("workflow_")) { + yield* sql`DELETE FROM ${sql(table)}`; + } + } + const named: string[] = []; + for (const { table, column } of columns) { + for (const prefix of real) { + const [found] = yield* sql<{ n: number }>` + SELECT COUNT(*) AS n FROM ${sql(table)} WHERE ${mentionsReal(column, prefix)}`; + if (Number(found?.n ?? 0) > 0) named.push(`${table}.${column}`); + } + } + if (named.length > 0) { + return yield* new MetricsError({ + message: `the seed still names real paths in ${[...new Set(named)].join(", ")}`, + }); + } + const [runs] = yield* sql<{ n: number }>` + SELECT COUNT(*) AS n FROM orchestration_v2_projection_runs`; + return { roots, runs: Number(runs?.n ?? 0) }; + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: database }))); +}); + +/** Runs the checkout's own `migrate-dev-db` into a temp base dir, closed with the scope. */ +const prepareSeed = Effect.fn("serverMetrics.prepareSeed")(function* ( + checkout: string, + projects: number, + threadsPerProject: number, +) { + const fs = yield* FileSystem.FileSystem; + const node = yield* HostProcess.ExecutablePath; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-seed-" }); + yield* Console.error(`seeding ${checkout} from the real database (read-only)...`); + // Its output names the kept projects, so it stays out of ours. + const seeded = yield* run( + node, + [ + "apps/server/scripts/migrate-dev-db.ts", + "--base-dir", + dir, + "--projects", + `${projects}`, + "--threads-per-project", + `${threadsPerProject}`, + ], + { cwd: checkout, allowExit: [0, 1] }, + ); + if (seeded.exitCode !== 0) { + return yield* new MetricsError({ message: `migrate-dev-db failed:\n${seeded.stderr.trim()}` }); + } + return dir; +}); + /** A free loopback port: bind 0, read it, let it go. */ const freePort = Effect.scoped( Effect.gen(function* () { @@ -469,6 +679,7 @@ const freePort = Effect.scoped( const startServer = Effect.fn("serverMetrics.startServer")(function* ( environment: Environment, name: string, + options: ServerOptions = {}, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -494,6 +705,11 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( const baseDir = path.join(directory, "base"); // Branch names come from Claude too, so a worktree launch's naming call reaches the fake API. yield* fs.makeDirectory(path.join(baseDir, "userdata"), { recursive: true }); + const seeded = + options.seed === undefined + ? undefined + : yield* seedBaseDir(options.seed, baseDir, directory, environment.checkout); + const roots = seeded?.roots ?? []; yield* fs.writeFileString( path.join(baseDir, "userdata/settings.json"), encodeJson({ textGenerationModelSelection: { instanceId: "claudeAgent", model: MODEL } }), @@ -657,10 +873,44 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( return { readyMs, + startedAt: started, + origin: `http://127.0.0.1:${port}`, + /** The seeded projects' clones; none without a seed. */ + roots, + /** + * Fails if the server started a run or called the agent API on its own since `since`: a seeded + * server must never resume the developer's work. + */ + assertIdle: Effect.fn("serverMetrics.assertIdle")(function* (since: number) { + const called = environment.requests.some((request) => request.at >= since); + const runs = yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const [row] = yield* sql<{ n: number }>` + SELECT COUNT(*) AS n FROM orchestration_v2_projection_runs`; + return Number(row?.n ?? 0); + }).pipe( + Effect.provide( + NodeSqliteClient.layer({ + filename: path.join(baseDir, "userdata/statev2.sqlite"), + readonly: true, + }), + ), + ); + if (called || runs !== (seeded?.runs ?? runs)) { + return yield* new MetricsError({ + message: `the seeded server started work on its own (${runs - (seeded?.runs ?? 0)} new runs, API ${called ? "called" : "idle"})`, + }); + } + }), measure, profile: devtools.profile, snapshot: devtools.snapshot, - threadStart: (message: string, extra: ReadonlyArray = []) => + heapAfterGc: devtools.heapAfterGc, + ballast: devtools.ballast, + issueToken: cli(["auth", "session", "issue", "--token-only"]).pipe( + Effect.map(({ stdout }) => stdout.trim()), + ), + threadStart: (message: string, extra: ReadonlyArray = [], root = project) => cli([ "thread", "start", @@ -669,7 +919,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( "--model", MODEL, ...extra, - project, + root, message, ]), threadSend: (threadId: string, message: string) => @@ -738,7 +988,63 @@ const openThreads = Effect.fn("serverMetrics.openThreads")(function* ( return ids.filter((id) => id !== undefined); }); -const SCENARIOS = ["startup", "rest", "firstWord", "quiet", "streaming"] as const; +/** The shell snapshot the web and mobile clients load first, timed to its last byte. */ +const loadShell = Effect.fn("serverMetrics.loadShell")(function* (server: Server, times: number) { + const http = yield* HttpClient.HttpClient; + const token = yield* server.issueToken; + const request = HttpClientRequest.get( + `${server.origin}/api/orchestration/shell?omitIdleSubagents=1&omitOlderSettled=1`, + ).pipe( + HttpClientRequest.bearerToken(token), + HttpClientRequest.setHeader(ORCHESTRATION_PROTOCOL_HEADER, ORCHESTRATION_PROTOCOL_VERSION_TEXT), + ); + const elapsed: number[] = []; + let bytes = 0; + for (let index = 0; index < times; index++) { + const started = yield* nowMs; + const response = yield* http.execute(request); + const body = yield* response.arrayBuffer; + if (response.status !== 200) { + return yield* new MetricsError({ message: `shell snapshot answered ${response.status}` }); + } + elapsed.push((yield* nowMs) - started); + bytes = body.byteLength; + } + return { ms: spread(elapsed), KB: Math.round(bytes / 1_000) }; +}); + +/** Short turns back to back in a clone, each ending in a checkpoint of the whole tree. */ +const gitTraffic = Effect.fn("serverMetrics.gitTraffic")(function* (server: Server) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = server.roots[0]; + if (root === undefined) return yield* new MetricsError({ message: "the seed has no projects" }); + const touch = (turn: number) => + fs.writeFileString(path.join(root, "BENCH.md"), `turn ${turn}\n`, { flag: "a" }); + yield* touch(0); + const started = yield* server.threadStart("Say hello.", ["--wait"], root); + const threadId = /^Thread (\S+)$/m.exec(started.stderr)?.[1]; + if (started.exitCode !== 0 || threadId === undefined) { + return yield* new MetricsError({ + message: `a turn in a clone failed: ${started.stderr.trim() || started.stdout.trim()}`, + }); + } + return Effect.gen(function* () { + for (let turn = 1; ; turn++) { + yield* touch(turn); + const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); + if (sent.exitCode !== 0) { + return yield* new MetricsError({ + message: `git traffic turn ${turn} failed: ${sent.stderr.trim() || sent.stdout.trim()}`, + }); + } + } + }); +}); + +const SCENARIOS = ["startup", "rest", "firstWord", "quiet", "streaming", "busy"] as const; +/** Scenarios that read the developer's real database, so they run only when named. */ +const OPT_IN_SCENARIOS: ReadonlyArray = ["busy"]; interface RunOptions { readonly checkout: string; @@ -747,6 +1053,9 @@ interface RunOptions { readonly threads: ReadonlyArray; readonly only: ReadonlyArray; readonly soakMinutes: number; + /** A seeded base dir for the busy scenario. */ + readonly seed: string | undefined; + readonly ballastMB: number; /** Where full CPU and allocation profiles go; none are written without it. */ readonly profileDir: string | undefined; } @@ -763,13 +1072,19 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption requests: api.requests, noAgentScope: options.noAgentScope, serverDir: path.join(options.checkout, "apps/server"), + checkout: options.checkout, }; - const wanted = (scenario: string) => options.only.length === 0 || options.only.includes(scenario); + const wanted = (scenario: string) => + options.only.includes(scenario) || + (options.only.length === 0 && !OPT_IN_SCENARIOS.includes(scenario)); const measured: { -readonly [K in keyof Measured]: Measured[K] } = {}; const profiles: Record = {}; let soakHeapGrowth: ReturnType | undefined; - const withServer = (name: string, body: (server: Server) => Effect.Effect) => - Effect.scoped(Effect.flatMap(startServer(environment, name), body)); + const withServer = ( + name: string, + body: (server: Server) => Effect.Effect, + serverOptions: ServerOptions = {}, + ) => Effect.scoped(Effect.flatMap(startServer(environment, name, serverOptions), body)); const profile = Effect.fn("serverMetrics.saveProfile")(function* (server: Server, name: string) { const { summary, raw } = yield* server.profile(20); profiles[name] = summary; @@ -872,6 +1187,43 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption }), ); } + if (wanted("busy")) { + if (options.seed === undefined) { + return yield* new MetricsError({ message: "the busy scenario needs a seeded database" }); + } + yield* withServer( + "busy", + (server) => + Effect.gen(function* () { + yield* server.ballast(options.ballastMB); + yield* Effect.sleep(Duration.seconds(30)); + const rest = yield* server.measure(30); + yield* server.assertIdle(server.startedAt); + const shell = yield* loadShell(server, 5); + const traffic = yield* gitTraffic(server); + // The traffic only ends by failing, which then fails the window instead of thinning it. + const git = yield* Effect.raceFirst( + Effect.gen(function* () { + yield* Effect.sleep(Duration.seconds(5)); + const window = yield* server.measure(30); + yield* profile(server, "busyGit"); + return window; + }), + traffic, + ); + measured.busy = { + readyMs: server.readyMs, + projects: server.roots.length, + ballastMB: options.ballastMB, + rest, + shellMs: shell.ms, + shellKB: shell.KB, + git, + }; + }), + { seed: options.seed }, + ); + } if (options.soakMinutes > 0) { yield* withServer("soak", (server) => Effect.gen(function* () { @@ -1030,6 +1382,29 @@ const runFlags = { Flag.withDescription(`Scenarios to run, comma separated: ${SCENARIOS.join(", ")}.`), Flag.optional, ), + seedDir: Flag.String("seed-dir").pipe( + Flag.withDescription( + "busy: a base dir `vp run migrate-dev-db --base-dir ` already seeded, instead of seeding each checkout on every invocation.", + ), + Flag.optional, + ), + busyProjects: Flag.Int("busy-projects").pipe( + Flag.withSchema(PositiveInt), + Flag.withDescription("busy: projects to keep from the real database, each backed by a clone."), + Flag.withDefault(10), + ), + busyThreads: Flag.Int("busy-threads").pipe( + Flag.withSchema(PositiveInt), + Flag.withDescription("busy: stopped threads to keep per project."), + Flag.withDefault(200), + ), + busyBallast: Flag.Int("busy-ballast-mb").pipe( + Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), + Flag.withDescription( + "busy: MB the server retains off-heap, so its RSS matches a server open for days. A seeded database alone keeps RSS near 0.5 GB.", + ), + Flag.withDefault(768), + ), soak: Flag.Int("soak").pipe( Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), Flag.withDescription( @@ -1044,6 +1419,10 @@ interface RunFlags { readonly threads: string; readonly only: Option.Option; readonly soak: number; + readonly seedDir: Option.Option; + readonly busyProjects: number; + readonly busyThreads: number; + readonly busyBallast: number; } const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( @@ -1068,10 +1447,26 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( only, soakMinutes: flags.soak, profileDir, + seed: undefined, + ballastMB: flags.busyBallast, }; return options; }); +/** The busy scenario's seed for these options: the given dir, or the checkout's own seeding. */ +const withSeed = Effect.fn("serverMetrics.withSeed")(function* ( + options: RunOptions, + flags: RunFlags, +) { + const path = yield* Path.Path; + if (!options.only.includes("busy")) return options; + const seed = Option.isSome(flags.seedDir) + ? path.resolve(flags.seedDir.value) + : yield* prepareSeed(options.checkout, flags.busyProjects, flags.busyThreads); + const seeded: RunOptions = { ...options, seed }; + return seeded; +}); + const runCommand = Command.make( "run", { @@ -1097,8 +1492,10 @@ const runCommand = Command.make( ); if (input.repeat < 1) return yield* new MetricsError({ message: "--repeat must be at least 1" }); - const options = yield* toRunOptions(input, checkout, profileDir); - const meta = yield* metaFor(options); + const unseeded = yield* toRunOptions(input, checkout, profileDir); + // Checks the machine before seeding, which takes minutes. + const meta = yield* metaFor(unseeded); + const options = yield* withSeed(unseeded, input); const runs: Measured[] = []; let last: Effect.Success> | undefined; for (let index = 0; index < input.repeat; index++) { @@ -1111,7 +1508,7 @@ const runCommand = Command.make( ...(last ? { profiles: last.profiles } : {}), ...(last?.soakHeapGrowth ? { soakHeapGrowth: last.soakHeapGrowth } : {}), }); - }), + }, Effect.scoped), ).pipe( Command.withDescription( "Measure a checkout's server: startup, rest and first word on one server, then quiet threads (with their cost per thread), streaming and an optional soak on servers of their own. Needs the real claude CLI on PATH; on Windows the native claude.exe from claude.ai/install.ps1, since an npm claude.cmd shim cannot be started without a shell.", @@ -1142,11 +1539,16 @@ const abCommand = Command.make( const path = yield* Path.Path; const outDir = path.resolve(input.outDir); yield* fs.makeDirectory(outDir, { recursive: true }); - const sides = [ + const unseeded = [ yield* toRunOptions(input, input.checkoutA, undefined), yield* toRunOptions(input, input.checkoutB, undefined), ] as const; - const metas = [yield* metaFor(sides[0]), yield* metaFor(sides[1])] as const; + // Checks the machine before seeding, which takes minutes. + const metas = [yield* metaFor(unseeded[0]), yield* metaFor(unseeded[1])] as const; + const sides = [ + yield* withSeed(unseeded[0], input), + yield* withSeed(unseeded[1], input), + ] as const; const runs: [Measured[], Measured[]] = [[], []]; for (let round = 0; round < input.rounds; round++) { // A B, then B A, so a drift in machine load lands on both sides. @@ -1161,7 +1563,7 @@ const abCommand = Command.make( yield* writeMetrics(Option.some(path.join(outDir, "a.json")), before); yield* writeMetrics(Option.some(path.join(outDir, "b.json")), after); yield* report(before, after, input.threshold); - }), + }, Effect.scoped), ).pipe( Command.withDescription( "Run two checkouts alternately on this machine and compare them. Each needs its dependencies installed; the harness comes from this script, so an old release works too.",