TypeScript
feat(dev): add startup profiling for cold-start diagnosis (#28566)
Yash Singh0bc95fcdea91
diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.tsindex 936c79943fd..a6dfe16f066 100644--- a/apps/server/src/bin.ts+++ b/apps/server/src/bin.ts@@ -40,7 +40,11 @@ if (// Windows desktop launches without stdin; attach before reading, except on fast paths using pipes.const { attachConsoleStdin } = await import("./cli/consoleStdin.ts");attachConsoleStdin();+ const importStart = performance.now();const { runCli } = await import("./binCli.ts");+ if (process.env.T3CODE_STARTUP_PROFILE_DIR) {+ performance.measure("server.import.binCli", { start: importStart });+ }runCli();}}diff --git a/apps/server/src/persistence/Sqlite.ts b/apps/server/src/persistence/Sqlite.tsindex 2f21ea0a8a9..9b95422c4f5 100644--- a/apps/server/src/persistence/Sqlite.ts+++ b/apps/server/src/persistence/Sqlite.ts@@ -41,7 +41,7 @@ const layerSetup = Layer.effectDiscard(yield* sql`DELETE FROM sqlite_stat1;`;yield* sql`ANALYZE sqlite_schema;`;}- }),+ }).pipe(Effect.withSpan("Sqlite.setup")),);export const layerFromPath = Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) {diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.tsindex ba647514ece..ca899d4ef04 100644--- a/apps/server/src/ws.test.ts+++ b/apps/server/src/ws.test.ts@@ -21,6 +21,7 @@ import {import * as Deferred from "effect/Deferred";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as PubSub from "effect/PubSub";import * as Queue from "effect/Queue";@@ -127,7 +128,7 @@ import {subscribeOrchestrationV2Shell,subscribeOrchestrationV2Thread,WS_RPC_SERVER_OPTIONS,- withLateEditorConfig,+ withLateConfigDiscovery,} from "./ws.ts";const snapshotConfig = (fields: Partial<ServerConfig>) =>@@ -142,7 +143,7 @@ const settingsUpdated = (settings: object): ServerConfigStreamEvent => ({it.effect("resends late editors without rolling back updates already sent", () =>Effect.gen(function* () {const settingsSent = yield* Deferred.make<void>();- const events = yield* withLateEditorConfig(+ const events = yield* withLateConfigDiscovery(snapshotConfig({ settings: { enableProviderUpdateChecks: true } as never }),Stream.make(settingsUpdated({ enableProviderUpdateChecks: false })),{@@ -150,6 +151,7 @@ it.effect("resends late editors without rolling back updates already sent", () =resolveFileManagerRevealKind: () =>Deferred.await(settingsSent).pipe(Effect.as("file-explorer" as const)),},+ { resolveTargets: () => Effect.succeed([]) },).pipe(Stream.tap((event) =>event.type === "settingsUpdated" ? Deferred.succeed(settingsSent, undefined) : Effect.void,@@ -169,24 +171,35 @@ it.effect("resends late editors without rolling back updates already sent", () =}),);-it.effect("resends a file manager reveal kind that missed the snapshot", () =>+it.effect("resends a reveal kind and remote targets that outlast the snapshot timeout", () =>Effect.gen(function* () {- const events = yield* withLateEditorConfig(+ const targets = [{ kind: "mdns" as const, host: "test.local" }];+ const finishDiscovery = yield* Deferred.make<typeof targets>();+ const collecting = yield* withLateConfigDiscovery(snapshotConfig({ availableEditors: ["file-manager"] }),Stream.empty,{resolveAvailableEditors: () => Effect.succeed(["file-manager"]),resolveFileManagerRevealKind: () => Effect.succeed("file-explorer"),},- ).pipe(Stream.runCollect);+ { resolveTargets: () => Deferred.await(finishDiscovery) },+ ).pipe(Stream.runCollect, Effect.forkScoped({ startImmediately: true }));+ yield* TestClock.adjust("6 seconds");+ yield* Deferred.succeed(finishDiscovery, targets);+ const events = yield* Fiber.join(collecting);- const [late] = Array.from(events);- assert.equal(events.length, 1);+ const [late, remote] = Array.from(events);+ assert.equal(events.length, 2);assert.equal(late?.type, "snapshot");if (late?.type === "snapshot") {assert.equal(late.config.shellRevealInFileManagerKind, "file-explorer");}- }),+ assert.equal(remote?.type, "snapshot");+ if (remote?.type === "snapshot") {+ assert.deepEqual(remote.config.remoteOpenTargets, targets);+ assert.equal(remote.config.shellRevealInFileManagerKind, "file-explorer");+ }+ }).pipe(Effect.scoped),);it.effect("runs editor, remote open target and direct endpoint discovery side by side", () =>@@ -600,9 +613,9 @@ const layerConfigSources = Layer.mergeAll(Layer.provideMerge(NodeServices.layer),);-it.effect(- "preserves settings during discovery and keybindings during snapshot ACK at the config RPC boundary",- () =>+it.effect.each(["pending", "cached"] as const)(+ "%s remote discovery preserves initial config and updates through discovery and ACK",+ (discovery) =>Effect.gen(function* () {const keybindings = yield* Keybindings.Keybindings;const settings = yield* ServerSettings.ServerSettingsService;@@ -617,6 +630,9 @@ it.effect(const initialKeybindings = (yield* keybindings.getSnapshot).keybindings;const discoveryStarted = yield* Deferred.make<void>();const finishDiscovery = yield* Deferred.make<void>();+ const remoteDiscoveryStarted = yield* Deferred.make<void>();+ const finishRemoteDiscovery = yield* Deferred.make<void>();+ const targets = [{ kind: "mdns" as const, host: "test.local" }];const responses = yield* Queue.unbounded<ServerConfigStreamEvent>();const configRpcServices = Layer.mergeAll(layerUnusedConfigRpcServices,@@ -635,7 +651,13 @@ it.effect(}),Layer.mock(UsageLimitSources.UsageLimitSources)({ streamChanges: Stream.make([]) }),Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({- resolveTargets: () => Effect.succeed([]),+ resolveTargets: () =>+ Deferred.succeed(remoteDiscoveryStarted, undefined).pipe(+ Effect.andThen(+ discovery === "cached" ? Effect.void : Deferred.await(finishRemoteDiscovery),+ ),+ Effect.as(targets),+ ),}),Layer.mock(DirectEndpoints.DirectEndpoints)({ resolve: () => Effect.succeed([]) }),Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({@@ -710,12 +732,14 @@ it.effect(headers: Headers.empty,});yield* Deferred.await(discoveryStarted);+ assert.isTrue(yield* Deferred.isDone(remoteDiscoveryStarted));const duringDiscovery = yield* settings.updateSettings({ defaultAutoPull: true });yield* Deferred.succeed(finishDiscovery, undefined);const snapshot = yield* Queue.take(responses);assert.equal(snapshot.type, "snapshot");if (snapshot.type !== "snapshot") return yield* Effect.die("Missing initial snapshot");+ assert.deepEqual(snapshot.config.remoteOpenTargets, discovery === "cached" ? targets : []);assert.isFalse(snapshot.config.settings.defaultAutoPull);assert.deepEqual(snapshot.config.keybindings, initialKeybindings);const duringAck = yield* keybindings.upsertKeybindingRule({@@ -752,6 +776,20 @@ it.effect(}assert.isEmpty(expectedSettings);assert.isEmpty(expectedKeybindings);+ if (discovery === "pending") {+ yield* Deferred.await(remoteDiscoveryStarted);+ yield* Deferred.succeed(finishRemoteDiscovery, undefined);+ const resolved = yield* Queue.take(responses);+ assert.equal(resolved.type, "snapshot");+ if (resolved.type !== "snapshot") return yield* Effect.die("Missing remote targets");+ assert.deepEqual(resolved.config.remoteOpenTargets, targets);+ assert.deepEqual(+ resolved.config.settings,+ ServerSettings.redactServerSettingsForClient(latestSettings),+ );+ assert.deepEqual(resolved.config.keybindings, latestKeybindings);+ yield* acknowledge;+ }yield* server.write(0, { _tag: "Interrupt", requestId, interruptors: [] });}).pipe(Effect.provide(diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 8373bbfae0c..abc7c71f4b8 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -9,6 +9,7 @@ import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Base64 from "effect/encoding/Base64";import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -313,10 +314,11 @@ const resolveEditorConfig = Effect.fn("ws.resolveEditorConfig")(function* <E, R>};});-export const withLateEditorConfig = <E, R>(+export const withLateConfigDiscovery = <E, R>(config: ClientServerConfig,liveUpdates: Stream.Stream<ServerConfigStreamEvent, E, R>,launcher: EditorDiscovery,+ remoteOpenTargets: RemoteOpenTargets.RemoteOpenTargets["Service"],) => {const lateEditorConfig = Stream.fromEffect(launcher.resolveAvailableEditors()).pipe(Stream.filter(@@ -337,7 +339,14 @@ export const withLateEditorConfig = <E, R>(Stream.map((editorConfig) => ({ type: "editorsResolved" as const, editorConfig })),);- return Stream.merge(liveUpdates, lateEditorConfig).pipe(+ const lateRemoteOpenTargets = Stream.fromEffect(remoteOpenTargets.resolveTargets()).pipe(+ Stream.filter(+ (targets) => JSON.stringify(targets) !== JSON.stringify(config.remoteOpenTargets ?? []),+ ),+ Stream.map((targets) => ({ type: "remoteOpenTargetsResolved" as const, targets })),+ );++ return Stream.merge(liveUpdates, Stream.merge(lateEditorConfig, lateRemoteOpenTargets)).pipe(Stream.mapAccum((): ClientServerConfig => config,(current, event): readonly [ClientServerConfig, ReadonlyArray<ServerConfigStreamEvent>] => {@@ -352,6 +361,10 @@ export const withLateEditorConfig = <E, R>(const next = { ...rest, ...event.editorConfig };return [next, [{ version: 1, type: "snapshot", config: next }]];}+ case "remoteOpenTargetsResolved": {+ const next = { ...current, remoteOpenTargets: event.targets };+ return [next, [{ version: 1, type: "snapshot", config: next }]];+ }case "keybindingsUpdated":return [{ ...current, ...event.payload }, [event]];case "providerStatuses":@@ -1754,6 +1767,7 @@ export const layerWsRpc = (const loadServerConfig = Effect.fn("ws.loadServerConfig")(function* (options: {readonly usageLimitsCommand: boolean;readonly workspaceSnapshotsOnDemand: boolean;+ readonly deferRemoteOpenTargets: boolean;}) {const keybindingsConfig = yield* keybindings.loadConfigState;const currentProviders = yield* providerRegistry.getProviders;@@ -1773,7 +1787,9 @@ export const layerWsRpc = (const discovery = yield* resolveOpenDiscoveryForConfig({editors: externalLauncher.resolveAvailableEditors(),fileManagerRevealKind: externalLauncher.resolveFileManagerRevealKind(),- remoteOpenTargets: remoteOpenTargets.resolveTargets(),+ remoteOpenTargets: options.deferRemoteOpenTargets+ ? Effect.succeed([])+ : remoteOpenTargets.resolveTargets(),directEndpoints: directEndpoints.resolve(),});@@ -2203,7 +2219,11 @@ export const layerWsRpc = (),[WS_METHODS.serverProbe]: (_input) => Effect.succeed({}),[WS_METHODS.serverGetConfig]: (_input) =>- loadServerConfig({ usageLimitsCommand: false, workspaceSnapshotsOnDemand: false }),+ loadServerConfig({+ usageLimitsCommand: false,+ workspaceSnapshotsOnDemand: false,+ deferRemoteOpenTargets: false,+ }),[WS_METHODS.serverSearchAcpRegistry]: (input) =>acpRegistryCatalog.search(input)@@ -3126,9 +3146,13 @@ export const layerWsRpc = (// Buffer changes through discovery and the initial snapshot's RPC ACK wait.const keybindingsChanges = yield* keybindings.subscribeChanges;const settingsChanges = yield* serverSettings.subscribeChanges;+ const remoteTargets = yield* Effect.forkScoped(remoteOpenTargets.resolveTargets(), {+ startImmediately: true,+ });const config = yield* loadServerConfig({usageLimitsCommand,workspaceSnapshotsOnDemand,+ deferRemoteOpenTargets: true,});const keybindingsUpdates = keybindingsChanges.pipe(Stream.map((event) => ({@@ -3215,9 +3239,18 @@ export const layerWsRpc = (),);+ const remoteResult = yield* Effect.sync(() => remoteTargets.pollUnsafe());+ const initialConfig =+ remoteResult?._tag === "Success"+ ? { ...config, remoteOpenTargets: remoteResult.value }+ : config;return Stream.concat(- rpcInitialItems([{ version: 1 as const, type: "snapshot" as const, config }]),- withLateEditorConfig(config, liveUpdates, externalLauncher),+ rpcInitialItems([+ { version: 1 as const, type: "snapshot" as const, config: initialConfig },+ ]),+ withLateConfigDiscovery(initialConfig, liveUpdates, externalLauncher, {+ resolveTargets: () => Fiber.join(remoteTargets),+ }),);}),),diff --git a/apps/web/scripts/warm-dep-cache.ts b/apps/web/scripts/warm-dep-cache.tsindex 1b3bbee0346..8607371535e 100644--- a/apps/web/scripts/warm-dep-cache.ts+++ b/apps/web/scripts/warm-dep-cache.ts@@ -10,6 +10,14 @@ import { optimizeDeps, resolveConfig } from "vite";const webRoot = NodePath.dirname(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)));+const configStart = performance.now();const config = await resolveConfig({ root: webRoot, logLevel: "error" }, "serve");+if (process.env.T3CODE_STARTUP_PROFILE_DIR) {+ performance.measure("web.warmDepCache.resolveConfig", { start: configStart });+}+const optimizeStart = performance.now();await optimizeDeps(config);+if (process.env.T3CODE_STARTUP_PROFILE_DIR) {+ performance.measure("web.warmDepCache.optimizeDeps", { start: optimizeStart });+}console.log("[warm-dep-cache] web dependency cache is warm");diff --git a/docs/operations/development.md b/docs/operations/development.mdindex 3a56a23f63d..df4affcad2a 100644--- a/docs/operations/development.md+++ b/docs/operations/development.md@@ -86,6 +86,34 @@ To add a scenario, point a `SCENARIOS` entry at a generic ACP replay fixtureThe agent replays session updates, permission requests, and questions. It drops session setupand vendor frames, so Grok and fx recordings lose their vendor-only behavior.+### Profiling dev startup++Run `vp run profile:startup` to capture the first 20 seconds of inherited Node processes under+`.t3/startup-profiles/<timestamp>`. Workers that execute the preload get separate profiles.+It starts the normal dev runner and accepts its flags.+Stop it with Ctrl+C after the capture. Set `T3CODE_STARTUP_PROFILE_DIR` to choose another output+directory. Profiling adds overhead, so compare readiness with an ordinary `vp run dev` run.++Open a `.cpuprofile` in Chrome DevTools' Performance panel for sampled function stacks and source+lines. Each `.modules.json` is a Chrome trace containing timed module resolution, loading,+synchronous subprocess calls, and startup measures. Per-file records include importer URLs,+source loading, preparation, recursive dependency linking, and top-level evaluation. Preparation+uses synchronous loader boundaries; linking includes dependencies, and CommonJS evaluation can+include nested `require` calls. Some ESM/CommonJS interop reports a combined stage. `.process.json` records the process, Node version, and capture window.+The server's nested Effect and SQL spans remain in `.t3/userdata/logs/server.trace.ndjson`.++The preload temporarily adds module-body timing markers and uses one automatic debugger pause+to instrument the live Node loader. The launcher adds `--no-node-snapshot` to inherited+`NODE_OPTIONS` because Node 26's snapshotted loader cannot accept that breakpoint. Include the+same flag when using the preload directly. This disables Node's built-in startup snapshot,+can change compilation-cache hits, and adds overhead.+Treat per-file captures as diagnostic runs; use uninstrumented runs for baseline startup latency.+The first entry module can compile before loader instrumentation is installed.++A fresh process still uses filesystem, Node compilation, provider, and Vite dependency caches.+Measure a missing Vite dependency cache separately from a restart with an existing database.+Neither the Vite ready message nor the HTTP listener proves that a browser has rendered the app.+### Sharing and remote debugging`vp run dev --share` publishes the web port over the machine's tailnet and prints a pairing URLdiff --git a/package.json b/package.jsonindex c78b879301b..b2912d680c8 100644--- a/package.json+++ b/package.json@@ -5,6 +5,7 @@"scripts": {"prepare": "vp config --no-agent","dev": "node scripts/dev-runner.ts dev",+ "profile:startup": "node scripts/profile-startup.mjs","dev:share": "node scripts/dev-runner.ts dev --share","dev:server": "node scripts/dev-runner.ts dev:server","dev:web": "node scripts/dev-runner.ts dev:web",diff --git a/packages/provider-cursor/src/server/sdk.ts b/packages/provider-cursor/src/server/sdk.tsindex a8a10e365b3..9443bf735a0 100644--- a/packages/provider-cursor/src/server/sdk.ts+++ b/packages/provider-cursor/src/server/sdk.ts@@ -3,6 +3,7 @@ import * as NodeModule from "node:module";// createRequire loads the disk-backed SDK and adjacent chunks even from a Node SEA executable.const requireCursorSdk = NodeModule.createRequire(import.meta.url);+const sdkImportStart = performance.now();export const {Agent,AuthenticationError,@@ -12,6 +13,13 @@ export const {CursorSdkError,InMemoryCredentialStore,} = requireCursorSdk("@cursor/sdk") as typeof import("@cursor/sdk");+if (process.env.T3CODE_STARTUP_PROFILE_DIR) {+ performance.measure("provider.cursor.importSdk", { start: sdkImportStart });+}+const sqliteImportStart = performance.now();export const { SqliteLocalAgentStore } = requireCursorSdk("@cursor/sdk/sqlite",) as typeof import("@cursor/sdk/sqlite");+if (process.env.T3CODE_STARTUP_PROFILE_DIR) {+ performance.measure("provider.cursor.importSqliteStore", { start: sqliteImportStart });+}diff --git a/scripts/profile-startup-modules.mjs b/scripts/profile-startup-modules.mjsnew file mode 100644index 00000000000..2db139a92ac--- /dev/null+++ b/scripts/profile-startup-modules.mjs@@ -0,0 +1,262 @@+import * as NodeFS from "node:fs";+import * as NodeModule from "node:module";+import * as NodePerfHooks from "node:perf_hooks";+import * as NodeURL from "node:url";++export function profileStartupModules(session, events, threadId) {+ const now = () => NodePerfHooks.performance.now();+ const origin = NodePerfHooks.performance.timeOrigin;+ const loaded = new Map();+ const compiling = new Map();+ const evaluating = new Map();+ const registryKey = "__t3codeStartupModuleProfiler";+ const previousRegistry = globalThis[registryKey];+ const previousModuleRegistry = NodeModule.default[registryKey];+ const restorers = [];+ let active = true;+ let installed = false;+ let breakpoint;+ let currentLink;+ let nextLink = 0;++ const record = (stage, url, start, end, attributes = {}) => {+ if (!active) return;+ events.push({+ name: `${stage} ${url}`,+ cat: "module.detail",+ ph: "X",+ pid: process.pid,+ tid: threadId,+ ts: (origin + start) * 1000,+ dur: (end - start) * 1000,+ args: { stage, url, ...attributes },+ });+ };+ const toUrl = (file) =>+ file instanceof URL+ ? file.href+ : typeof file === "string"+ ? file.startsWith("file:")+ ? file+ : NodeURL.pathToFileURL(file).href+ : undefined;+ const inject = (source, statement, preserveDirectives) => {+ let offset = source.startsWith("#!") ? source.indexOf("\n") + 1 : 0;+ if (preserveDirectives) {+ for (;;) {+ const trivia = /^(?:\s+|\/\/[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*/.exec(+ source.slice(offset),+ )[0];+ offset += trivia.length;+ if (!/^["']/.test(source.slice(offset))) break;+ const directive = /^(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*;/.exec(+ source.slice(offset),+ );+ // Leave ambiguous semicolon-free prologues untouched rather than changing strict-mode semantics.+ if (!directive) return undefined;+ offset += directive[0].length;+ }+ }+ return source.slice(0, offset) + statement + source.slice(offset);+ };+ const registry = {+ begin(url) {+ if (active) evaluating.set(url, now());+ },+ end(url) {+ const start = evaluating.get(url);+ if (start === undefined) return;+ record("evaluate", url, start, now(), {+ format: "esm",+ boundary: "module body; top-level await included",+ });+ evaluating.delete(url);+ },+ cjsBegin(filename) {+ const url = toUrl(filename),+ pending = compiling.get(url);+ if (!pending) return;+ pending.evaluationStart = now();+ record("prepare", url, pending.start, pending.evaluationStart, {+ format: "commonjs",+ boundary: "_compile entry to module-body entry",+ });+ },+ install(job) {+ if (installed) return;+ installed = true;+ const loader = Object.getPrototypeOf(job.loader);+ for (const method of [+ "loadAndTranslate",+ "loadAndTranslateForRequireInImportedCJS",+ "loadAndTranslateForImportInRequiredESM",+ ]) {+ const original = loader[method];+ if (typeof original !== "function") continue;+ loader[method] = function (url, ...args) {+ const start = now();+ try {+ return original.call(this, url, ...args);+ } finally {+ const moduleUrl = typeof url === "string" ? url : url.url;+ const pending = loaded.get(moduleUrl);+ if (pending && pending.start >= start)+ record("prepare", moduleUrl, pending.start, now(), {+ format: pending.format,+ boundary:+ "source-ready to loadAndTranslate return; compilation and format preparation",+ });+ }+ };+ restorers.push(() => {+ loader[method] = original;+ });+ }+ const prototype = Object.getPrototypeOf(Object.getPrototypeOf(job)),+ link = prototype.syncLink;+ prototype.syncLink = function (...args) {+ const start = now(),+ parent = currentLink,+ id = ++nextLink;+ currentLink = { id, url: this.url };+ try {+ return link.apply(this, args);+ } finally {+ record("link", this.url, start, now(), {+ id,+ parentId: parent?.id,+ importedBy: parent?.url,+ boundary: "ModuleJob.syncLink; includes recursive dependency loading",+ });+ currentLink = parent;+ }+ };+ restorers.push(() => {+ prototype.syncLink = link;+ });+ },+ };+ globalThis[registryKey] = registry;+ NodeModule.default[registryKey] = registry;++ session.post("Debugger.enable");+ // One pause obtains the live loader; subsequent measurements use synchronous method boundaries.+ const source = process.binding("natives")["internal/modules/esm/module_job"].split("\n");+ const classLine = source.findIndex((line) => line.includes("class ModuleJob extends"));+ const lineNumber = source.findIndex(+ (line, index) => index > classLine && line.includes("this.linked = this.link("),+ );+ const paused = ({ params }) => {+ if (!breakpoint || !params.hitBreakpoints?.includes(breakpoint)) return;+ const start = now();+ session.post("Debugger.removeBreakpoint", { breakpointId: breakpoint });+ breakpoint = undefined;+ session.post(+ "Debugger.evaluateOnCallFrame",+ {+ callFrameId: params.callFrames[0].callFrameId,+ expression: `globalThis.${registryKey}.install(this)`,+ silent: true,+ },+ (error, result) => {+ if (error || result?.exceptionDetails)+ record("instrumentation-error", "node:esm-loader", start, now());+ },+ );+ record("instrumentation-setup", "node:esm-loader", start, now());+ session.post("Debugger.resume");+ };+ session.on("Debugger.paused", paused);+ if (lineNumber >= 0)+ session.post(+ "Debugger.setBreakpointByUrl",+ {+ url: "node:internal/modules/esm/module_job",+ lineNumber,+ },+ (error, result) => {+ if (!error) breakpoint = result.breakpointId;+ },+ );++ const readFileSync = NodeFS.default.readFileSync;+ NodeFS.default.readFileSync = function (file, ...args) {+ const url = toUrl(file);+ if (!url || !/\.[cm]?[jt]sx?(?:$|\?)/.test(url)) return readFileSync.call(this, file, ...args);+ const start = now();+ try {+ return readFileSync.call(this, file, ...args);+ } finally {+ record("read", url, start, now());+ }+ };+ const compile = NodeModule.default.prototype._compile;+ NodeModule.default.prototype._compile = function (source, filename, ...args) {+ const url = toUrl(filename),+ pending = { start: now() };+ const format = args[0] ?? loaded.get(url)?.format;+ const isEsm =+ format === "module" ||+ format === "module-typescript" ||+ /(^|[;\n])\s*(?:import[\s.]|export\s)/.test(source);+ const annotated = isEsm+ ? undefined+ : inject(source, `module.constructor.${registryKey}?.cjsBegin(__filename);`, true);+ compiling.set(url, pending);+ try {+ return compile.call(this, annotated ?? source, filename, ...args);+ } finally {+ const end = now();+ record(isEsm ? "require-esm" : "commonjs", url, pending.start, end, {+ importedBy: this.parent?.filename ? toUrl(this.parent.filename) : undefined,+ sourceBytes: Buffer.byteLength(source),+ });+ if (pending.evaluationStart !== undefined)+ record("evaluate", url, pending.evaluationStart, end, {+ format: "commonjs",+ includesNestedRequires: true,+ });+ compiling.delete(url);+ }+ };+ NodeModule.syncBuiltinESMExports();++ return {+ sourceReady(url, result) {+ if (!url.startsWith("file:")) return result;+ const format = result.format;+ let source = result.source;+ if (typeof source !== "string" && ArrayBuffer.isView(source))+ source = Buffer.from(source.buffer, source.byteOffset, source.byteLength).toString("utf8");+ if (typeof source === "string" && (format === "module" || format === "module-typescript")) {+ // A module-local globalThis binding would put the injected access in its temporal dead zone.+ if (!/\b(?:const|let|var|class|function|as)\s+globalThis\b/.test(source)) {+ source =+ inject(source, `globalThis.${registryKey}?.begin(import.meta.url);`, false) ++ `\n;globalThis.${registryKey}?.end(import.meta.url);\n`;+ result = { ...result, source };+ }+ }+ loaded.set(url, { start: now(), format });+ return result;+ },+ finish() {+ const end = now();+ for (const [url, start] of evaluating)+ record("evaluate", url, start, end, { incomplete: true });+ record("instrumentation-status", "node:esm-loader", end, end, { installed });+ active = false;+ if (breakpoint) session.post("Debugger.removeBreakpoint", { breakpointId: breakpoint });+ session.off("Debugger.paused", paused);+ session.post("Debugger.disable");+ for (const restore of restorers.reverse()) restore();+ NodeFS.default.readFileSync = readFileSync;+ NodeModule.default.prototype._compile = compile;+ NodeModule.syncBuiltinESMExports();+ if (previousRegistry === undefined) delete globalThis[registryKey];+ else globalThis[registryKey] = previousRegistry;+ if (previousModuleRegistry === undefined) delete NodeModule.default[registryKey];+ else NodeModule.default[registryKey] = previousModuleRegistry;+ },+ };+}diff --git a/scripts/profile-startup.mjs b/scripts/profile-startup.mjsnew file mode 100644index 00000000000..f14dfc01551--- /dev/null+++ b/scripts/profile-startup.mjs@@ -0,0 +1,165 @@+// Opt in with T3CODE_STARTUP_PROFILE_DIR=/absolute/path NODE_OPTIONS="--no-node-snapshot --import=/absolute/path/to/this/file".+import * as NodeFS from "node:fs";+import * as NodeInspector from "node:inspector";+import * as NodeChildProcess from "node:child_process";+import * as NodeModule from "node:module";+import * as NodePath from "node:path";+import * as NodePerfHooks from "node:perf_hooks";+import * as NodeWorkerThreads from "node:worker_threads";+import * as NodeURL from "node:url";++import { profileStartupModules } from "./profile-startup-modules.mjs";++const directory = process.env.T3CODE_STARTUP_PROFILE_DIR;+const isLauncher = process.argv[1] === NodeURL.fileURLToPath(import.meta.url);+if (directory && !isLauncher) {+ NodeFS.mkdirSync(directory, { recursive: true });+ const { threadId } = NodeWorkerThreads;+ const prefix = NodePath.join(directory, `${process.pid}-${threadId}`);+ const origin = NodePerfHooks.performance.timeOrigin;+ const events = [];+ const session = new NodeInspector.Session();+ session.connect();+ session.post("Profiler.setSamplingInterval", { interval: 1000 });+ session.post("Profiler.enable");+ const profileStartTimeUnixMs = origin + NodePerfHooks.performance.now();+ session.post("Profiler.start");++ const moduleDetails = profileStartupModules(session, events, threadId);++ const measure = (name, operation, cat = "module", attributes = {}) => {+ const start = NodePerfHooks.performance.now();+ try {+ return operation();+ } finally {+ events.push({+ name,+ cat,+ ph: "X",+ pid: process.pid,+ tid: threadId,+ ts: (origin + start) * 1000,+ dur: (NodePerfHooks.performance.now() - start) * 1000,+ args: attributes,+ });+ }+ };++ const recordMeasures = (entries) => {+ for (const entry of entries) {+ events.push({+ name: entry.name,+ cat: "startup",+ ph: "X",+ pid: process.pid,+ tid: threadId,+ ts: (origin + entry.startTime) * 1000,+ dur: entry.duration * 1000,+ });+ }+ };+ const observer = new NodePerfHooks.PerformanceObserver((list) =>+ recordMeasures(list.getEntries()),+ );+ observer.observe({ entryTypes: ["measure"] });+ const execFileSync = NodeChildProcess.default.execFileSync;+ NodeChildProcess.default.execFileSync = function (file, ...args) {+ return measure(+ `execFileSync ${file}`,+ () => execFileSync.call(this, file, ...args),+ "subprocess",+ );+ };+ NodeModule.syncBuiltinESMExports();++ const hooks = NodeModule.registerHooks({+ resolve(specifier, context, next) {+ const attributes = { specifier, parentURL: context.parentURL };+ return measure(+ `resolve ${specifier}`,+ () => {+ const result = next(specifier, context);+ attributes.url = result.url;+ attributes.format = result.format;+ return result;+ },+ "module",+ attributes,+ );+ },+ load(url, context, next) {+ const result = measure(`load ${url}`, () => next(url, context), "module", {+ url,+ format: context.format,+ });+ return moduleDetails.sourceReady(url, result);+ },+ });++ let finished = false;+ const finish = () => {+ if (finished) return;+ finished = true;+ hooks.deregister();+ moduleDetails.finish();+ recordMeasures(observer.takeRecords());+ observer.disconnect();+ NodeChildProcess.default.execFileSync = execFileSync;+ NodeModule.syncBuiltinESMExports();+ session.post("Profiler.stop", (error, result) => {+ if (!error) NodeFS.writeFileSync(`${prefix}.cpuprofile`, JSON.stringify(result.profile));+ session.disconnect();+ });+ NodeFS.writeFileSync(`${prefix}.modules.json`, JSON.stringify({ traceEvents: events }));+ NodeFS.writeFileSync(+ `${prefix}.process.json`,+ JSON.stringify({+ pid: process.pid,+ parentPid: process.ppid,+ threadId,+ nodeVersion: process.version,+ executable: process.execPath,+ entry: process.argv[1],+ timeOrigin: origin,+ profileStartTimeUnixMs,+ captureEnd: origin + NodePerfHooks.performance.now(),+ cpu: process.cpuUsage(),+ memory: process.memoryUsage(),+ }),+ );+ };+ // Bound the capture without keeping dev servers or short-lived helpers alive.+ setTimeout(finish, 20_000).unref();+ process.once("exit", finish);+}++if (isLauncher) {+ const output = NodePath.resolve(+ directory ??+ NodePath.join(".t3/startup-profiles", new Date().toISOString().replaceAll(":", "-")),+ );+ console.log(`[profile-startup] Writing CPU profiles and timeline events to ${output}`);+ const child = NodeChildProcess.spawn(+ process.execPath,+ ["scripts/dev-runner.ts", "dev", ...process.argv.slice(2)],+ {+ stdio: "inherit",+ env: {+ ...process.env,+ T3CODE_STARTUP_PROFILE_DIR: output,+ // Node 26's snapshotted loader cannot accept the debugger breakpoint used by this profiler.+ NODE_OPTIONS:+ `${process.env.NODE_OPTIONS ?? ""} --no-node-snapshot --import=${import.meta.url}`.trim(),+ },+ },+ );+ process.on("SIGINT", () => child.kill("SIGINT"));+ process.on("SIGTERM", () => child.kill("SIGTERM"));+ child.on("error", (error) => {+ console.error(error);+ process.exitCode = 1;+ });+ child.on("exit", (code) => {+ process.exitCode = code ?? 1;+ });+}diff --git a/scripts/profile-startup.test.ts b/scripts/profile-startup.test.tsnew file mode 100644index 00000000000..998843ed1cf--- /dev/null+++ b/scripts/profile-startup.test.ts@@ -0,0 +1,149 @@+// @effect-diagnostics nodeBuiltinImport:off -- Runs the profiling preload in a real Node subprocess.+import * as NodeChildProcess from "node:child_process";+import * as NodeFS from "node:fs";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";+import * as NodeURL from "node:url";+import * as Schema from "effect/Schema";+import { expect, it } from "vite-plus/test";++const decodeTrace = Schema.decodeUnknownSync(+ Schema.fromJsonString(+ Schema.Struct({+ traceEvents: Schema.Array(+ Schema.Struct({+ name: Schema.String,+ ts: Schema.Number,+ dur: Schema.Number,+ args: Schema.optional(+ Schema.Struct({+ stage: Schema.optional(Schema.String),+ url: Schema.optional(Schema.String),+ parentURL: Schema.optional(Schema.String),+ importedBy: Schema.optional(Schema.String),+ installed: Schema.optional(Schema.Boolean),+ }),+ ),+ }),+ ),+ }),+ ),+);++const decodeRunner = Schema.decodeUnknownSync(+ Schema.fromJsonString(Schema.Struct({ pid: Schema.Number, args: Schema.Array(Schema.String) })),+);++it("attributes ESM and CommonJS imports without changing module execution", () => {+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-startup-profile-"));+ try {+ NodeFS.writeFileSync(NodePath.join(directory, "package.json"), '{"type":"module"}');+ const fixtures = {+ "root.mjs": `+ import { value } from './dependency.mjs';+ import strict from './strict.cjs';+ import loose from './loose.cjs';+ import interop from './interop.cjs';+ if (value !== 42 || strict !== undefined || loose !== true || interop !== 9) {+ throw Error('Profiling changed module semantics');+ }+ `,+ "dependency.mjs": "export const value = 42;",+ "strict.cjs": `/* retain the directive */\n"use strict"; module.exports = (function () { return this; })();`,+ "loose.cjs": "module.exports = (function () { return this; })() === globalThis;",+ "interop.cjs": "module.exports = require('./required.js').value;",+ "required.js": "export const value = 9;",+ };+ for (const [name, source] of Object.entries(fixtures)) {+ NodeFS.writeFileSync(NodePath.join(directory, name), source);+ }+ const output = NodePath.join(directory, "capture");+ const root = NodeURL.pathToFileURL(+ NodeFS.realpathSync(NodePath.join(directory, "root.mjs")),+ ).href;+ NodeChildProcess.execFileSync(+ process.execPath,+ [+ "--no-node-snapshot",+ "--import",+ NodeURL.pathToFileURL(NodePath.join(import.meta.dirname, "profile-startup.mjs")).href,+ "--input-type=module",+ "-e",+ `await import(${JSON.stringify(root)})`,+ ],+ { env: { ...process.env, NODE_OPTIONS: "", T3CODE_STARTUP_PROFILE_DIR: output } },+ );+ const spans = NodeFS.readdirSync(output)+ .filter((name) => name.endsWith(".modules.json"))+ .flatMap(+ (name) => decodeTrace(NodeFS.readFileSync(NodePath.join(output, name), "utf8")).traceEvents,+ );+ expect(spans.some((span) => span.args?.installed === true)).toBe(true);+ for (const name of Object.keys(fixtures)) {+ const url = NodeURL.pathToFileURL(NodeFS.realpathSync(NodePath.join(directory, name))).href;+ const stages = spans.filter((span) => span.args?.url === url).map((span) => span.args?.stage);+ expect(stages, name).toEqual(+ expect.arrayContaining(+ name === "required.js" ? ["link", "require-esm"] : ["prepare", "evaluate"],+ ),+ );+ }+ const prepared = spans.find(+ (span) => span.args?.url === root && span.args?.stage === "prepare",+ );+ const linked = spans.find((span) => span.args?.url === root && span.args?.stage === "link");+ if (!prepared || !linked) throw Error("Missing root module preparation/link boundaries");+ expect(prepared.ts + prepared.dur).toBeLessThanOrEqual(linked.ts);+ const dependency = NodeURL.pathToFileURL(+ NodeFS.realpathSync(NodePath.join(directory, "dependency.mjs")),+ ).href;+ expect(+ spans.find((span) => span.args?.url === dependency && span.args?.stage === "link")?.args+ ?.importedBy,+ ).toBe(root);+ } finally {+ NodeFS.rmSync(directory, { recursive: true, force: true });+ }+});++it("captures only the dev runner and preserves its exit status", () => {+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-startup-launcher-"));+ try {+ NodeFS.mkdirSync(NodePath.join(directory, "scripts"));+ NodeFS.writeFileSync(+ NodePath.join(directory, "scripts/dev-runner.ts"),+ "console.log(JSON.stringify({ pid: process.pid, args: process.argv.slice(2) }));",+ );+ const output = NodePath.join(directory, "capture");+ const stdout = NodeChildProcess.execFileSync(+ process.execPath,+ [NodePath.join(import.meta.dirname, "profile-startup.mjs"), "--no-seed"],+ {+ cwd: directory,+ env: { ...process.env, NODE_OPTIONS: "", T3CODE_STARTUP_PROFILE_DIR: output },+ encoding: "utf8",+ },+ );+ const runner = decodeRunner(stdout.trim().split("\n").at(-1));+ expect(runner.args).toEqual(["dev", "--no-seed"]);+ expect(NodeFS.readdirSync(output).sort()).toEqual(+ ["cpuprofile", "modules.json", "process.json"].map((suffix) => `${runner.pid}-0.${suffix}`),+ );+ NodeFS.writeFileSync(+ NodePath.join(directory, "scripts/dev-runner.ts"),+ "process.kill(process.pid, 'SIGTERM');",+ );+ const interrupted = NodeChildProcess.spawnSync(+ process.execPath,+ [NodePath.join(import.meta.dirname, "profile-startup.mjs")],+ {+ cwd: directory,+ env: { ...process.env, NODE_OPTIONS: "", T3CODE_STARTUP_PROFILE_DIR: output },+ },+ );+ expect(interrupted.error).toBeUndefined();+ expect(interrupted.status).toBe(1);+ } finally {+ NodeFS.rmSync(directory, { recursive: true, force: true });+ }+});