feat(scripts): server metrics measure a busy server on a copy of real data #41280
Mergedjuliusmarmingemerged 7 commits into
perf/server-metrics-loop-delay fromrefs/pull/41280/headmerged by juliusmarminge View on GitHubtanstack-source added labelsfeature
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -42,3 +42,13 @@4242 scaling: Schema.optional(Scaling),4343 streaming: Schema.optional(Window),4444 soak: Schema.optional(Soak),45+ /** A server on a copy of the developer's real database, its projects backed by clones. */46+ busy: Schema.optional(47+ Schema.Struct({48+ readyMs: Schema.Number,49+ projects: Schema.Number,50+ /** Off-heap MB the server held so its RSS is a long-lived server's; not compared. */51+ ballastMB: Schema.Number,52+ rest: Window,53+ shellMs: Spread,54+ shellKB: Schema.Number,@@ -860,3 +1052,21 @@8601052 }),8611053 );8621054 }1055+ if (wanted("busy")) {1056+ if (options.seed === undefined) {1057+ return yield* new MetricsError({ message: "the busy scenario needs a seeded database" });1058+ }1059+ yield* withServer(1060+ "busy",1061+ (server) =>1062+ Effect.gen(function* () {1063+ yield* server.ballast(options.ballastMB);1064+ yield* Effect.sleep(Duration.seconds(30));1065+ const rest = yield* server.measure(30);1066+ const shell = yield* loadShell(server, 5);1067+ const traffic = yield* gitTraffic(server);1068+ const loop = yield* Effect.forkScoped(traffic);1069+ yield* Effect.sleep(Duration.seconds(5));1070+ const git = yield* server.measure(30);1071+ yield* profile(server, "busyGit");1072+ yield* Fiber.interrupt(loop);@@ -1085,4 +1351,4 @@10851351 );10861352 if (input.repeat < 1)10871353 return yield* new MetricsError({ message: "--repeat must be at least 1" });1088- const options = yield* toRunOptions(input, checkout, profileDir);1354+ const options = yield* withSeed(yield* toRunOptions(input, checkout, profileDir), input);
Pushedde716a4
- @@ -451,0 +485,21 @@485+ checkout: string,486+) {487+ const fs = yield* FileSystem.FileSystem;488+ const path = yield* Path.Path;489+ const database = path.join(baseDir, "userdata/statev2.sqlite");490+ yield* fs.copyFile(path.join(seed, "userdata/statev2.sqlite"), database);491+ return yield* Effect.gen(function* () {492+ const sql = yield* SqlClient.SqlClient;493+ const projects = yield* sql<{ project_id: string; deleted: number }>`494+ SELECT project_id, deleted_at IS NOT NULL AS deleted FROM projection_projects`;495+ const roots: string[] = [];496+ yield* Effect.forEach(497+ projects,498+ (project, index) =>499+ Effect.gen(function* () {500+ const root = path.join(reposDir, `repo-${index}`);501+ if (!project.deleted) {502+ yield* run("git", ["clone", "--shared", "-q", checkout, root]);503+ roots.push(root);504+ }505+ yield* sql`UPDATE projection_projects SET workspace_root = ${root}@@ -451,0 +503,21 @@503+ roots.push(root);504+ }505+ yield* sql`UPDATE projection_projects SET workspace_root = ${root}506+ WHERE project_id = ${project.project_id}`;507+ }),508+ { concurrency: 4, discard: true },509+ );510+ yield* sql`UPDATE orchestration_v2_projection_threads511+ SET payload_json = json_set(payload_json, '$.worktreePath', json('null'))512+ WHERE json_extract(payload_json, '$.worktreePath') IS NOT NULL`;513+ const tables = new Set(514+ (yield* sql<{ name: string }>`SELECT name FROM sqlite_master WHERE type = 'table'`).map(515+ (table) => table.name,516+ ),517+ );518+ if (tables.has("projection_threads"))519+ yield* sql`UPDATE projection_threads SET worktree_path = NULL`;520+ // Durable workflows postdate migrate-dev-db's list of pending work, so none may resume here.521+ for (const table of tables) {522+ if (table === "task_folders" || table.startsWith("workflow_")) {523+ yield* sql`DELETE FROM ${sql(table)}`;
Pushedd8c4b80
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -344,0 +367,21 @@367+ */368+export const dropResumableFamilies = Effect.fn("dropResumableDevDbFamilies")(function* (369+ databasePath: string,370+) {371+ return yield* Effect.gen(function* () {372+ const sql = yield* SqlClient.SqlClient;373+ const resumable = yield* resumableThreadIds();374+ if (resumable.length > 0) {375+ yield* sql`CREATE TEMP TABLE resumable_families (thread_id TEXT PRIMARY KEY)`;376+ yield* sql`INSERT OR IGNORE INTO resumable_families377+ SELECT family.thread_id FROM orchestration_v2_projection_threads family378+ WHERE COALESCE(json_extract(family.payload_json, '$.lineage.rootThreadId'), family.thread_id) IN (379+ SELECT COALESCE(json_extract(payload_json, '$.lineage.rootThreadId'), thread_id)380+ FROM orchestration_v2_projection_threads WHERE thread_id IN ${sql.in(resumable)})`;381+ yield* sql.withTransaction(382+ Effect.gen(function* () {383+ for (const { name } of yield* sql<{ name: string }>`384+ SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c385+ WHERE m.type = 'table' AND c.name = 'thread_id'`) {386+ yield* sql`DELETE FROM ${sql(name)}387+ WHERE thread_id IN (SELECT thread_id FROM resumable_families)`;@@ -641,6 +714,17 @@641714 Flag.optional,642715 Flag.withDescription("Source database. Defaults to ~/.t3/userdata/statev2.sqlite."),643716 ),717+ dropResumable: Flag.String("drop-resumable").pipe(718+ Flag.optional,719+ Flag.withDescription(720+ "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.",721+ ),722+ ),644723 },645- ({ projects, threadsPerProject, baseDir, source }) =>724+ ({ projects, threadsPerProject, baseDir, source, dropResumable }) =>646725 Effect.gen(function* () {726+ if (Option.isSome(dropResumable)) {727+ const path = yield* Path.Path;728+ const target = path.resolve(dropResumable.value);729+ const live = path.resolve(path.join(NodeOS.homedir(), ".t3", "userdata", "statev2.sqlite"));730+ if (target === live) return yield* new MigrateDevDbSharedHomeError();@@ -641,6 +714,18 @@641714 Flag.optional,642715 Flag.withDescription("Source database. Defaults to ~/.t3/userdata/statev2.sqlite."),643716 ),717+ dropResumable: Flag.String("drop-resumable").pipe(718+ Flag.optional,719+ Flag.withDescription(720+ "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.",721+ ),722+ ),644723 },645- ({ projects, threadsPerProject, baseDir, source }) =>724+ ({ projects, threadsPerProject, baseDir, source, dropResumable }) =>646725 Effect.gen(function* () {726+ if (Option.isSome(dropResumable)) {727+ const path = yield* Path.Path;728+ const target = path.resolve(dropResumable.value);729+ const live = path.resolve(path.join(NodeOS.homedir(), ".t3", "userdata", "statev2.sqlite"));730+ if (target === live) return yield* new MigrateDevDbSharedHomeError();731+ const dropped = yield* dropResumableFamilies(target);@@ -458,0 +544,21 @@544+ const columns: Array<{ table: string; column: string }> = [];545+ for (const { name } of yield* sql<{ name: string; virtual: number }>`546+ SELECT name FROM sqlite_master WHERE type = 'table' AND sql NOT LIKE 'CREATE VIRTUAL%'`) {547+ if (TRANSCRIPT_TABLES.has(name) || name.startsWith("sqlite_") || name.includes("search")) {548+ continue;549+ }550+ for (const column of yield* sql<{ name: string; type: string }>`551+ SELECT name, type FROM pragma_table_info(${name})`) {552+ if (/^(TEXT|)$/i.test(column.type) && !TRANSCRIPT_COLUMNS.has(column.name)) {553+ columns.push({ table: name, column: column.name });554+ }555+ }556+ }557+ // Every occurrence, mid-string too: a prompt or preview inside state JSON can name a path.558+ // Longer prefixes first, so a project root is not cut by the home prefix inside it.559+ const longestFirst = real.toSorted((a, b) => b.length - a.length);560+ for (const { table, column } of columns) {561+ for (const [index, prefix] of longestFirst.entries()) {562+ const moved = prefix.endsWith("/") ? `${gone}/` : `${gone}/root-${index}`;563+ yield* sql`UPDATE ${sql(table)} SET ${sql(column)} = replace(${sql(column)}, ${prefix}, ${moved})564+ WHERE instr(${sql(column)}, ${prefix}) > 0`;
Pushed7109669
- @@ -344,0 +372,21 @@372+) {373+ const fs = yield* FileSystem.FileSystem;374+ const path = yield* Path.Path;375+ const platform = yield* HostProcess.Platform;376+ // A symlink, `..` or another letter case can name the live database; compare where they lead.377+ const canonical = (file: string) =>378+ fs.realPath(file).pipe(379+ Effect.catch(() =>380+ fs381+ .realPath(path.dirname(file))382+ .pipe(Effect.map((dir) => path.join(dir, path.basename(file)))),383+ ),384+ Effect.orElseSucceed(() => path.resolve(file)),385+ Effect.map((resolved) => (platform === "linux" ? resolved : resolved.toLowerCase())),386+ );387+ const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));388+ const [target, live] = yield* Effect.all([389+ canonical(databasePath),390+ canonical(path.join(sharedHome, "userdata", "statev2.sqlite")),391+ ]);392+ if (target === live) return yield* new MigrateDevDbSharedHomeError();@@ -344,0 +373,21 @@373+ const fs = yield* FileSystem.FileSystem;374+ const path = yield* Path.Path;375+ const platform = yield* HostProcess.Platform;376+ // A symlink, `..` or another letter case can name the live database; compare where they lead.377+ const canonical = (file: string) =>378+ fs.realPath(file).pipe(379+ Effect.catch(() =>380+ fs381+ .realPath(path.dirname(file))382+ .pipe(Effect.map((dir) => path.join(dir, path.basename(file)))),383+ ),384+ Effect.orElseSucceed(() => path.resolve(file)),385+ Effect.map((resolved) => (platform === "linux" ? resolved : resolved.toLowerCase())),386+ );387+ const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));388+ const [target, live] = yield* Effect.all([389+ canonical(databasePath),390+ canonical(path.join(sharedHome, "userdata", "statev2.sqlite")),391+ ]);392+ if (target === live) return yield* new MigrateDevDbSharedHomeError();393+ yield* ensureNotInUse(databasePath);@@ -374,3 +392,8 @@374392 .slice(0, 25)375393 .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) }));376394 }395+396+const spellings: ReadonlyArray<(path: string) => string> = [397+ (path) => path,398+ // JSON stores each backslash of a Windows path doubled.399+ (path) => path.replaceAll("\\", "\\\\"),
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review.
Walkthrough
The migration script can identify and remove resumable thread families. The metrics harness uses sanitized database seeds for an opt-in busy scenario that measures server readiness, idle behavior, shell requests, and Git-backed turns.
Changes: Busy Metrics and Resumable Database Cleanup
apps/server/scripts/migrate-dev-db.ts,apps/server/scripts/migrate-dev-db.test.tsscripts/server-metrics.ts,scripts/server-metrics-report.ts,scripts/server-metrics.test.tsscripts/server-metrics.ts,scripts/server-metrics-report.ts,scripts/server-metrics.test.tsEstimated code review effort: 4 (Complex) | ~45 minutes
Change: Feature
Sequence Diagram(s)#
Possibly related PRs
Suggested reviewers:
macroscopeappMerge Risk:
Minimal · previous review
a74f1This adds an opt-in benchmark scenario and an in-place cleanup option on the dev migration tool. The cleanup refuses targets that resolve to the shared developer database through symlinks or hard links. The seeded copy rewrites real project paths, and the scenario fails if resumable work remains or if Git-traffic turns fail. No merge-blocking risk remains. Only rare edge cases, such as control characters in project paths, are left as optional follow-ups.
Pre-merge checks:
4
Full details: Title check
Explanation
The title "feat(scripts): server metrics measure a busy server on a copy of real data" matches the main change. The PR adds an opt-in busy scenario to the server metrics harness that seeds from a copy of real developer data. It is a conventional commit title in plain language, and it does not list files or use vague terms.
Full details: Description check
Explanation
The description follows the repository template. It has Problem, Change, Scope, and Verification sections, each filled with specific content. The Problem section gives the expected behavior and the reason for the change. The Change section covers seeding, path sanitizing, resumable-work removal, measurements, and ballast. The Scope section links related PRs and states why no issue is needed. The Verification section reports the commands run, the observed results, and the items not checked. The template asks for a model and harness line at the end, and the author provides one. The description also contains a large amount of benchmark data, which some reviewers may find heavy, but all required sections are complete.
Finishing Touches
Generate unit tests (beta)
9e0e83dc-79da-4f84-88b6-ce29789736e3Reviewing files that changed from the base of the PR and between 7109669eadce73af498e24e6913995b30440b410 and a74f120eaa97c2695822ca719a591658356782cc.
apps/server/scripts/migrate-dev-db.test.tsapps/server/scripts/migrate-dev-db.tsscripts/server-metrics-report.tsscripts/server-metrics.test.tsIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.