Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

perf(tests): defer the run-time-only imports at the head of the server suite's import graph (#6156)

Adam Eivyf0e9fbccd8cf
diff --git a/server/AGENTS.md b/server/AGENTS.md
index 0b5bc83a3d..373b1fda6f 100644
--- a/server/AGENTS.md
+++ b/server/AGENTS.md
@@ -26,6 +26,8 @@ These apply to Express/service/model code. Universal constraints (no try/catch o
## Import scoping
- **A widely-reached module must not drag a subtree it only needs a constant from.** The Linux CI server suite spends more wall time importing modules than running assertions, because import cost multiplies: every test file that transitively reaches module `X` re-instantiates all of `X`'s closure in its own worker. So one convenient barrel import inside a module 400 suites reach is worth thousands of module instantiations. `server/lib/importScoping.test.js` pins the narrowings made in #6009 (which cut the suite from ~115.5k static module instantiations to ~94.5k) as negative reachability assertions over `staticImportClosure`; add a row there when you narrow another one. The two shapes worth looking for: a constant re-exported through a heavy barrel (import it from the module that *declares* it — `CHECK_SCOPES` from `editorial/checkInfra/taxonomy.js`, not from `editorial/checkRegistry.js` and its 13 check-definition modules), and a dependency only a boot/rare path uses (`await import()` it inside that path — `ensureSchemaImpl()` composes the DDL that way, keeping `lib/db/schema/**` out of the ~400 suites that reach `lib/db.js` through `pgFileFacade.js`).
+- **In a non-async scope, defer with `.then()` rather than giving up.** The lazy shape is not limited to `async` functions: a `new Promise` executor or a fire-and-forget branch takes `import('./x.js').then(({ fn }) => fn(…)).catch(handler)`, which also routes an import failure into the error path the call already had. That is how the TUI branch in `services/promptRunner.js` defers `tuiPromptRunner.js` (and with it `node-pty`). Prefer putting the `import()` INSIDE an existing predicate gate when there is one — `runner.js` defers `ollamaAgentContext.js` inside the `isOllamaBackedProvider` ternary, so a cloud-provider run pays neither the hop nor the subtree.
+- **The tree-wide budget is the backstop the per-edge rows can't be.** `importScoping.test.js` also asserts a ceiling on the sum, over every server test file, of `staticImportClosure(file).files.size` — the one assertion that catches a NEW heavy edge somewhere nobody thought to add a row for. It carries headroom for ordinary growth; when it fails, narrow or defer the import before raising the number, and lower it after a change that drops the total. History: 115,519 (before #6009) → 96,233 (#6009) → 83,439 (#6156).
- **Narrowing an import must not step around a barrel a suite mocks.** `vi.mock('./cos.js')` intercepts the specifier, not the function — so re-pointing a caller from `./cos.js` to the `./cosTaskStore.js` that declares `addTask` makes production code reach the REAL implementation while the suite still believes it is doubled. The failure lands in an unrelated test file with no obvious link to the import you changed. Before narrowing, grep the tree for `vi.mock` against the module you are leaving; if any suite that reaches the caller mocks it, leave the import on the barrel. A lazy `await import()` has no such hazard — vitest's mock registry covers dynamic imports too.
## Generated manifests
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index cacb70a012..fcf74afc26 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -24,9 +24,10 @@
*/
import { describe, it, expect } from 'vitest';
-import { dirname, join } from 'path';
+import { existsSync, readdirSync, readFileSync } from 'fs';
+import { dirname, join, resolve } from 'path';
import { fileURLToPath } from 'url';
-import { staticImportClosure } from './staticImportGraph.js';
+import { staticImportClosure, staticImportSpecifiers } from './staticImportGraph.js';
const SERVER_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -84,3 +85,160 @@ describe('narrowed imports stay narrow (#6009)', () => {
expect(reaches('lib/db/schema/index.js', 'lib/db/schema/catalog.js')).toBe(true);
});
});
+
+/**
+ * Deferred imports (#6156).
+ *
+ * The other shape from the AGENTS.md section: not a constant reachable from a
+ * lighter module, but a dependency that only a run/boot path executes. #6009
+ * used it once (`ensureSchemaImpl`); these are the rest of the head of the
+ * distribution — the four heaviest remaining edges were all "imported at module
+ * scope, called only once a run is actually executing".
+ *
+ * Each row is asserted BOTH ways. The negative alone would also pass if someone
+ * deleted the call entirely, which is a different (and probably wrong) change
+ * than the one this row is defending; the positive pins the `await import()`
+ * that has to remain in its place.
+ */
+// [entry, target, why, specifier] — same first three columns as NARROWED above,
+// plus the specifier the call site must still name in its `await import()`.
+const DEFERRED = [
+ ['services/cos.js', 'services/persistentMindAdapter.js',
+ 'is registered once at daemon start, but pulls the CoS tool registry, voice tools, ask service and image-gen backends',
+ './persistentMindAdapter.js'],
+ ['services/promptRunner.js', 'services/providerExecutionReadiness.js',
+ 'runs readiness only on the TUI execution branch, not when a run is built or classified',
+ './providerExecutionReadiness.js'],
+ ['services/promptRunner.js', 'services/tuiPromptRunner.js',
+ 'drags node-pty in through services/shell.js for a branch most promptRunner suites never take',
+ './tuiPromptRunner.js'],
+ ['services/settings.js', 'services/userActions.js',
+ 'makes one ledger write reaching the DB layer, from a module nearly every service imports',
+ './userActions.js'],
+ ['services/runner.js', 'services/ollamaAgentContext.js',
+ 'needs the daemon manager only for an ollama-backed CLI run; the call was already predicate-gated',
+ './ollamaAgentContext.js'],
+];
+
+describe('deferred imports stay deferred (#6156)', () => {
+ it.each(DEFERRED)('%s no longer statically reaches %s — it %s', (entry, target) => {
+ expect(reaches(entry, target)).toBe(false);
+ });
+
+ it.each(DEFERRED)('%s still lazily imports %s at its call site', (entry, target, why, specifier) => {
+ const src = readFileSync(abs(entry), 'utf-8');
+ expect(
+ src.includes(`import('${specifier}')`),
+ `${entry} no longer contains a dynamic import('${specifier}'). If ${target} is genuinely unused now, delete this row — do not restore a static import.`,
+ ).toBe(true);
+ });
+
+ // Positive control, mirroring the one above: these targets are real modules
+ // with real graphs, so a resolver gap can't be what makes the negatives pass.
+ it('still sees the deferred modules from their own entry points', () => {
+ expect(reaches('services/persistentMindAdapter.js', 'services/cosToolRegistry.js')).toBe(true);
+ expect(reaches('services/tuiPromptRunner.js', 'services/shell.js')).toBe(true);
+ });
+});
+
+/**
+ * The trend metric, as a budget.
+ *
+ * The rows above are exact: each defends one edge. This defends the property
+ * they exist for — that the suite as a whole does not drift back toward
+ * importing what it never runs — and it is the only assertion here that catches
+ * a NEW heavy edge somewhere nobody has thought to add a row for.
+ *
+ * It is a budget, not a high-water mark. It sits ~1.5k above the measured total
+ * so ordinary growth (a new service plus its suite) does not fail it, while the
+ * shape this file exists to catch — one eager edge into a heavy subtree,
+ * multiplied by every suite crossing it — moves the number by thousands.
+ *
+ * If a change pushes past it, first ask whether the new import belongs at module
+ * scope at all. If it does, raise the number in the same commit and say what was
+ * added. When a narrowing drops the total well below it, lower it — a budget
+ * nobody tightens stops measuring anything.
+ *
+ * History, over the test files under `server/` only — the same denominator
+ * #6009 reported, and what `serverTestFiles()` below walks:
+ * 115,519 before #6009 · 96,233 after · 83,439 after #6156.
+ */
+const MAX_STATIC_INSTANTIATIONS = 85000;
+
+const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
+const serverTestFiles = (dir = SERVER_DIR, out = []) => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (entry.isDirectory()) {
+ if (SKIP_DIRS.has(entry.name) || entry.name.startsWith('.')) continue;
+ serverTestFiles(join(dir, entry.name), out);
+ } else if (entry.name.endsWith('.test.js')) {
+ out.push(join(dir, entry.name));
+ }
+ }
+ return out;
+};
+
+/**
+ * `staticImportClosure` re-reads and re-parses every module it walks, so calling
+ * it once per suite re-parses widely-shared modules thousands of times. That is
+ * fine for the handful of single-entry assertions above and far too slow here:
+ * ~1,600 entries took 18s on a CI runner and blew the 10s testTimeout.
+ *
+ * Same walk, with the per-file specifier list memoized across entries. The
+ * agreement test below pins it to the shared implementation so the two cannot
+ * drift into measuring different things.
+ */
+const depsCache = new Map();
+const resolvedDeps = (file) => {
+ const cached = depsCache.get(file);
+ if (cached) return cached;
+ const deps = [...new Set(
+ staticImportSpecifiers(file)
+ .filter((spec) => spec.startsWith('.'))
+ .map((spec) => resolve(dirname(file), spec))
+ .filter((path) => existsSync(path)),
+ )];
+ depsCache.set(file, deps);
+ return deps;
+};
+
+const closureSize = (entry) => {
+ const seen = new Set();
+ const stack = [entry];
+ while (stack.length) {
+ const file = stack.pop();
+ if (seen.has(file)) continue;
+ seen.add(file);
+ for (const dep of resolvedDeps(file)) if (!seen.has(dep)) stack.push(dep);
+ }
+ return seen.size;
+};
+
+describe('server suite import budget (#6156)', () => {
+ it('memoized closure walk agrees with staticImportClosure', () => {
+ // A spread of entry points: two modules this PR touched, one heavy suite,
+ // and a leaf. If the shared parser gains a specifier shape this walk does
+ // not follow (or vice versa), these diverge.
+ for (const sample of ['lib/db.js', 'lib/pipelineValidation.js', 'services/agentManagement.test.js', 'lib/editorial/checkInfra/taxonomy.js']) {
+ expect(closureSize(abs(sample)), sample).toBe(staticImportClosure(abs(sample)).files.size);
+ }
+ });
+
+ // Explicit timeout: this walks every server test file, which is inherently
+ // more work than a unit test and runs on a shared CI runner. The memoized
+ // walk brings it to ~1s locally, but the default 10s leaves no margin for a
+ // slow or contended runner — and a timeout here reads as a budget failure,
+ // which is exactly the wrong diagnosis.
+ it(`stays under ${MAX_STATIC_INSTANTIATIONS.toLocaleString()} static module instantiations`, () => {
+ const files = serverTestFiles();
+ // Guards the walk itself: an empty or tiny list would make the budget pass
+ // vacuously, the same failure mode the positive controls above defend.
+ expect(files.length, 'found almost no test files — the walk above is broken').toBeGreaterThan(1000);
+
+ const total = files.reduce((sum, file) => sum + closureSize(file), 0);
+ expect(
+ total,
+ `Static module instantiations across the server suite rose to ${total.toLocaleString()}. Something added an eager import into a heavy subtree from a widely-reached module — narrow it, defer it with a call-site await import(), or raise the budget deliberately. See the "Import scoping" section of server/AGENTS.md.`,
+ ).toBeLessThanOrEqual(MAX_STATIC_INSTANTIATIONS);
+ }, 60_000);
+});
diff --git a/server/services/cos.js b/server/services/cos.js
index 4563e0896d..77a94c8a55 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -172,7 +172,11 @@ import {
registerPersistentMindTurnAdapter,
unregisterPersistentMindTurnAdapter,
} from './persistentMindSupervisor.js';
-import { createPersistentMindTurnAdapter } from './persistentMindAdapter.js';
+// `./persistentMindAdapter.js` is imported lazily where the daemon registers the
+// adapter, NOT here. It pulls in the whole CoS tool registry — and through it the
+// voice tool surface, ask service and image-gen backends — a graph the daemon only
+// executes once it is actually running, but that a static edge instantiated in
+// every suite importing cos.js for an unrelated helper.
export {
getPersistentMindState,
@@ -512,6 +516,7 @@ async function runStart() {
emitLog('info', 'Running initial task evaluation...');
await evaluateTasks({ initialStartup: true });
await runHealthCheck();
+ const { createPersistentMindTurnAdapter } = await import('./persistentMindAdapter.js');
await registerPersistentMindTurnAdapter(createPersistentMindTurnAdapter());
await initializePersistentMindSupervisor();
diff --git a/server/services/promptRunner.js b/server/services/promptRunner.js
index d97cf6ebda..0df1b95afc 100644
--- a/server/services/promptRunner.js
+++ b/server/services/promptRunner.js
@@ -28,7 +28,11 @@
import { createRun, executeApiRun, executeCliRun, extractBakedModel, hasModelFlag, stopRun, patchRunMetadata, finalizeRunRecord } from './runner.js';
import { getActiveProvider, getProviderById, getAllProviders } from './providers.js';
-import { executeTuiRun } from './tuiPromptRunner.js';
+// `./tuiPromptRunner.js` (which drags node-pty in through `./shell.js`) and
+// `./providerExecutionReadiness.js` are imported lazily on the branches that
+// actually execute a run — see their call sites below. promptRunner.js is reached
+// by ~160 suites that only build or classify a run, and a static edge instantiated
+// both subtrees in every one of them.
import { ServerError } from '../lib/errorHandler.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { analyzeError, ERROR_CATEGORIES, isRunCanceledError } from '../lib/aiToolkit/errorDetection.js';
@@ -39,7 +43,6 @@ import { createSingleFlight } from '../lib/singleFlight.js';
import { extractJson } from '../lib/jsonExtract.js';
import { isCreativeRunSource, withCreativeLatitude } from '../lib/creativeLatitude.js';
import { DEFAULT_OUTPUT_RESERVE_TOKENS, estimateTokens } from '../lib/contextBudget.js';
-import { ensureProviderReadyForExecution } from './providerExecutionReadiness.js';
// The fallback-lifecycle notifiers live in services/autoFixer.js, which
// transitively pulls in services/cos.js (PM2 + fs + sockets). Importing it
@@ -1266,10 +1269,12 @@ async function executeProviderRunOnce({
// providers spawn OpenCode directly, so they need the same hook here or
// MTPLX remains stopped until after the TUI has already failed its request.
if (effectiveProvider.type === PROVIDER_TYPES.TUI) {
- const ready = await ensureProviderReadyForExecution(effectiveProvider).catch((err) => ({
- success: false,
- error: err.message,
- }));
+ const ready = await import('./providerExecutionReadiness.js')
+ .then(({ ensureProviderReadyForExecution }) => ensureProviderReadyForExecution(effectiveProvider))
+ .catch((err) => ({
+ success: false,
+ error: err.message,
+ }));
if (!ready.success) {
const message = ready.error || 'Provider readiness check failed';
await finalizeRunRecord({
@@ -1400,7 +1405,9 @@ async function executeProviderRunOnce({
} else if (effectiveProvider.type === PROVIDER_TYPES.TUI) {
// `source` (e.g. 'pipeline-manuscript-completeness') labels the live,
// interactive view this TUI run surfaces in the Shell page.
- executeTuiRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, onData, onComplete, onReady: onRunReady, timeout: effectiveTimeout, label: source }).catch(safeReject);
+ import('./tuiPromptRunner.js')
+ .then(({ executeTuiRun }) => executeTuiRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, onData, onComplete, onReady: onRunReady, timeout: effectiveTimeout, label: source }))
+ .catch(safeReject);
} else {
safeReject(new Error(`Unsupported provider type: ${effectiveProvider.type}`));
}
diff --git a/server/services/runner.js b/server/services/runner.js
index 285f4abed6..760cb01be7 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -13,7 +13,8 @@ import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { createImmediateFallbackSignalDetector, ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';
import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { isHostShuttingDown } from '../lib/hostShutdown.js';
-import { ensureOllamaAgentContext } from './ollamaAgentContext.js';
+// `./ollamaAgentContext.js` (and the ollama daemon manager behind it) is imported
+// lazily inside the predicate-gated branch below, NOT here — see that call site.
import { isOllamaBackedProvider } from './providers.js';
import {
setAIToolkitInstance,
@@ -384,9 +385,12 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc
// hold the daemon at the provider's configured window (or warn) first. See
// services/ollamaAgentContext.js.
// Gated on the predicate here (not just inside the helper) so a cloud-provider
- // run — the overwhelmingly common case — takes no async hop at all.
+ // run — the overwhelmingly common case — takes no async hop at all, and the
+ // import sits INSIDE that gate so it never instantiates the daemon manager's
+ // subtree either. ~160 suites reach runner.js and none of them run ollama.
const ollamaContext = isOllamaBackedProvider(provider)
- ? await ensureOllamaAgentContext(provider, { model: provider.defaultModel ?? null })
+ ? await import('./ollamaAgentContext.js')
+ .then(({ ensureOllamaAgentContext }) => ensureOllamaAgentContext(provider, { model: provider.defaultModel ?? null }))
: null;
if (ollamaContext?.warning) onData?.(`${ollamaContext.warning}\n`);
diff --git a/server/services/settings.js b/server/services/settings.js
index c50851ca35..60d3cb4b58 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -3,7 +3,10 @@ import { EventEmitter } from 'events';
import { safeJSONParse, PATHS, atomicWrite, tryReadFile, tryReadFileStrict } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { canonicalStringify, isPlainObject, POLLUTING_KEYS } from '../lib/objects.js';
-import { recordUserAction } from './userActions.js';
+// `./userActions.js` is imported lazily at its single call site below, NOT here.
+// It reaches the DB schema/query layer, and settings.js is imported by nearly
+// every service — a static edge instantiated that subtree in ~200 suites that
+// never write a ledger row.
// POLLUTING_KEYS (`__proto__`/`constructor`/`prototype`) is the project-wide
// prototype-pollution denylist (defined in server/lib/objects.js). Without it,
@@ -269,6 +272,7 @@ const save = async (settings, { actor = 'system', skipUserAction = false } = {})
if (!skipUserAction && change && change.keysChanged.length > 0) {
const happenedAt = new Date().toISOString();
const changedKeys = change.keysChanged.join(',');
+ const { recordUserAction } = await import('./userActions.js');
await recordUserAction({
type: 'settings.update',
actor,