Skip to content
TypeScript

perf(scripts): check:changed finishes in about 10 s (#23581)

Theo Browne66ee628e0875
diff --git a/docs/operations/development.md b/docs/operations/development.md
index 5b121258038..c34dc108890 100644
--- a/docs/operations/development.md
+++ b/docs/operations/development.md
@@ -160,6 +160,11 @@ files to packages with [ci-changes.cjs](../../.github/scripts/ci-changes.cjs), a
compares against the merge base with `origin/main`, or with a ref you pass. CI still runs the full
test suites and the jobs the summary lists, so a local pass does not promise a green CI run.
+The steps run side by side, so a run takes about as long as its slowest step, usually knip's
+exports pass at about 10 s. When the files are exactly those of the last passing run, it prints that
+run's summary instead of running again. Any change to a file, the install, or a generated file runs
+the checks again.
+
While you iterate, run single checks:
```sh
diff --git a/knip.jsonc b/knip.jsonc
index babc22932ca..e85064e5091 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -32,7 +32,9 @@
],
"ignoreDependencies": ["esbuild"],
// The `t3` npm package's files: copied into the package, never imported.
- "ignore": ["npm-launcher/**"],
+ // knip-schemas.test.ts writes a throwaway project to .knip-test-*, which a
+ // knip run beside it in check:changed must not report.
+ "ignore": ["npm-launcher/**", ".knip-test-*/**"],
},
"apps/server": {
// Vite+ pack entries and the launcher used by installed background services.
diff --git a/scripts/check-changed.ts b/scripts/check-changed.ts
index 11376b85106..81850389c4d 100644
--- a/scripts/check-changed.ts
+++ b/scripts/check-changed.ts
@@ -10,7 +10,10 @@
//
// Uncommitted and untracked files count. Affected packages come from
// .github/scripts/ci-changes.cjs, the same mapping CI uses to gate its jobs.
+// The steps run side by side; each prints its output when it finishes. A
+// rerun on exactly the files of the last passing run prints that run's summary.
import * as NodeChildProcess from "node:child_process";
+import * as NodeCrypto from "node:crypto";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
@@ -19,8 +22,13 @@ import { decide, readWorkspace } from "../.github/scripts/ci-changes.cjs";
const root = NodePath.resolve(import.meta.dirname, "..");
const CODE = /\.[cm]?[jt]sx?$/;
+// quotePath=false keeps non-ASCII paths as real paths instead of quoted escapes.
const git = (...args: Array<string>) =>
- NodeChildProcess.execFileSync("git", args, { cwd: root, encoding: "utf8" })
+ NodeChildProcess.execFileSync("git", ["-c", "core.quotePath=false", ...args], {
+ cwd: root,
+ encoding: "utf8",
+ maxBuffer: 64 * 1024 * 1024,
+ })
.split("\n")
.filter(Boolean);
@@ -46,6 +54,75 @@ if (files.length === 0) {
console.log(`check:changed: no changes since ${base.slice(0, 12)}.`);
process.exit(0);
}
+console.log(`check:changed: ${files.length} files since ${base.slice(0, 12)}`);
+
+// The checked tree is the merge base plus the diff plus the untracked files.
+// Ignored generated sources, .astro types, generated declarations such as
+// apps/mobile/expo-env.d.ts, env files, and the install state can change results
+// too, so they are part of the key. Other ignored folders (iOS Pods, dist, the
+// Electron runtime) are large and no check reads them.
+// Computed again after a passing run, so edits made during the run are never
+// cached as passing.
+const inputKey = () => {
+ const hash = NodeCrypto.createHash("sha256");
+ // CI changes test behavior (vite.config.ts rejects .only under CI).
+ hash.update(`${process.version}\0${base}\0${process.env.CI ?? ""}\0`);
+ hash.update(
+ NodeChildProcess.execFileSync(
+ "git",
+ ["diff", "--binary", "--no-renames", "--no-ext-diff", "--no-textconv", base, "--"],
+ { cwd: root, maxBuffer: 1024 * 1024 * 1024 },
+ ),
+ );
+ const ignored = git(
+ "ls-files",
+ "--others",
+ "--ignored",
+ "--exclude-standard",
+ "--",
+ ":(glob)**/.generated/**",
+ ":(glob)**/.astro/**",
+ ":(glob)**/*.d.ts",
+ ":(glob)**/.env*",
+ ":(exclude,glob)**/node_modules/**",
+ );
+ for (const file of [
+ // Raw bytes of changed files too: .gitattributes normalizes line endings in
+ // the diff, but the formatter reads the file as it is on disk.
+ ...git("diff", "--name-only", "--no-renames", base, "--"),
+ ...git("ls-files", "--others", "--exclude-standard"),
+ ...ignored,
+ "node_modules/.modules.yaml",
+ "node_modules/.pnpm/lock.yaml",
+ ]) {
+ hash.update(`\0${file}\0`);
+ const path = NodePath.join(root, file);
+ // Untracked nested repositories are listed as directories.
+ if (NodeFS.statSync(path, { throwIfNoEntry: false })?.isFile()) {
+ hash.update(NodeFS.readFileSync(path));
+ }
+ }
+ return hash.digest("hex");
+};
+const key = inputKey();
+const cachePath = NodePath.join(root, "node_modules/.cache/check-changed.json");
+// A missing or unreadable cache is a miss, never a failure.
+const readCache = () => {
+ try {
+ return JSON.parse(NodeFS.readFileSync(cachePath, "utf8")) as {
+ key: string;
+ summary: Array<string>;
+ };
+ } catch {
+ return undefined;
+ }
+};
+const cached = readCache();
+if (cached?.key === key) {
+ console.log("Nothing changed since the last passing run.\n");
+ for (const line of cached.summary) console.log(line);
+ process.exit(0);
+}
const present = files.filter((file) => NodeFS.existsSync(NodePath.join(root, file)));
const code = present.filter((file) => CODE.test(file));
@@ -66,12 +143,24 @@ for (const file of code) {
}
}
-// knip:check takes about 35 s and cannot be scoped to a package. Any code
-// change can leave a file, export, or dependency unused (removing the last
-// import of a helper does), so it runs whenever code or a manifest changes.
+// knip:check cannot be scoped to a package. Any code change can leave a file,
+// export, or dependency unused (removing the last import of a helper does), so
+// it runs whenever code or a manifest changes.
const runKnip = files.some(
(file) => CODE.test(file) || NodePath.basename(file) === "package.json" || file === "knip.jsonc",
);
+// CI runs knip:check as one script of `knip ... && knip ...` passes. The passes
+// do not depend on each other, so they run side by side here.
+const knipCheck: string = JSON.parse(
+ NodeFS.readFileSync(NodePath.join(root, "package.json"), "utf8"),
+).scripts["knip:check"];
+const knipPasses = knipCheck.split(" && ").map((command, index, all) => {
+ const [bin, ...args] = command.trim().split(/\s+/);
+ if (bin !== "knip" || /["'$\\|;&<>]/.test(command)) {
+ throw new Error(`check:changed cannot split knip:check: ${command}`);
+ }
+ return { name: `knip ${index + 1}/${all.length}`, args: ["exec", "knip", ...args] };
+});
// A version bump can strand a patch in pnpm-workspace.yaml: no resolved
// version uses it and pnpm rejects the install with ERR_PNPM_UNUSED_PATCH.
@@ -153,14 +242,24 @@ const steps = [
args: ["fmt", "--check", "--no-error-on-unmatched-pattern", ...present],
},
code.length > 0 && { name: "lint", args: ["lint", ...code] },
- runKnip && { name: "knip", args: ["run", "knip:check"] },
+ ...(runKnip ? knipPasses : []),
...graphql.map((dir) => ({
name: `graphql (${dir})`,
args: ["run", "--filter", `./${dir}`, "generate", "--check"],
})),
affected.length > 0 && {
name: `typecheck (${affected.length} packages)`,
- args: ["run", "--cache", "--concurrency-limit", "4", ...filters(affected), "typecheck"],
+ // `tsc --noEmit` writes nothing another package reads, so dependency order
+ // only made dependents wait: --parallel cut a contracts change from 13 s to 9 s.
+ args: [
+ "run",
+ "--cache",
+ "--parallel",
+ "--concurrency-limit",
+ "4",
+ ...filters(affected),
+ "typecheck",
+ ],
},
// From the repo root, the root vite.config.ts hands each file to its package's config.
tests.size > 0 && {
@@ -169,23 +268,36 @@ const steps = [
},
].filter((step) => step !== false);
-console.log(`check:changed: ${files.length} files since ${base.slice(0, 12)}`);
-const results = steps.map((step) => {
- console.log(`\n> vp ${step.name}`);
- const started = performance.now();
- const status =
- "args" in step
- ? NodeChildProcess.spawnSync("vp", step.args, { cwd: root, stdio: "inherit" }).status
- : step.run()
- ? 0
- : 1;
- const seconds = ((performance.now() - started) / 1000).toFixed(1);
- return { name: step.name, ok: status === 0, seconds };
-});
+// Output is piped, so keep the colors a terminal would get.
+const env = process.stdout.isTTY ? { ...process.env, FORCE_COLOR: "1" } : process.env;
+const results = await Promise.all(
+ steps.map(
+ (step) =>
+ new Promise<{ name: string; ok: boolean; seconds: string }>((resolve) => {
+ const started = performance.now();
+ const finish = (ok: boolean, output?: Buffer) => {
+ const seconds = ((performance.now() - started) / 1000).toFixed(1);
+ console.log(`\n> vp ${step.name} ${ok ? "pass" : "FAIL"} ${seconds}s`);
+ if (output) process.stdout.write(output);
+ resolve({ name: step.name, ok, seconds });
+ };
+ // In-process steps print their own output. The patch check is first and
+ // takes about a second, so the commands start right after it.
+ if ("run" in step) return finish(step.run());
+ const output: Array<Buffer> = [];
+ const child = NodeChildProcess.spawn("vp", step.args, { cwd: root, env });
+ child.stdout.on("data", (chunk: Buffer) => output.push(chunk));
+ child.stderr.on("data", (chunk: Buffer) => output.push(chunk));
+ // A failed spawn emits "error", then "close" with a nonzero code.
+ child.on("error", (error) => output.push(Buffer.from(`${error.message}\n`)));
+ child.on("close", (status) => finish(status === 0, Buffer.concat(output)));
+ }),
+ ),
+);
-console.log("\ncheck:changed summary");
+const summary = ["check:changed summary"];
for (const result of results) {
- console.log(` ${result.ok ? "pass" : "FAIL"} ${result.name} ${result.seconds}s`);
+ summary.push(` ${result.ok ? "pass" : "FAIL"} ${result.name} ${result.seconds}s`);
}
const ciOnly = Object.entries({
"full test suites": outputs.test || outputs.test_web || outputs.test_server,
@@ -194,7 +306,24 @@ const ciOnly = Object.entries({
"mobile native lint": outputs.mobile_native,
"release smoke": outputs.release_smoke,
}).flatMap(([job, runs]) => (runs ? [job] : []));
-if (ciOnly.length > 0) console.log(` CI also runs: ${ciOnly.join(", ")}`);
-if (!runPatchCheck) console.log(" unused patch check skipped: no dependency files changed");
-if (!runKnip) console.log(" knip skipped: no code or manifest changed");
-if (results.some((result) => !result.ok)) process.exit(1);
+if (ciOnly.length > 0) summary.push(` CI also runs: ${ciOnly.join(", ")}`);
+if (!runPatchCheck) summary.push(" unused patch check skipped: no dependency files changed");
+if (!runKnip) summary.push(" knip skipped: no code or manifest changed");
+console.log(`\n${summary.join("\n")}`);
+// exitCode, not exit(): piped stdout is asynchronous on macOS, and exit()
+// would cut off a failing step's output.
+if (results.some((result) => !result.ok)) {
+ process.exitCode = 1;
+} else if (inputKey() !== key) {
+ console.log(" pass not cached: files changed during the run");
+} else {
+ try {
+ // Write then rename, so a concurrent run never reads half a file.
+ const temp = `${cachePath}.${process.pid}`;
+ NodeFS.mkdirSync(NodePath.dirname(cachePath), { recursive: true });
+ NodeFS.writeFileSync(temp, JSON.stringify({ key, summary }));
+ NodeFS.renameSync(temp, cachePath);
+ } catch (error) {
+ console.warn(` pass not cached: ${error instanceof Error ? error.message : String(error)}`);
+ }
+}
diff --git a/scripts/knip-schemas.ts b/scripts/knip-schemas.ts
index 824c43eb31f..314702626c1 100644
--- a/scripts/knip-schemas.ts
+++ b/scripts/knip-schemas.ts
@@ -1,14 +1,117 @@
// @effect-diagnostics nodeBuiltinImport:off - Knip and the TypeScript compiler host use synchronous Node paths.
+import * as NodeOS from "node:os";
import * as NodePath from "node:path";
+import * as NodeWorkerThreads from "node:worker_threads";
import type { Preprocessor } from "knip";
// Knip needs the legacy compiler API, which TypeScript 7 no longer exports.
import ts from "typescript-legacy";
const schemaTypeId = "~effect/Schema/Schema";
-const preprocess: Preprocessor = (options) => {
+// One tsconfig's files, each with the export names its issues mention. Only
+// those names are checked: inferring the type of every export cost seconds.
+interface Project {
+ readonly cwd: string;
+ readonly configPath: string | undefined;
+ readonly files: ReadonlyArray<readonly [string, ReadonlyArray<string>]>;
+}
+
+// Each tsconfig needs its own program. The programs share parsed and bound
+// files (Effect's and Node's declarations) through one registry, as the
+// language service does. Without it, building 17 programs took about 13 s.
+const registry = ts.createDocumentRegistry();
+
+// Returns each file with those of its names that are Effect schemas.
+function findSchemas({ cwd, configPath, files }: Project) {
+ const config = configPath
+ ? ts.getParsedCommandLineOfConfigFile(
+ configPath,
+ {},
+ {
+ ...ts.sys,
+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
+ throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
+ },
+ },
+ )
+ : undefined;
+ if (config?.errors.length) {
+ throw new Error(
+ config.errors
+ .map((error) => ts.flattenDiagnosticMessageText(error.messageText, "\n"))
+ .join("\n"),
+ );
+ }
+ const options: ts.CompilerOptions = {
+ module: ts.ModuleKind.NodeNext,
+ allowJs: true,
+ ...config?.options,
+ noEmit: true,
+ };
+ const host = ts.createCompilerHost(options);
+ const key = registry.getKeyForCompilationSettings(options);
+ host.getSourceFile = (fileName, languageVersionOrOptions) => {
+ const text = host.readFile(fileName);
+ if (text === undefined) return undefined;
+ return registry.acquireDocumentWithKey(
+ fileName,
+ ts.sys.resolvePath(fileName) as ts.Path,
+ options,
+ key,
+ ts.ScriptSnapshot.fromString(text),
+ // Files do not change during one run.
+ "1",
+ undefined,
+ languageVersionOrOptions,
+ );
+ };
+ const program = ts.createProgram(
+ files.map(([file]) => NodePath.resolve(cwd, file)),
+ options,
+ host,
+ );
+ const checker = program.getTypeChecker();
+ return files.flatMap(([filePath, names]) => {
+ const source = program.getSourceFile(NodePath.resolve(cwd, filePath));
+ const module = source && checker.getSymbolAtLocation(source);
+ if (!source || !module) return [];
+ const schemas = checker
+ .getExportsOfModule(module)
+ .filter((symbol) => names.includes(symbol.name))
+ .flatMap((symbol) => {
+ const exported =
+ symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
+ const target =
+ exported.flags & ts.SymbolFlags.Value
+ ? exported
+ : checker.resolveName(symbol.name, source, ts.SymbolFlags.Value, false);
+ if (!target) return [];
+ const type = checker.getTypeOfSymbolAtLocation(target, target.valueDeclaration ?? source);
+ const marker = type.getProperty(schemaTypeId);
+ if (!marker) return [];
+ const markerType = checker.getTypeOfSymbolAtLocation(marker, source);
+ return markerType.isStringLiteral() && markerType.value === schemaTypeId
+ ? [symbol.name]
+ : [];
+ });
+ return [[filePath, schemas] as const];
+ });
+}
+
+// The preprocessor loads this file again as each worker.
+if (!NodeWorkerThreads.isMainThread) {
+ const projects: ReadonlyArray<Project> = NodeWorkerThreads.workerData;
+ NodeWorkerThreads.parentPort?.postMessage(projects.flatMap(findSchemas));
+}
+
+// Three workers measured fastest. Each one parses Effect again, so more
+// workers cost more than they save.
+const WORKERS = Math.min(3, NodeOS.availableParallelism());
+
+// Drops unused-export issues whose every symbol is an Effect schema.
+const preprocess = async (options: Parameters<Preprocessor>[0]) => {
const categories = ["exports", "nsExports", "duplicates"] as const;
- const projects = new Map<string | undefined, Set<string>>();
+ const projects = new Map<string | undefined, Map<string, Set<string>>>();
for (const category of categories) {
for (const [filePath, issues] of Object.entries(options.issues[category])) {
if (Object.keys(issues).length === 0) continue;
@@ -16,76 +119,60 @@ const preprocess: Preprocessor = (options) => {
NodePath.dirname(NodePath.resolve(options.cwd, filePath)),
ts.sys.fileExists,
);
- const files = projects.get(configPath) ?? new Set<string>();
- files.add(filePath);
+ const files = projects.get(configPath) ?? new Map<string, Set<string>>();
+ const names = files.get(filePath) ?? new Set<string>();
+ for (const issue of Object.values(issues)) {
+ for (const { symbol } of issue.symbols ?? [{ symbol: issue.symbol }]) names.add(symbol);
+ }
+ files.set(filePath, names);
projects.set(configPath, files);
}
}
- for (const [configPath, files] of projects) {
- const config = configPath
- ? ts.getParsedCommandLineOfConfigFile(
- configPath,
- {},
- {
- ...ts.sys,
- onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
- throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
- },
- },
- )
- : undefined;
- if (config?.errors.length) {
- throw new Error(
- config.errors
- .map((error) => ts.flattenDiagnosticMessageText(error.messageText, "\n"))
- .join("\n"),
- );
- }
- const program = ts.createProgram(
- [...files].map((file) => NodePath.resolve(options.cwd, file)),
- {
- module: ts.ModuleKind.NodeNext,
- allowJs: true,
- ...config?.options,
- noEmit: true,
- },
- );
- const checker = program.getTypeChecker();
- for (const filePath of files) {
- const source = program.getSourceFile(NodePath.resolve(options.cwd, filePath));
- const module = source && checker.getSymbolAtLocation(source);
- if (!source || !module) continue;
- const schemas = new Set(
- checker.getExportsOfModule(module).flatMap((symbol) => {
- const exported =
- symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
- const target =
- exported.flags & ts.SymbolFlags.Value
- ? exported
- : checker.resolveName(symbol.name, source, ts.SymbolFlags.Value, false);
- if (!target) return [];
- const type = checker.getTypeOfSymbolAtLocation(target, target.valueDeclaration ?? source);
- const marker = type.getProperty(schemaTypeId);
- if (!marker) return [];
- const markerType = checker.getTypeOfSymbolAtLocation(marker, source);
- return markerType.isStringLiteral() && markerType.value === schemaTypeId
- ? [symbol.name]
- : [];
+ // Deal the projects out largest first so the workers get similar shares.
+ const shares = Array.from({ length: WORKERS }, (): Array<Project> => []);
+ [...projects]
+ .sort(([, a], [, b]) => b.size - a.size)
+ .forEach(([configPath, files], index) => {
+ shares[index % WORKERS]!.push({
+ cwd: options.cwd,
+ configPath,
+ files: [...files].map(([file, names]) => [file, [...names]]),
+ });
+ });
+ const workers = shares
+ .filter((share) => share.length > 0)
+ .map((share) => new NodeWorkerThreads.Worker(new URL(import.meta.url), { workerData: share }));
+ const results = await Promise.all(
+ workers.map(
+ (worker) =>
+ new Promise<ReturnType<typeof findSchemas>>((resolve, reject) => {
+ worker.once("message", resolve);
+ worker.once("error", reject);
+ worker.once("exit", (code) => {
+ if (code !== 0) reject(new Error(`knip-schemas worker exited with code ${code}`));
+ });
}),
- );
- for (const category of categories) {
- const issues = options.issues[category][filePath];
- if (!issues) continue;
- for (const [key, issue] of Object.entries(issues)) {
- const symbols = issue.symbols ?? [{ symbol: issue.symbol }];
- if (symbols.length > 0 && symbols.every(({ symbol }) => schemas.has(symbol))) {
- delete issues[key];
- options.counters[category]--;
- }
+ ),
+ ).catch(async (error: unknown) => {
+ // knip only sets an exit code on a failed preprocessor, so stop the
+ // siblings or the failed run waits for their work.
+ await Promise.allSettled(workers.map((worker) => worker.terminate()));
+ throw error;
+ });
+
+ for (const [filePath, names] of results.flat()) {
+ for (const category of categories) {
+ const issues = options.issues[category][filePath];
+ if (!issues) continue;
+ for (const [key, issue] of Object.entries(issues)) {
+ const symbols = issue.symbols ?? [{ symbol: issue.symbol }];
+ if (symbols.length > 0 && symbols.every(({ symbol }) => names.includes(symbol))) {
+ delete issues[key];
+ options.counters[category]--;
}
- if (Object.keys(issues).length === 0) delete options.issues[category][filePath];
}
+ if (Object.keys(issues).length === 0) delete options.issues[category][filePath];
}
}
return options;