diff --git a/loopx/control_plane/coordination/authority_store_codec.ts b/loopx/control_plane/coordination/authority_store_codec.ts index 93bd923468..8bae0df7b1 100644 --- a/loopx/control_plane/coordination/authority_store_codec.ts +++ b/loopx/control_plane/coordination/authority_store_codec.ts @@ -10,11 +10,9 @@ export function isAuthorityJsonObject(value: unknown): value is JsonObject { return typeof value === "object" && value !== null && !Array.isArray(value); } -export function authorityUnicodeCompare(left: string, right: string): number { - // Walk code points without allocating two arrays for every sort comparison. - // JS's default sort compares UTF-16 units, which would change persisted - // revisions for supplementary characters relative to BMP characters. - let leftIndex = 0, rightIndex = 0; +function compareCodePointsFrom(left: string, right: string, startIndex: number): number { + let leftIndex = startIndex; + let rightIndex = startIndex; while (leftIndex < left.length && rightIndex < right.length) { const leftPoint = left.codePointAt(leftIndex)!; const rightPoint = right.codePointAt(rightIndex)!; @@ -25,6 +23,24 @@ export function authorityUnicodeCompare(left: string, right: string): number { return leftIndex < left.length ? 1 : rightIndex < right.length ? -1 : 0; } +export function authorityUnicodeCompare(left: string, right: string): number { + // Fast-path code-unit comparison below 0xD800 where UTF-16 order matches + // Unicode code-point order, falling back cleanly for any surrogate units. + const limit = Math.min(left.length, right.length); + for (let index = 0; index < limit; index++) { + const leftUnit = left.charCodeAt(index); + const rightUnit = right.charCodeAt(index); + if (leftUnit !== rightUnit) { + if (leftUnit < 0xd800 && rightUnit < 0xd800) return leftUnit - rightUnit; + return compareCodePointsFrom(left, right, index); + } + if (leftUnit >= 0xd800 && leftUnit <= 0xdfff) { + return compareCodePointsFrom(left, right, index); + } + } + return left.length - right.length; +} + export function hasExactAuthorityKeys( value: JsonObject, keys: readonly string[], @@ -111,6 +127,15 @@ export function copyAuthorityJson(value: unknown): unknown { return cloneAuthorityJson(value, new Set(), false); } +function sortCanonicalKeys(keys: string[]): void { + for (let index = 1; index < keys.length; index++) { + if (authorityUnicodeCompare(keys[index - 1]!, keys[index]!) > 0) { + keys.sort(authorityUnicodeCompare); + return; + } + } +} + function cloneAuthorityJson(value: unknown, stack: Set, canonicalKeys: boolean): unknown { if (value === null || typeof value === "string" || typeof value === "boolean") { return value; @@ -147,20 +172,28 @@ function cloneAuthorityJson(value: unknown, stack: Set, canonicalKeys: b stack.add(value); try { const keys = Object.keys(value); - if (!canonicalKeys) { - // Fill without inherited setters (including __proto__), then normalize - // to the same ordinary object as Object.fromEntries. No per-field tuples. - const copy: JsonObject = Object.create(null); - for (const key of keys) copy[key] = cloneAuthorityJson(value[key], stack, false); - return Object.setPrototypeOf(copy, Object.prototype); + if (canonicalKeys && keys.length > 1) { + sortCanonicalKeys(keys); + } + // Define own data properties on an ordinary object (avoiding Object.create(null) + // + Object.setPrototypeOf dictionary transitions) while preventing inherited + // setters such as __proto__ via Object.defineProperty. + const copy: JsonObject = {}; + for (let index = 0; index < keys.length; index++) { + const key = keys[index]!; + const cloned = cloneAuthorityJson(value[key], stack, canonicalKeys); + if (key in Object.prototype) { + Object.defineProperty(copy, key, { + value: cloned, + writable: true, + enumerable: true, + configurable: true, + }); + } else { + copy[key] = cloned; + } } - keys.sort(authorityUnicodeCompare); - return Object.fromEntries( - keys.map((key) => [ - key, - cloneAuthorityJson(value[key], stack, canonicalKeys), - ]), - ); + return copy; } finally { stack.delete(value); } diff --git a/loopx/control_plane/coordination/coordination_projection.ts b/loopx/control_plane/coordination/coordination_projection.ts index c38e9de725..68136261e5 100644 --- a/loopx/control_plane/coordination/coordination_projection.ts +++ b/loopx/control_plane/coordination/coordination_projection.ts @@ -374,6 +374,41 @@ export class CoordinationProjectionRead { } } +function assembleReducedProjection( + value: JsonObject, + nextTodos: JsonObject[], + nextLeases: JsonObject[], + readModel: JsonObject | undefined, +): JsonObject { + const rest: JsonObject = {}; + for (const key of Object.keys(value)) { + if (key === "todos" || key === "leases" || key === "todo_read_model") continue; + const entry = value[key]; + if (key in Object.prototype) { + Object.defineProperty(rest, key, { value: entry, writable: true, enumerable: true, configurable: true }); + } else { + rest[key] = entry; + } + } + const canonicalRest = canonicalAuthorityObject(rest, "coordination projection"); + canonicalRest.todos = nextTodos; + canonicalRest.leases = nextLeases; + if (readModel !== undefined) { + canonicalRest.todo_read_model = readModel; + } + const keys = Object.keys(canonicalRest).sort(authorityUnicodeCompare); + const assembled: JsonObject = {}; + for (const key of keys) { + const entry = canonicalRest[key]; + if (key in Object.prototype) { + Object.defineProperty(assembled, key, { value: entry, writable: true, enumerable: true, configurable: true }); + } else { + assembled[key] = entry; + } + } + return assembled; +} + /** * Apply one already-authorized coordination transaction as a pure projection * reduction. Domain transition policy stays with the LoopX kernel; this @@ -394,6 +429,7 @@ export function reduceCoordinationProjection( const todos = new Map(current.todos); const leases = new Map(current.leases); const mutatedRecords = new Set(); + const mutatedTodoIds: string[] = []; const claimMutationTarget = (kind: "todo" | "lease", todoId: string): void => { const target = `${kind}:${todoId}`; @@ -403,6 +439,7 @@ export function reduceCoordinationProjection( ); } mutatedRecords.add(target); + if (kind === "todo") mutatedTodoIds.push(todoId); }; for (const [index, mutation] of mutations.entries()) { @@ -424,25 +461,24 @@ export function reduceCoordinationProjection( } } const nextTodos = sortedIds(todos.keys()).map((todoId) => todos.get(todoId)!); - const readModel = previous && coordinationTodoReadModel(nextTodos, previous.readModel.schema_version); - const historicalContract = previous?.historicalContract; - // Ordinary writes should keep a released declaration readable by its - // original consumer. A write that uses newer fields needs the current one. - if (readModel && historicalContract && !usesFieldsOutsideTodoContract(nextTodos, historicalContract)) { - readModel.contract_fields = [...historicalContract.fields]; - } - const reduced = canonicalAuthorityObject({ - ...value, - todos: nextTodos, - leases: sortedIds(leases.keys()).map((todoId) => leases.get(todoId)!), - ...(readModel === undefined - ? {} - : { todo_read_model: readModel }), - }, "coordination projection"); - if (value.todo_read_model !== undefined) { - validateCoordinationTodoReadModel(reduced, expectedGoalId); + const nextLeases = sortedIds(leases.keys()).map((todoId) => leases.get(todoId)!); + let readModel: JsonObject | undefined; + if (previous !== undefined) { + for (const todoId of mutatedTodoIds) { + const updated = todos.get(todoId); + if (updated !== undefined) { + canonicalTodoRecord(updated, `coordination Todo read record ${todoId}`); + } + } + readModel = coordinationTodoReadModel(nextTodos, previous.readModel.schema_version); + const historicalContract = previous.historicalContract; + // Ordinary writes should keep a released declaration readable by its + // original consumer. A write that uses newer fields needs the current one. + if (historicalContract && !usesFieldsOutsideTodoContract(nextTodos, historicalContract)) { + readModel.contract_fields = [...historicalContract.fields]; + } } - return reduced; + return assembleReducedProjection(value, nextTodos, nextLeases, readModel); } function mutationTarget(mutation: CoordinationProjectionMutation, index: number): string { @@ -476,9 +512,6 @@ export function prepareCoordinationProjectionCommit( goalId, input.mutations, ); - if (currentProjection.todo_read_model !== undefined) { - validateCoordinationTodoReadModel(nextProjection, goalId); - } const targets = input.mutations.map(mutationTarget).sort(authorityUnicodeCompare); const mutationKinds = input.mutations.map((mutation) => mutation.kind).sort( authorityUnicodeCompare, diff --git a/loopx/control_plane/coordination/coordination_state_contract.ts b/loopx/control_plane/coordination/coordination_state_contract.ts index 5deb8e8908..d31c5931f4 100644 --- a/loopx/control_plane/coordination/coordination_state_contract.ts +++ b/loopx/control_plane/coordination/coordination_state_contract.ts @@ -70,13 +70,26 @@ export function canonicalTodoDomainRecord(value: unknown, label = "Todo domain r return record as TodoDomainRecord; } +const FROZEN_CONTRACT_ALLOWED = new WeakMap>(); + +function allowedFieldsForContract(contract: RecordContract): ReadonlySet { + if (Object.isFrozen(contract) && Object.isFrozen(contract.fields)) { + const cached = FROZEN_CONTRACT_ALLOWED.get(contract); + if (cached !== undefined) return cached; + const set = new Set(contract.fields); + FROZEN_CONTRACT_ALLOWED.set(contract, set); + return set; + } + return new Set(contract.fields); +} + export function canonicalCoordinationRecord( value: unknown, contract: RecordContract, label: string, ): JsonObject { const record = canonicalAuthorityObject(value, label); - const allowed = new Set(contract.fields); + const allowed = allowedFieldsForContract(contract); const unknownRequired = contract.required_fields.filter( (field) => !allowed.has(field), ); @@ -85,15 +98,20 @@ export function canonicalCoordinationRecord( `${label} required fields are absent from fields: ${unknownRequired.join(", ")}`, ); } - const unexpected = Object.keys(record) - .filter((field) => !allowed.has(field)) - .sort((left, right) => left.localeCompare(right)); + const unexpected: string[] = []; + for (const field of Object.keys(record)) { + if (!allowed.has(field)) unexpected.push(field); + } if (unexpected.length > 0) { + unexpected.sort((left, right) => left.localeCompare(right)); throw new AuthorityStoreProtocolError( `${label} has unversioned fields: ${unexpected.join(", ")}`, ); } - const missing = contract.required_fields.filter((field) => !(field in record)); + const missing: string[] = []; + for (const field of contract.required_fields) { + if (!(field in record)) missing.push(field); + } if (missing.length > 0) { throw new AuthorityStoreProtocolError( `${label} omits required fields: ${missing.join(", ")}`, @@ -102,10 +120,12 @@ export function canonicalCoordinationRecord( // Preserve the generic contract's legacy `in` selection for inherited fields. // Shipped Todo contracts need no reconstruction: normalization already owns // every allowed field and nested container in canonical order. - if (contract.fields.some((field) => !Object.hasOwn(record, field) && field in record)) { - return canonicalAuthorityObject(Object.fromEntries( - contract.fields.flatMap((field) => field in record ? [[field, record[field]]] : []), - ), label); + for (const field of contract.fields) { + if (!Object.hasOwn(record, field) && field in record) { + return canonicalAuthorityObject(Object.fromEntries( + contract.fields.flatMap((entry) => entry in record ? [[entry, record[entry]]] : []), + ), label); + } } return record; } diff --git a/loopx/control_plane/coordination/nokv_authority_store.ts b/loopx/control_plane/coordination/nokv_authority_store.ts index a9feaaf915..b3a6b17654 100644 --- a/loopx/control_plane/coordination/nokv_authority_store.ts +++ b/loopx/control_plane/coordination/nokv_authority_store.ts @@ -202,6 +202,8 @@ function validStoreIdentity(value: string, workbench: string): boolean { return value.startsWith(prefix) && HEX_128_PATTERN.test(value.slice(prefix.length)); } +const FATAL_UTF8_DECODER = new TextDecoder("utf-8", { fatal: true }); + /** Stage 2A candidate. No runtime constructs this provider by default. */ export class NoKVAuthorityStore implements AuthorityStore { readonly providerKind = "nokv" as const; @@ -267,7 +269,7 @@ export class NoKVAuthorityStore implements AuthorityStore { const generation = requireGeneration(result.generation, "NoKV read generation"); let raw: string; try { - raw = new TextDecoder("utf-8", { fatal: true }).decode(result.bytes); + raw = FATAL_UTF8_DECODER.decode(result.bytes); } catch (error) { throw new AuthorityStoreProtocolError( `NoKV authority store bytes are not UTF-8: ${ diff --git a/package.json b/package.json index f87d381c5a..016167efd5 100644 --- a/package.json +++ b/package.json @@ -8,9 +8,9 @@ "node": ">=22.22.3" }, "scripts": { - "test:control-plane": "node --no-warnings --experimental-sqlite --experimental-strip-types --test --test-concurrency=4 tests/control_plane_ts/*.test.ts", + "test:control-plane": "node scripts/run_control_plane_ts_tests.mjs", "test:remote-authority": "node --no-warnings --experimental-sqlite --experimental-strip-types --test tests/control_plane_ts/remote_authority_client.test.ts", - "test:control-plane:coverage": "c8 --all --include=loopx/control_plane/**/*.ts --exclude=loopx/control_plane/**/*.generated.ts --reporter=lcov --reporter=text --reports-dir=coverage/control-plane node --no-warnings --experimental-sqlite --experimental-strip-types --test --test-concurrency=4 tests/control_plane_ts/*.test.ts", + "test:control-plane:coverage": "c8 --all --include=loopx/control_plane/**/*.ts --exclude=loopx/control_plane/**/*.generated.ts --reporter=lcov --reporter=text --reports-dir=coverage/control-plane node scripts/run_control_plane_ts_tests.mjs", "test:dashboard:coverage": "tsc --ignoreConfig --target ES2022 --module ES2022 --moduleResolution Bundler --skipLibCheck --strict --sourceMap --inlineSources --outDir apps/presentation/dashboard/node_modules/.cache/loopx-agent-family apps/presentation/dashboard/src/features/personal-workspace/agent-family.ts && cd apps/presentation/dashboard && npx vite build --ssr smoke/decision-research-surface-coverage.tsx --outDir node_modules/.cache/loopx-decision-research-coverage --emptyOutDir --sourcemap && cd ../../.. && c8 --exclude-node-modules=false --include=apps/presentation/dashboard/node_modules/.cache/loopx-agent-family/agent-family.js --include=apps/presentation/dashboard/node_modules/.cache/loopx-decision-research-coverage/decision-research-surface-coverage.js --reporter=lcov --reporter=text --reports-dir=coverage/dashboard node apps/presentation/dashboard/smoke/dashboard-coverage-runner.mjs", "typecheck:control-plane": "tsc --project tsconfig.control-plane.json --noEmit" }, diff --git a/scripts/run_control_plane_ts_tests.d.mts b/scripts/run_control_plane_ts_tests.d.mts new file mode 100644 index 0000000000..2dafe2a284 --- /dev/null +++ b/scripts/run_control_plane_ts_tests.d.mts @@ -0,0 +1,78 @@ +export const REPO_ROOT: string; +export const DEFAULT_TEST_DIR: string; +export const DEFAULT_CONCURRENCY_MIN: number; +export const DEFAULT_CONCURRENCY_MAX: number; +export const HEAVY_LANE_CONCURRENCY: number; +export const HEAVY_CONTROL_PLANE_TEST_FILES: readonly string[]; + +export function resolveTestConcurrency( + env?: NodeJS.ProcessEnv | Record, + availableParallelism?: number, +): number; + +export function shouldEnableCompileCache( + env?: NodeJS.ProcessEnv | Record, +): boolean; + +export function listDefaultControlPlaneTestFiles(repoRoot?: string): string[]; + +export function analyzeCliArgs(argv?: readonly string[]): { + hasExplicitTestTargets: boolean; + hasExplicitConcurrency: boolean; +}; + +export function buildNodeTestArgs( + argv?: readonly string[], + options?: { + env?: NodeJS.ProcessEnv | Record; + availableParallelism?: number; + repoRoot?: string; + }, +): string[]; + +export type ControlPlaneRunPlan = + | { + mode: "single"; + totalConcurrency: number; + args: string[]; + } + | { + mode: "two_lane"; + totalConcurrency: number; + heavyConcurrency: number; + standardConcurrency: number; + heavyFiles: string[]; + standardFiles: string[]; + }; + +export function buildControlPlaneRunPlan( + argv?: readonly string[], + options?: { + env?: NodeJS.ProcessEnv | Record; + availableParallelism?: number; + repoRoot?: string; + }, +): ControlPlaneRunPlan; + +export function createScopedCompileCache(options?: { + env?: NodeJS.ProcessEnv | Record; + tmpRoot?: string; +}): { + cacheDir: string | null; + cleanup: () => void; +}; + +export function runControlPlaneTests( + argv?: readonly string[], + options?: { + env?: NodeJS.ProcessEnv | Record; + availableParallelism?: number; + repoRoot?: string; + tmpRoot?: string; + execPath?: string; + }, +): Promise<{ + status: number | null; + signal: NodeJS.Signals | null; + cacheDir: string | null; +}>; diff --git a/scripts/run_control_plane_ts_tests.mjs b/scripts/run_control_plane_ts_tests.mjs new file mode 100644 index 0000000000..73f42a6739 --- /dev/null +++ b/scripts/run_control_plane_ts_tests.mjs @@ -0,0 +1,540 @@ +#!/usr/bin/env node +/** + * Adaptive runner for TypeScript control-plane tests (`npm run test:control-plane`). + * + * Uses APFS-safe adaptive `--test-concurrency` (`LOOPX_TS_TEST_CONCURRENCY` or + * clamped `Math.floor(availableParallelism / 2)` within `[4, 8]`), 2-lane + * heavy-first scheduling for the default full suite when concurrency >= 6, and a + * private run-scoped `NODE_COMPILE_CACHE` directory unless caller cache, + * disable, or coverage environment settings apply. + */ + +import { spawn } from "node:child_process"; +import { + chmodSync, + mkdtempSync, + readdirSync, + realpathSync, + rmSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +export const REPO_ROOT = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "..", +); +export const DEFAULT_TEST_DIR = "tests/control_plane_ts"; +export const DEFAULT_CONCURRENCY_MIN = 4; +export const DEFAULT_CONCURRENCY_MAX = 8; +export const HEAVY_LANE_CONCURRENCY = 2; +export const HEAVY_CONTROL_PLANE_TEST_FILES = [ + "tests/control_plane_ts/sqlite_authority_store.test.ts", + "tests/control_plane_ts/authority_store.test.ts", +]; + +const VALUE_FLAGS = new Set([ + "-C", + "-r", + "--conditions", + "--cpu-prof-dir", + "--diagnostic-dir", + "--env-file", + "--env-file-if-exists", + "--heap-prof-dir", + "--import", + "--loader", + "--require", + "--test-concurrency", + "--test-name-pattern", + "--test-reporter", + "--test-reporter-destination", + "--test-shard", + "--test-skip-pattern", + "--test-timeout", +]); + +const BASE_NODE_TEST_ARGS = [ + "--no-warnings", + "--experimental-sqlite", + "--experimental-strip-types", + "--test", +]; + +/** + * Resolve worker concurrency from `LOOPX_TS_TEST_CONCURRENCY` or adaptive CPU + * scaling clamped to `[4, 8]`. + */ +export function resolveTestConcurrency( + env = process.env, + availableParallelism = os.availableParallelism(), +) { + const raw = env?.LOOPX_TS_TEST_CONCURRENCY; + if (typeof raw === "string") { + const trimmed = raw.trim(); + if (/^\d+$/.test(trimmed)) { + const parsed = Number.parseInt(trimmed, 10); + if (Number.isSafeInteger(parsed) && parsed > 0) { + return parsed; + } + } + } + const detected = + Number.isFinite(availableParallelism) && availableParallelism > 0 + ? Math.floor(availableParallelism) + : DEFAULT_CONCURRENCY_MIN; + return Math.min( + DEFAULT_CONCURRENCY_MAX, + Math.max(DEFAULT_CONCURRENCY_MIN, Math.floor(detected / 2)), + ); +} + +/** + * Enable a private run-scoped compile cache only when no caller cache, + * explicit disable flag, or V8 coverage collection is active. + */ +export function shouldEnableCompileCache(env = process.env) { + if (!env) return true; + if (env.NODE_COMPILE_CACHE) return false; + if (env.NODE_DISABLE_COMPILE_CACHE === "1") return false; + if (env.NODE_V8_COVERAGE) return false; + return true; +} + +/** + * Discover and sort `tests/control_plane_ts/*.test.ts` deterministically. + */ +export function listDefaultControlPlaneTestFiles(repoRoot = REPO_ROOT) { + const testDir = path.join(repoRoot, DEFAULT_TEST_DIR); + const entries = readdirSync(testDir, { withFileTypes: true }); + return entries + .filter((entry) => entry.isFile() && entry.name.endsWith(".test.ts")) + .map((entry) => `${DEFAULT_TEST_DIR}/${entry.name}`) + .sort(); +} + +/** + * Inspect forwarded CLI arguments to distinguish Node test flags from explicit + * positional test targets without discarding multi-token flags. + */ +export function analyzeCliArgs(argv = []) { + let hasExplicitTestTargets = false; + let hasExplicitConcurrency = false; + let expectingFlagValue = false; + let afterDoubleDash = false; + + for (const token of argv) { + if (afterDoubleDash) { + hasExplicitTestTargets = true; + continue; + } + if (expectingFlagValue) { + expectingFlagValue = false; + continue; + } + if (token === "--") { + afterDoubleDash = true; + continue; + } + if ( + token === "--test-concurrency" || + token.startsWith("--test-concurrency=") + ) { + hasExplicitConcurrency = true; + } + if (token.startsWith("-")) { + if (!token.includes("=") && VALUE_FLAGS.has(token)) { + expectingFlagValue = true; + } + continue; + } + hasExplicitTestTargets = true; + } + + return { hasExplicitTestTargets, hasExplicitConcurrency }; +} + +/** + * Build the complete `node` argv for executing control-plane TS tests. + */ +export function buildNodeTestArgs( + argv = [], + { + env = process.env, + availableParallelism = os.availableParallelism(), + repoRoot = REPO_ROOT, + } = {}, +) { + const { hasExplicitTestTargets, hasExplicitConcurrency } = analyzeCliArgs(argv); + const args = [...BASE_NODE_TEST_ARGS]; + if (!hasExplicitConcurrency) { + const concurrency = resolveTestConcurrency(env, availableParallelism); + args.push(`--test-concurrency=${concurrency}`); + } + args.push(...argv); + if (!hasExplicitTestTargets) { + args.push(...listDefaultControlPlaneTestFiles(repoRoot)); + } + return args; +} + +/** + * Plan single-process fallback or 2-lane heavy-first execution for the control-plane suite. + */ +export function buildControlPlaneRunPlan( + argv = [], + { + env = process.env, + availableParallelism = os.availableParallelism(), + repoRoot = REPO_ROOT, + } = {}, +) { + const totalConcurrency = resolveTestConcurrency(env, availableParallelism); + if (argv.length > 0 || totalConcurrency < 6 || Boolean(env?.NODE_V8_COVERAGE)) { + return { + mode: "single", + totalConcurrency, + args: buildNodeTestArgs(argv, { env, availableParallelism, repoRoot }), + }; + } + const allFiles = listDefaultControlPlaneTestFiles(repoRoot); + const allFileSet = new Set(allFiles); + const heavyFiles = HEAVY_CONTROL_PLANE_TEST_FILES.filter((file) => + allFileSet.has(file), + ); + const heavySet = new Set(heavyFiles); + const standardFiles = allFiles.filter((file) => !heavySet.has(file)); + if (heavyFiles.length === 0 || standardFiles.length === 0) { + return { + mode: "single", + totalConcurrency, + args: buildNodeTestArgs(argv, { env, availableParallelism, repoRoot }), + }; + } + return { + mode: "two_lane", + totalConcurrency, + heavyConcurrency: HEAVY_LANE_CONCURRENCY, + standardConcurrency: totalConcurrency - HEAVY_LANE_CONCURRENCY, + heavyFiles, + standardFiles, + }; +} + +/** + * Create a mode-`0o700` temporary compile-cache directory scoped to one run. + */ +export function createScopedCompileCache({ + env = process.env, + tmpRoot = os.tmpdir(), +} = {}) { + if (!shouldEnableCompileCache(env)) { + return { cacheDir: null, cleanup: () => {} }; + } + const cacheDir = mkdtempSync(path.join(tmpRoot, "loopx-ts-compile-cache-")); + chmodSync(cacheDir, 0o700); + let cleaned = false; + const cleanup = () => { + if (cleaned) return; + cleaned = true; + try { + rmSync(cacheDir, { recursive: true, force: true }); + } catch { + // Best-effort cleanup on exit/signal; never mask child test failure. + } + }; + return { cacheDir, cleanup }; +} + +function terminateWithSignal(signal) { + try { + process.kill(process.pid, signal); + } catch { + process.exitCode = 1; + } +} + +function attachProcessSignalHandlers(onCleanup, onSignal) { + const signals = + process.platform === "win32" + ? ["SIGINT", "SIGTERM"] + : ["SIGINT", "SIGTERM", "SIGHUP"]; + const signalListeners = new Map(); + process.on("exit", onCleanup); + for (const signal of signals) { + const listener = () => onSignal(signal); + signalListeners.set(signal, listener); + process.on(signal, listener); + } + return () => { + process.off("exit", onCleanup); + for (const [signal, listener] of signalListeners.entries()) { + process.off(signal, listener); + } + signalListeners.clear(); + }; +} + +function spawnManagedProcess({ execPath, args, cwd, env, stdio, activeChildren }) { + const child = spawn(execPath, args, { + cwd, + env, + stdio, + windowsHide: true, + }); + activeChildren.add(child); + return child; +} + +function runInheritedLane({ execPath, args, cwd, env, activeChildren }) { + return new Promise((resolve) => { + const child = spawnManagedProcess({ + execPath, + args, + cwd, + env, + stdio: "inherit", + activeChildren, + }); + let settled = false; + child.once("error", (error) => { + if (settled) return; + settled = true; + activeChildren.delete(child); + console.error(`Failed to launch Node test runner: ${error.message}`); + resolve({ status: 1, signal: null }); + }); + child.once("close", (status, signal) => { + if (settled) return; + settled = true; + activeChildren.delete(child); + resolve({ status, signal }); + }); + }); +} + +function runBufferedHeavyFile({ execPath, file, cwd, env, activeChildren }) { + return new Promise((resolve) => { + const args = [...BASE_NODE_TEST_ARGS, "--test-concurrency=1", file]; + const child = spawnManagedProcess({ + execPath, + args, + cwd, + env, + stdio: ["ignore", "pipe", "pipe"], + activeChildren, + }); + let stdout = ""; + let stderr = ""; + let settled = false; + child.stdout?.setEncoding("utf8"); + child.stderr?.setEncoding("utf8"); + child.stdout?.on("data", (chunk) => { + stdout += chunk; + }); + child.stderr?.on("data", (chunk) => { + stderr += chunk; + }); + child.once("error", (error) => { + if (settled) return; + settled = true; + activeChildren.delete(child); + resolve({ + file, + status: 1, + signal: null, + stdout, + stderr: `${stderr}Failed to launch ${file}: ${error.message}\n`, + }); + }); + child.once("close", (status, signal) => { + if (settled) return; + settled = true; + activeChildren.delete(child); + resolve({ file, status, signal, stdout, stderr }); + }); + }); +} + +function flushHeavyResult(result) { + const outcome = + result.signal !== null + ? `signal=${result.signal}` + : `exit=${result.status ?? 1}`; + process.stdout.write(`\n[heavy-lane] ${result.file} (${outcome})\n`); + if (result.stdout) { + process.stdout.write(result.stdout); + if (!result.stdout.endsWith("\n")) process.stdout.write("\n"); + } + if (result.stderr) { + process.stderr.write(result.stderr); + if (!result.stderr.endsWith("\n")) process.stderr.write("\n"); + } +} + +export async function runControlPlaneTests( + argv = process.argv.slice(2), + { + env = process.env, + availableParallelism = os.availableParallelism(), + repoRoot = REPO_ROOT, + tmpRoot = os.tmpdir(), + execPath = process.execPath, + } = {}, +) { + const { cacheDir, cleanup } = createScopedCompileCache({ env, tmpRoot }); + const childEnv = { ...env }; + if (cacheDir !== null) { + childEnv.NODE_COMPILE_CACHE = cacheDir; + } + + let plan; + try { + plan = buildControlPlaneRunPlan(argv, { + env, + availableParallelism, + repoRoot, + }); + } catch (error) { + cleanup(); + throw error; + } + + const activeChildren = new Set(); + let aborted = false; + let forwardedSignal = null; + + const detachListeners = attachProcessSignalHandlers(cleanup, (signal) => { + aborted = true; + forwardedSignal ??= signal; + for (const child of activeChildren) { + if (!child.killed) { + try { + child.kill(signal); + } catch { + // Child may have already exited while signal arrived. + } + } + } + }); + + try { + if (plan.mode === "single") { + const outcome = await runInheritedLane({ + execPath, + args: plan.args, + cwd: repoRoot, + env: childEnv, + activeChildren, + }); + return { + status: outcome.status, + signal: outcome.signal ?? forwardedSignal, + cacheDir, + }; + } + + const standardArgs = [ + ...BASE_NODE_TEST_ARGS, + `--test-concurrency=${plan.standardConcurrency}`, + ...plan.standardFiles, + ]; + let standardDone = false; + const pendingHeavyOutputs = []; + + const standardPromise = runInheritedLane({ + execPath, + args: standardArgs, + cwd: repoRoot, + env: childEnv, + activeChildren, + }).then((result) => { + standardDone = true; + while (pendingHeavyOutputs.length > 0) { + flushHeavyResult(pendingHeavyOutputs.shift()); + } + return result; + }); + + const queue = [...plan.heavyFiles]; + const heavyResults = []; + const runWorker = async () => { + while (!aborted && queue.length > 0) { + const file = queue.shift(); + const result = await runBufferedHeavyFile({ + execPath, + file, + cwd: repoRoot, + env: childEnv, + activeChildren, + }); + heavyResults.push(result); + if (standardDone) { + flushHeavyResult(result); + } else { + pendingHeavyOutputs.push(result); + } + } + }; + const workerCount = Math.min(plan.heavyConcurrency, queue.length); + const heavyPromise = Promise.all( + Array.from({ length: workerCount }, () => runWorker()), + ); + + const [standardOutcome] = await Promise.all([standardPromise, heavyPromise]); + const heavySignal = + heavyResults.find((item) => item.signal !== null)?.signal ?? null; + const failedHeavy = heavyResults.find( + (item) => item.status !== 0 || item.signal !== null, + ); + const missingHeavy = heavyResults.length !== plan.heavyFiles.length; + const combinedSignal = + standardOutcome.signal ?? heavySignal ?? forwardedSignal; + let combinedStatus = 0; + if (standardOutcome.status !== 0) { + combinedStatus = standardOutcome.status ?? 1; + } else if (failedHeavy) { + combinedStatus = failedHeavy.status ?? 1; + } else if (missingHeavy) { + combinedStatus = 1; + } + + const heavyPassed = heavyResults.filter( + (item) => item.status === 0 && item.signal === null, + ).length; + process.stdout.write( + `[run_control_plane_ts_tests] 2-lane summary: heavy=${heavyPassed}/${plan.heavyFiles.length} (concurrency=${plan.heavyConcurrency}), standard_files=${plan.standardFiles.length} (concurrency=${plan.standardConcurrency}, exit=${standardOutcome.status ?? standardOutcome.signal})\n`, + ); + + return { + status: combinedSignal !== null ? null : combinedStatus, + signal: combinedSignal, + cacheDir, + }; + } finally { + detachListeners(); + cleanup(); + } +} + +function isMainModule() { + if (!process.argv[1]) return false; + try { + return ( + realpathSync(fileURLToPath(import.meta.url)) === + realpathSync(process.argv[1]) + ); + } catch { + return false; + } +} + +if (isMainModule()) { + const result = await runControlPlaneTests(); + if (result.signal !== null) { + terminateWithSignal(result.signal); + } else { + process.exit(result.status ?? 1); + } +} diff --git a/tests/control_plane/test_shared_goal_authority_e2e.py b/tests/control_plane/test_shared_goal_authority_e2e.py index 9c825cf993..9e88971e34 100644 --- a/tests/control_plane/test_shared_goal_authority_e2e.py +++ b/tests/control_plane/test_shared_goal_authority_e2e.py @@ -10,6 +10,7 @@ import json import os +import subprocess from collections.abc import Iterator from pathlib import Path @@ -452,7 +453,29 @@ def test_retired_prototype_rows_are_not_relabelled_as_native_evidence(capsys) -> def test_native_ladder_suites_remain_in_the_regular_typescript_test_job() -> None: package = json.loads((ladder.REPO_ROOT / "package.json").read_text()) - assert "tests/control_plane_ts/*.test.ts" in package["scripts"]["test:control-plane"] + script = package["scripts"]["test:control-plane"] + if "scripts/run_control_plane_ts_tests.mjs" in script: + node = ladder.node_executable() + assert node is not None + probe = subprocess.run( + [ + node, + "--input-type=module", + "-e", + ( + "import { buildNodeTestArgs } from './scripts/run_control_plane_ts_tests.mjs'; " + "console.log(JSON.stringify(buildNodeTestArgs([])));" + ), + ], + cwd=ladder.REPO_ROOT, + capture_output=True, + text=True, + check=True, + ) + selected_args = set(json.loads(probe.stdout)) + assert {path.as_posix() for path in ladder.LOCAL_CONFORMANCE_TESTS.values()} <= selected_args + else: + assert "tests/control_plane_ts/*.test.ts" in script regular_suites = set(ladder.REPO_ROOT.glob("tests/control_plane_ts/*.test.ts")) assert {ladder.REPO_ROOT / path for path in ladder.LOCAL_CONFORMANCE_TESTS.values()} <= regular_suites assert {row.id for row in ladder.LADDER_ROWS if row.stage == "0"} == { diff --git a/tests/control_plane_ts/authority_archive_audit.test.ts b/tests/control_plane_ts/authority_archive_audit.test.ts index c37b9cffad..b4de11061c 100644 --- a/tests/control_plane_ts/authority_archive_audit.test.ts +++ b/tests/control_plane_ts/authority_archive_audit.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import {spawnSync} from "node:child_process"; +import {spawn} from "node:child_process"; import {mkdtemp, readFile, rm, writeFile} from "node:fs/promises"; import {tmpdir} from "node:os"; import {join} from "node:path"; @@ -227,6 +227,24 @@ test("native and imported complete graphs audit all history across SQLite checkp } finally { await rm(root, {recursive: true, force: true}); } }); +function runConsumer(kind: "file" | "sqlite", path: string, checkpoint: string): Promise<{status: number | null; stdout: string; stderr: string}> { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, + ["--no-warnings", "--experimental-sqlite", "--experimental-strip-types", "--input-type=module", + "-e", consumerRead, kind, path, checkpoint], + {cwd: fileURLToPath(new URL("../../", import.meta.url)), stdio: ["ignore", "pipe", "pipe"], windowsHide: true}); + let stdout = "", stderr = ""; + child.stdout.setEncoding("utf8"); + child.stderr.setEncoding("utf8"); + child.stdout.on("data", chunk => { stdout += chunk; }); + child.stderr.on("data", chunk => { stderr += chunk; }); + const timer = setTimeout(() => { child.kill("SIGKILL"); reject(new Error("consumerRead timed out")); }, 30000); + child.once("error", err => { clearTimeout(timer); reject(err); }); + child.once("close", status => { clearTimeout(timer); resolve({status, stdout, stderr}); }); + }); +} + +test.suite("archive audit and consumer recovery", { concurrency: 4 }, () => { for (const provider of ["file", "sqlite"] as const) { test(`${provider}: lagging consumer resumes after process restart and explicit archive roundtrip`, async () => { const root = await mkdtemp(join(tmpdir(), "consumer-recovery-")); @@ -264,12 +282,9 @@ for (const provider of ["file", "sqlite"] as const) { assert.deepEqual(consumed.transactions.map(({provider_revision, ...row}) => row), expected); await writeFile(checkpoint, JSON.stringify({store_identity: identity.store_identity, after_cursor: "63"})); for (let i = 64; i <= 131; i++) revision = await append(source, revision, i); - const consume = (kind: "file" | "sqlite", path: string) => spawnSync(process.execPath, - ["--no-warnings", "--experimental-sqlite", "--experimental-strip-types", "--input-type=module", - "-e", consumerRead, kind, path, checkpoint], - {cwd: fileURLToPath(new URL("../../", import.meta.url)), encoding: "utf8", timeout: 30000}); + const consume = (kind: "file" | "sqlite", path: string) => runConsumer(kind, path, checkpoint); const check = async (kind: "file" | "sqlite", path: string, store: AuthorityStore) => { - const before = await store.loadAuthority(), child = consume(kind, path); + const before = await store.loadAuthority(), child = await consume(kind, path); assert.equal(child.status, 0, child.stderr); const result = JSON.parse(child.stdout); assert.equal(result.cursor, String(expected.length)); @@ -288,7 +303,7 @@ for (const provider of ["file", "sqlite"] as const) { const migrated = makeStore(other, migratedPath), backup = join(root, "backup"); const archive = await exportAuthorityArchive(source, "goal", backup, {pageSize: 17}); await restoreAuthorityArchive(backup, migrated, archive.archive_sha256); - const wrongLineage = consume(other, migratedPath); + const wrongLineage = await consume(other, migratedPath); assert.notEqual(wrongLineage.status, 0); assert.match(wrongLineage.stderr, /another store lineage/); // A verified complete archive supplies the explicit cursor mapping. The @@ -314,3 +329,4 @@ for (const provider of ["file", "sqlite"] as const) { } finally { await rm(root, {recursive: true, force: true}); } }); } +}); diff --git a/tests/control_plane_ts/nokv_jsonl_transport.test.ts b/tests/control_plane_ts/nokv_jsonl_transport.test.ts index 0ce6493de5..4bdb38a3df 100644 --- a/tests/control_plane_ts/nokv_jsonl_transport.test.ts +++ b/tests/control_plane_ts/nokv_jsonl_transport.test.ts @@ -94,21 +94,42 @@ test("JSON-lines transport cannot bypass its open handshake", () => { assert.equal(processStarted, false); }); -registerAuthorityStoreConformance("NoKV JSON-lines process", async (t) => { - const transport = await openSdkHelper(); - t.after(async () => await transport.close()); - return { - store: new NoKVAuthorityStore(transport, { - tenant_id: "tenant-a", - goal_id: "goal-a", - workbench: "authority-workbench", - }), - contender: new NoKVAuthorityStore(transport, { - tenant_id: "tenant-a", - goal_id: "goal-a", - workbench: "authority-workbench", - }), - }; +const CONFORMANCE_POOL_SIZE = 6; +const idleConformanceTransports: NoKVJsonLinesTransport[] = []; +const openedConformanceTransports: NoKVJsonLinesTransport[] = []; +let conformanceCounter = 0; + +test.suite("NoKV JSON-lines process conformance", { concurrency: CONFORMANCE_POOL_SIZE }, () => { + test.after(async () => { + const transports = openedConformanceTransports.splice(0); + idleConformanceTransports.length = 0; + await Promise.all(transports.map((transport) => transport.close())); + }); + + registerAuthorityStoreConformance("NoKV JSON-lines process", async (t) => { + let transport = idleConformanceTransports.pop(); + if (transport === undefined) { + transport = await openSdkHelper(); + openedConformanceTransports.push(transport); + } + const leased = transport; + t.after(() => { + idleConformanceTransports.push(leased); + }); + const tenantId = `tenant-conformance-${conformanceCounter++}`; + return { + store: new NoKVAuthorityStore(leased, { + tenant_id: tenantId, + goal_id: "goal-a", + workbench: "authority-workbench", + }), + contender: new NoKVAuthorityStore(leased, { + tenant_id: tenantId, + goal_id: "goal-a", + workbench: "authority-workbench", + }), + }; + }); }); test("JSON-lines transport starts once and reuses the helper process", async (t) => { diff --git a/tests/control_plane_ts/production_scale_coordination_fixture.ts b/tests/control_plane_ts/production_scale_coordination_fixture.ts index cc073a1df7..b8c86dc037 100644 --- a/tests/control_plane_ts/production_scale_coordination_fixture.ts +++ b/tests/control_plane_ts/production_scale_coordination_fixture.ts @@ -54,6 +54,23 @@ const envelope = JSON.parse(readFileSync(new URL( export const PRODUCTION_SCALE_FIXTURE_SCHEMA = "loopx_coordination_production_scale_fixture_v0"; +const fixtureTemplateCache = new Map(); + +function memoizeFixture( + name: string, + build: (...args: A) => R, +): (...args: A) => R { + return (...args: A): R => { + const key = JSON.stringify([name, ...args]); + let cached = fixtureTemplateCache.get(key); + if (cached === undefined) { + cached = build(...args); + fixtureTemplateCache.set(key, cached); + } + return structuredClone(cached) as R; + }; +} + /** * One long retained history over the production-scale projection. * @@ -239,10 +256,12 @@ function todoRecords( }); } -export function productionScaleCoordinationFixture( - goalId: string, - schema: AuthorityProjectionSchema = "legacy", -): ProductionScaleCoordinationFixture { +export const productionScaleCoordinationFixture = memoizeFixture( + "coordination", + ( + goalId: string, + schema: AuthorityProjectionSchema = "legacy", + ): ProductionScaleCoordinationFixture => { if (envelope.schema_version !== PRODUCTION_SCALE_FIXTURE_SCHEMA) { throw new Error("production-scale fixture envelope schema mismatch"); } @@ -343,7 +362,7 @@ export function productionScaleCoordinationFixture( service_requires_factory: envelope.provider_matrix.service_requires_factory, }, }; -} +}); export const PRODUCTION_SCALE_RETIRED_LEASE_COUNT = envelope.retired_lease_count; export const PRODUCTION_SCALE_REJECTED_DECISION_COUNT = envelope.rejected_standing_decision_count; @@ -434,36 +453,39 @@ export interface ProductionScaleHistoryProjection { * The retained-history projection: production-scale record families and record * shapes at a size that keeps hundreds of retained transactions affordable. */ -export function productionScaleHistoryProjection( - goalId: string, - schema: AuthorityProjectionSchema = "legacy", -): ProductionScaleHistoryProjection { - const full = productionScaleCoordinationFixture(goalId, "legacy"); - const scope = PRODUCTION_SCALE_HISTORY.projection_scope; - const allTodos = full.projection.todos as Record[]; - const agentTodos = allTodos.filter(todo => todo.role === "agent"); - // Retained history is dominated by live observations, so the slice keeps the - // open monitors first and fills the remaining record budget with the other - // agent Todos in fixture order. - const openMonitors = agentTodos.filter(todo => - todo.status === "open" && todo.task_class === "continuous_monitor"); - const todos = [...openMonitors, ...agentTodos.filter(todo => !openMonitors.includes(todo))] - .slice(0, scope.agent_todos) - .concat(allTodos.filter(todo => todo.role === "user").slice(0, scope.user_todos)); - const todoIds = new Set(todos.map(todo => String(todo.todo_id))); - const leases = (full.projection.leases as Record[]) - .filter(lease => todoIds.has(String(lease.todo_id))).slice(0, scope.leases); - const projection = authorityProjectionFixture(goalId, todos, leases, "legacy", - {source_authority: "synthetic_production_scale_history_fixture", handoff_mode: "hard_lease"}); - const monitor_ids = todos.filter(todo => todo.task_class === "continuous_monitor") - .map(todo => String(todo.todo_id)); - if (monitor_ids.length === 0) { - throw new Error("production fixture history projection needs monitor Todos"); - } - return {projection: schema === "legacy" ? projection : projectionFixtureAsSchema(projection, schema), - todo_ids: todos.map(todo => String(todo.todo_id)).sort(authorityUnicodeCompare), - monitor_ids: monitor_ids.sort(authorityUnicodeCompare)}; -} +export const productionScaleHistoryProjection = memoizeFixture( + "history", + ( + goalId: string, + schema: AuthorityProjectionSchema = "legacy", + ): ProductionScaleHistoryProjection => { + const full = productionScaleCoordinationFixture(goalId, "legacy"); + const scope = PRODUCTION_SCALE_HISTORY.projection_scope; + const allTodos = full.projection.todos as Record[]; + const agentTodos = allTodos.filter(todo => todo.role === "agent"); + // Retained history is dominated by live observations, so the slice keeps the + // open monitors first and fills the remaining record budget with the other + // agent Todos in fixture order. + const openMonitors = agentTodos.filter(todo => + todo.status === "open" && todo.task_class === "continuous_monitor"); + const todos = [...openMonitors, ...agentTodos.filter(todo => !openMonitors.includes(todo))] + .slice(0, scope.agent_todos) + .concat(allTodos.filter(todo => todo.role === "user").slice(0, scope.user_todos)); + const todoIds = new Set(todos.map(todo => String(todo.todo_id))); + const leases = (full.projection.leases as Record[]) + .filter(lease => todoIds.has(String(lease.todo_id))).slice(0, scope.leases); + const projection = authorityProjectionFixture(goalId, todos, leases, "legacy", + {source_authority: "synthetic_production_scale_history_fixture", handoff_mode: "hard_lease"}); + const monitor_ids = todos.filter(todo => todo.task_class === "continuous_monitor") + .map(todo => String(todo.todo_id)); + if (monitor_ids.length === 0) { + throw new Error("production fixture history projection needs monitor Todos"); + } + return {projection: schema === "legacy" ? projection : projectionFixtureAsSchema(projection, schema), + todo_ids: todos.map(todo => String(todo.todo_id)).sort(authorityUnicodeCompare), + monitor_ids: monitor_ids.sort(authorityUnicodeCompare)}; + }, +); export interface ProductionScaleObservationStep { readonly operation_id: string; @@ -506,179 +528,200 @@ export function productionScaleObservationStep( /** Exercise execution handover inside the same mixed-status, decision and * historical-lease population. The ordinary fixture's counts stay unchanged. */ -export function productionScaleLeaseLifecycleFixture(goalId: string, - schema: AuthorityProjectionSchema = "native") { - const fixture = productionScaleCoordinationFixture(goalId, schema); - const scenario = envelope.lease_lifecycle; - const todos = fixture.projection.todos as Record[]; - const leases = fixture.projection.leases as Record[]; - const target = fixture.completion_todo_id; - const projection = authorityProjectionFixture(goalId, - todos.map(todo => todo.todo_id === target ? {...todo, claimed_by: null} : todo), - leases.map(lease => lease.todo_id === target ? {...lease, owner: scenario.owner, - idempotency_key: scenario.execution_key, version: scenario.version, - lease_epoch: scenario.lease_epoch} : lease), schema, - {source_authority: "synthetic_production_scale_fixture", handoff_mode: "hard_lease"}); - return {projection, target, scenario, registered_agents: fixture.registered_agents}; -} +export const productionScaleLeaseLifecycleFixture = memoizeFixture( + "lease_lifecycle", + (goalId: string, schema: AuthorityProjectionSchema = "native") => { + const fixture = productionScaleCoordinationFixture(goalId, schema); + const scenario = envelope.lease_lifecycle; + const todos = fixture.projection.todos as Record[]; + const leases = fixture.projection.leases as Record[]; + const target = fixture.completion_todo_id; + const projection = authorityProjectionFixture(goalId, + todos.map(todo => todo.todo_id === target ? {...todo, claimed_by: null} : todo), + leases.map(lease => lease.todo_id === target ? {...lease, owner: scenario.owner, + idempotency_key: scenario.execution_key, version: scenario.version, + lease_epoch: scenario.lease_epoch} : lease), schema, + {source_authority: "synthetic_production_scale_fixture", handoff_mode: "hard_lease"}); + return {projection, target, scenario, registered_agents: fixture.registered_agents}; + }, +); /** Claimed handover retains the complete mixed-status work graph. */ -export function productionScaleClaimTransferFixture(goalId: string, - schema: AuthorityProjectionSchema = "native") { - const fixture = productionScaleLeaseLifecycleFixture(goalId, schema); - const target = (fixture.projection.todos as Record[]).find(todo => todo.todo_id === fixture.target)!; - target.claimed_by = fixture.scenario.owner; - return {...fixture, projection: authorityProjectionFixture(goalId, - fixture.projection.todos as Record[], fixture.projection.leases as Record[], - schema, {handoff_mode: "hard_lease"})}; -} +export const productionScaleClaimTransferFixture = memoizeFixture( + "claim_transfer", + (goalId: string, schema: AuthorityProjectionSchema = "native") => { + const fixture = productionScaleLeaseLifecycleFixture(goalId, schema); + const target = (fixture.projection.todos as Record[]).find(todo => todo.todo_id === fixture.target)!; + target.claimed_by = fixture.scenario.owner; + return {...fixture, projection: authorityProjectionFixture(goalId, + fixture.projection.todos as Record[], fixture.projection.leases as Record[], + schema, {handoff_mode: "hard_lease"})}; + }, +); /** Start without a target lease, with a live peer beyond the bounded display. */ -export function productionScaleLeaseAcquisitionFixture(goalId: string, - schema: AuthorityProjectionSchema = "native") { - const fixture = productionScaleLeaseLifecycleFixture(goalId, schema); - const scenario = envelope.lease_acquisition; - const todos = fixture.projection.todos as Record[]; - const leases = fixture.projection.leases as Record[]; - const target = todos.find(todo => todo.todo_id === fixture.target)!; - const oldLease = leases.find(lease => lease.todo_id === fixture.target)!; - const projection = authorityProjectionFixture(goalId, - [...todos, {...target, todo_id: scenario.conflict_todo_id, text: "Independent scope holder beyond display limits"}], - [...leases.filter(lease => lease.todo_id !== fixture.target), {...oldLease, - todo_id: scenario.conflict_todo_id, owner: "agent-b", idempotency_key: "scope-holder", - write_scopes: ["independent-work/**"]}], schema, - {source_authority: "synthetic_production_scale_fixture", handoff_mode: "hard_lease"}); - return {...fixture, projection, acquisition: scenario}; -} +export const productionScaleLeaseAcquisitionFixture = memoizeFixture( + "lease_acquisition", + (goalId: string, schema: AuthorityProjectionSchema = "native") => { + const fixture = productionScaleLeaseLifecycleFixture(goalId, schema); + const scenario = envelope.lease_acquisition; + const todos = fixture.projection.todos as Record[]; + const leases = fixture.projection.leases as Record[]; + const target = todos.find(todo => todo.todo_id === fixture.target)!; + const oldLease = leases.find(lease => lease.todo_id === fixture.target)!; + const projection = authorityProjectionFixture(goalId, + [...todos, {...target, todo_id: scenario.conflict_todo_id, text: "Independent scope holder beyond display limits"}], + [...leases.filter(lease => lease.todo_id !== fixture.target), {...oldLease, + todo_id: scenario.conflict_todo_id, owner: "agent-b", idempotency_key: "scope-holder", + write_scopes: ["independent-work/**"]}], schema, + {source_authority: "synthetic_production_scale_fixture", handoff_mode: "hard_lease"}); + return {...fixture, projection, acquisition: scenario}; + }, +); /** A leased Monitor in the complete mixed work graph, with prior observations * and a waiting dependent. Only these target rows differ from the base fixture. */ -export function productionScaleLeasedMonitorFixture(goalId: string, - schema: AuthorityProjectionSchema = "native") { - const fixture = productionScaleCoordinationFixture(goalId, schema); - const target = fixture.completion_todo_id; - const rows = fixture.projection.todos as Record[]; - const dependent = [...rows].reverse().find(todo => todo.role === "agent" && todo.status === "open" && todo.todo_id !== target)!; - const todos = rows.map(todo => todo.todo_id === target ? {...todo, - task_class: "continuous_monitor", target_key: "leased-public-watch", cadence: "1h", - material_change_generation: 4, consecutive_no_change: "2", result_hash: "previous-evidence", - last_checked_at: "2026-09-01T00:00:00Z", next_due_at: "2026-09-01T01:00:00Z"} : - todo.todo_id === dependent.todo_id ? {...todo, resume_when: `monitor_changed:${target}`, - resume_monitor_generation: 4} : todo); - const projection = authorityProjectionFixture(goalId, todos, - fixture.projection.leases as Record[], schema, - {source_authority: "synthetic_production_scale_fixture", handoff_mode: "hard_lease"}); - return {projection, target, dependent: String(dependent.todo_id), - actor: "agent-a", registered_agents: fixture.registered_agents, - now: new Date("2026-09-01T01:00:00Z"), - proof: {idempotency_key: fixture.completion_lease_idempotency_key, - expected_version: fixture.completion_lease_expected_version}}; -} +export const productionScaleLeasedMonitorFixture = memoizeFixture( + "leased_monitor", + (goalId: string, schema: AuthorityProjectionSchema = "native") => { + const fixture = productionScaleCoordinationFixture(goalId, schema); + const target = fixture.completion_todo_id; + const rows = fixture.projection.todos as Record[]; + const dependent = [...rows].reverse().find(todo => todo.role === "agent" && todo.status === "open" && todo.todo_id !== target)!; + const todos = rows.map(todo => todo.todo_id === target ? {...todo, + task_class: "continuous_monitor", target_key: "leased-public-watch", cadence: "1h", + material_change_generation: 4, consecutive_no_change: "2", result_hash: "previous-evidence", + last_checked_at: "2026-09-01T00:00:00Z", next_due_at: "2026-09-01T01:00:00Z"} : + todo.todo_id === dependent.todo_id ? {...todo, resume_when: `monitor_changed:${target}`, + resume_monitor_generation: 4} : todo); + const projection = authorityProjectionFixture(goalId, todos, + fixture.projection.leases as Record[], schema, + {source_authority: "synthetic_production_scale_fixture", handoff_mode: "hard_lease"}); + return {projection, target, dependent: String(dependent.todo_id), + actor: "agent-a", registered_agents: fixture.registered_agents, + now: new Date("2026-09-01T01:00:00Z"), + proof: {idempotency_key: fixture.completion_lease_idempotency_key, + expected_version: fixture.completion_lease_expected_version}}; + }, +); /** A completed watch and its waiting dependent within the full mixed graph. */ -export function productionScaleCompletedMonitorFixture(goalId: string, - schema: AuthorityProjectionSchema = "native", retainedLease: "absent" | "active" | "expired" | "released" = "absent") { - const fixture = productionScaleLeasedMonitorFixture(goalId, schema); - const todos = (fixture.projection.todos as Record[]).map(todo => - todo.todo_id === fixture.target ? {...todo, status: "done", done: true, - completed_at: "2026-09-01T00:30:00Z", no_followup: true, - completion_continuation: "no_followup", completion_recovery: "same_turn_terminal_closeout", - completion_turn_key: "retired-cycle", watch_only: "true"} : todo); - return {...fixture, projection: authorityProjectionFixture(goalId, todos, - (fixture.projection.leases as Record[]).flatMap(lease => lease.todo_id !== fixture.target ? [lease] : - retainedLease === "absent" ? [] : [{...lease, - status: retainedLease === "released" ? "released" : "active", - ...(retainedLease === "expired" ? {expires_at: "2026-09-01T00:20:00Z"} : {}), - ...(retainedLease === "released" ? {released_at: "2026-09-01T00:30:00Z"} : {})}]), - schema, {source_authority: "synthetic_production_scale_fixture", handoff_mode: retainedLease === "absent" ? "soft_claim" : "hard_lease"})}; -} +export const productionScaleCompletedMonitorFixture = memoizeFixture( + "completed_monitor", + (goalId: string, schema: AuthorityProjectionSchema = "native", + retainedLease: "absent" | "active" | "expired" | "released" = "absent") => { + const fixture = productionScaleLeasedMonitorFixture(goalId, schema); + const todos = (fixture.projection.todos as Record[]).map(todo => + todo.todo_id === fixture.target ? {...todo, status: "done", done: true, + completed_at: "2026-09-01T00:30:00Z", no_followup: true, + completion_continuation: "no_followup", completion_recovery: "same_turn_terminal_closeout", + completion_turn_key: "retired-cycle", watch_only: "true"} : todo); + return {...fixture, projection: authorityProjectionFixture(goalId, todos, + (fixture.projection.leases as Record[]).flatMap(lease => lease.todo_id !== fixture.target ? [lease] : + retainedLease === "absent" ? [] : [{...lease, + status: retainedLease === "released" ? "released" : "active", + ...(retainedLease === "expired" ? {expires_at: "2026-09-01T00:20:00Z"} : {}), + ...(retainedLease === "released" ? {released_at: "2026-09-01T00:30:00Z"} : {})}]), + schema, {source_authority: "synthetic_production_scale_fixture", handoff_mode: retainedLease === "absent" ? "soft_claim" : "hard_lease"})}; + }, +); /** User decisions act on an exact dependent inside the full mixed graph. * The second blocker is deliberately beyond the compact display population. */ -export function productionScaleUserCompletionFixture(goalId: string, - schema: AuthorityProjectionSchema = "native", otherBlocker = false) { - const fixture = productionScaleCoordinationFixture(goalId, schema); - const scenario = envelope.semantic_cases.user_completion; - const todos = structuredClone(fixture.projection.todos) as Record[]; - const target = todos.find(todo => todo.role === "agent" && todo.status === "blocked")!; - const source = todos.find(todo => todo.role === "user" && todo.status === "open")!; - const scope = {schema_version: "decision_scope_v0", kind: "direction", granularity: "action", scope_key: scenario.scope_key}; - Object.assign(target, {task_class: "advancement_task", claimed_by: "agent-a", required_decision_scopes: [scope], - decision_scope_outcomes: [{schema_version: "todo_decision_scope_outcome_v0", outcome: "reject", - decision_scope: scope, source_todo_id: "todo_fixture_prior_decision"}]}); - Object.assign(source, {task_class: "user_gate", bound_agent: "agent-a", blocks_agent: "agent-a", - claimed_by: "agent-a", decision_scope: scope, unblocks_todo_id: target.todo_id}); - if (otherBlocker) todos.push({...source, todo_id: scenario.other_blocker_id, text: "Independent remaining owner decision"}); - return {projection: authorityProjectionFixture(goalId, todos, fixture.projection.leases as Record[], - schema, {handoff_mode: "hard_lease"}), source: String(source.todo_id), target: String(target.todo_id), - scope, registered_agents: fixture.registered_agents}; -} +export const productionScaleUserCompletionFixture = memoizeFixture( + "user_completion", + (goalId: string, schema: AuthorityProjectionSchema = "native", otherBlocker = false) => { + const fixture = productionScaleCoordinationFixture(goalId, schema); + const scenario = envelope.semantic_cases.user_completion; + const todos = structuredClone(fixture.projection.todos) as Record[]; + const target = todos.find(todo => todo.role === "agent" && todo.status === "blocked")!; + const source = todos.find(todo => todo.role === "user" && todo.status === "open")!; + const scope = {schema_version: "decision_scope_v0", kind: "direction", granularity: "action", scope_key: scenario.scope_key}; + Object.assign(target, {task_class: "advancement_task", claimed_by: "agent-a", required_decision_scopes: [scope], + decision_scope_outcomes: [{schema_version: "todo_decision_scope_outcome_v0", outcome: "reject", + decision_scope: scope, source_todo_id: "todo_fixture_prior_decision"}]}); + Object.assign(source, {task_class: "user_gate", bound_agent: "agent-a", blocks_agent: "agent-a", + claimed_by: "agent-a", decision_scope: scope, unblocks_todo_id: target.todo_id}); + if (otherBlocker) todos.push({...source, todo_id: scenario.other_blocker_id, text: "Independent remaining owner decision"}); + return {projection: authorityProjectionFixture(goalId, todos, fixture.projection.leases as Record[], + schema, {handoff_mode: "hard_lease"}), source: String(source.todo_id), target: String(target.todo_id), + scope, registered_agents: fixture.registered_agents}; + }, +); /** Complete graph evidence must survive archive, selection and display limits. */ -export function productionScaleSuccessionFixture(goalId: string, schema: AuthorityProjectionSchema = "native") { - const fixture = productionScaleCoordinationFixture(goalId, schema); - const projection = structuredClone(fixture.projection); - const todos = projection.todos as Record[]; - const cases = envelope.semantic_cases.succession as Record; - const base = todos.find(todo => todo.role === "agent")!; - const source = (key: string, fields: Record = {}): Record => ({...base, - todo_id: cases[key], text: "Verify the continuation relationship", index: todos.length + Object.keys(cases).indexOf(key) + 1, - status: "done", done: true, archive_state: "active", claimed_by: "agent-a", task_class: "advancement_task", - successor_todo_ids: [], superseded_by: null, resume_when: null, unblocks_todo_id: null, - no_followup: false, excluded_agents: [], ...fields}); - const added = [source("inferred_source"), source("archived_target", {archive_state: "archive", - resume_when: `todo_done:${cases.inferred_source}`, no_followup: true}), - source("missing_source", {successor_todo_ids: ["todo_missing_continuation"]}), - source("self_source", {successor_todo_ids: [cases.self_source]}), - source("handoff_source", {excluded_agents: ["agent-b"], unblocks_todo_id: cases.inferred_source, - successor_todo_ids: [cases.explicit_target]}), - source("explicit_target", {status: "open", done: false}), - source("closed_source", {no_followup: true})]; - for (const record of added) { - Reflect.deleteProperty(record, "material_change_generation"); - if (schema === "native") {Reflect.deleteProperty(record, "index"); Reflect.deleteProperty(record, "source_section");} - else if (record.archive_state === "archive") record.source_section = "Completed Work Archive"; - } - todos.push(...added); - todos.sort((left, right) => authorityUnicodeCompare(String(left.todo_id), String(right.todo_id))); - const readModel = projection.todo_read_model as Record; - readModel.todo_count = todos.length; - readModel.records_sha256 = canonicalAuthoritySha256(todos); - return {projection, cases}; -} +export const productionScaleSuccessionFixture = memoizeFixture( + "succession", + (goalId: string, schema: AuthorityProjectionSchema = "native") => { + const fixture = productionScaleCoordinationFixture(goalId, schema); + const projection = structuredClone(fixture.projection); + const todos = projection.todos as Record[]; + const cases = envelope.semantic_cases.succession as Record; + const base = todos.find(todo => todo.role === "agent")!; + const source = (key: string, fields: Record = {}): Record => ({...base, + todo_id: cases[key], text: "Verify the continuation relationship", index: todos.length + Object.keys(cases).indexOf(key) + 1, + status: "done", done: true, archive_state: "active", claimed_by: "agent-a", task_class: "advancement_task", + successor_todo_ids: [], superseded_by: null, resume_when: null, unblocks_todo_id: null, + no_followup: false, excluded_agents: [], ...fields}); + const added = [source("inferred_source"), source("archived_target", {archive_state: "archive", + resume_when: `todo_done:${cases.inferred_source}`, no_followup: true}), + source("missing_source", {successor_todo_ids: ["todo_missing_continuation"]}), + source("self_source", {successor_todo_ids: [cases.self_source]}), + source("handoff_source", {excluded_agents: ["agent-b"], unblocks_todo_id: cases.inferred_source, + successor_todo_ids: [cases.explicit_target]}), + source("explicit_target", {status: "open", done: false}), + source("closed_source", {no_followup: true})]; + for (const record of added) { + Reflect.deleteProperty(record, "material_change_generation"); + if (schema === "native") {Reflect.deleteProperty(record, "index"); Reflect.deleteProperty(record, "source_section");} + else if (record.archive_state === "archive") record.source_section = "Completed Work Archive"; + } + todos.push(...added); + todos.sort((left, right) => authorityUnicodeCompare(String(left.todo_id), String(right.todo_id))); + const readModel = projection.todo_read_model as Record; + readModel.todo_count = todos.length; + readModel.records_sha256 = canonicalAuthoritySha256(todos); + return {projection, cases}; + }, +); /** Retained User addressing in the complete graph, including legacy claims. * Selection must not derive completeness from the short display population. */ -export function productionScaleConsumerScopeFixture(goalId: string, schema: AuthorityProjectionSchema = "native") { - const fixture = productionScaleSuccessionFixture(goalId, schema); - const extra = [ - {todo_id: "todo_scope_peer_gate", task_class: "user_gate", claimed_by: "agent-b"}, - {todo_id: "todo_scope_peer_action", task_class: "user_action", claimed_by: "agent-b"}, - {todo_id: "todo_scope_explicit_gate", task_class: "user_gate", claimed_by: "agent-b", blocks_agent: "agent-a"}, - {todo_id: "todo_scope_explicit_action", task_class: "user_action", claimed_by: "agent-b", bound_agent: "agent-a"}, - {todo_id: "todo_scope_global", task_class: "user_gate", claimed_by: "agent-b", global_gate: true}, - ].map((item, index) => ({role: "user", status: "open", done: false, archive_state: "active", - text: "Review a synthetic result", source_section: "User Todo", index: 2000 + index, ...item})); - return {...fixture, projection: authorityProjectionFixture(goalId, - [...fixture.projection.todos as Record[], ...extra], - fixture.projection.leases as Record[], schema, {handoff_mode: "soft_claim"})}; -} +export const productionScaleConsumerScopeFixture = memoizeFixture( + "consumer_scope", + (goalId: string, schema: AuthorityProjectionSchema = "native") => { + const fixture = productionScaleSuccessionFixture(goalId, schema); + const extra = [ + {todo_id: "todo_scope_peer_gate", task_class: "user_gate", claimed_by: "agent-b"}, + {todo_id: "todo_scope_peer_action", task_class: "user_action", claimed_by: "agent-b"}, + {todo_id: "todo_scope_explicit_gate", task_class: "user_gate", claimed_by: "agent-b", blocks_agent: "agent-a"}, + {todo_id: "todo_scope_explicit_action", task_class: "user_action", claimed_by: "agent-b", bound_agent: "agent-a"}, + {todo_id: "todo_scope_global", task_class: "user_gate", claimed_by: "agent-b", global_gate: true}, + ].map((item, index) => ({role: "user", status: "open", done: false, archive_state: "active", + text: "Review a synthetic result", source_section: "User Todo", index: 2000 + index, ...item})); + return {...fixture, projection: authorityProjectionFixture(goalId, + [...fixture.projection.todos as Record[], ...extra], + fixture.projection.leases as Record[], schema, {handoff_mode: "soft_claim"})}; + }, +); /** Capability-owned bucket inside a full mixed graph, including a historical * same-target row that must never shadow the current Monitor. */ -export function productionScaleGroupedMonitorFixture(goalId: string, - schema: AuthorityProjectionSchema = "native") { - const fixture = productionScaleCoordinationFixture(goalId, schema); - const targetKey = "github-pr-state-example--repo-checks-pending"; - const monitor = {schema_version: "todo_domain_record_v0", todo_id: "todo_grouped_monitor", - role: "agent", status: "open", done: false, archive_state: "active", text: "Watch the pending PR bucket", - task_class: "continuous_monitor", action_kind: "issue_fix_pr_state_checks_pending", target_key: targetKey, - claimed_by: "agent-a", cadence: "30m", watch_only: "true", last_checked_at: "2026-09-01T00:00:00Z", - result_hash: "previous-membership", material_change_generation: 4, required_write_scopes: []}; - const projection = authorityProjectionFixture(goalId, [...fixture.projection.todos as Record[], - monitor, {...monitor, todo_id: "todo_grouped_history", status: "done", done: true, archive_state: "archive"}], - fixture.projection.leases as Record[], schema, - {source_authority: "synthetic_production_scale_fixture", handoff_mode: "hard_lease"}); - return {projection, target: monitor.todo_id, targetKey, actor: "agent-a", registered_agents: fixture.registered_agents, - now: new Date("2026-09-01T01:00:00Z")}; -} +export const productionScaleGroupedMonitorFixture = memoizeFixture( + "grouped_monitor", + (goalId: string, schema: AuthorityProjectionSchema = "native") => { + const fixture = productionScaleCoordinationFixture(goalId, schema); + const targetKey = "github-pr-state-example--repo-checks-pending"; + const monitor = {schema_version: "todo_domain_record_v0", todo_id: "todo_grouped_monitor", + role: "agent", status: "open", done: false, archive_state: "active", text: "Watch the pending PR bucket", + task_class: "continuous_monitor", action_kind: "issue_fix_pr_state_checks_pending", target_key: targetKey, + claimed_by: "agent-a", cadence: "30m", watch_only: "true", last_checked_at: "2026-09-01T00:00:00Z", + result_hash: "previous-membership", material_change_generation: 4, required_write_scopes: []}; + const projection = authorityProjectionFixture(goalId, [...fixture.projection.todos as Record[], + monitor, {...monitor, todo_id: "todo_grouped_history", status: "done", done: true, archive_state: "archive"}], + fixture.projection.leases as Record[], schema, + {source_authority: "synthetic_production_scale_fixture", handoff_mode: "hard_lease"}); + return {projection, target: monitor.todo_id, targetKey, actor: "agent-a", registered_agents: fixture.registered_agents, + now: new Date("2026-09-01T01:00:00Z")}; + }, +); diff --git a/tests/control_plane_ts/run_control_plane_ts_tests.test.ts b/tests/control_plane_ts/run_control_plane_ts_tests.test.ts new file mode 100644 index 0000000000..b3c7c0ccc2 --- /dev/null +++ b/tests/control_plane_ts/run_control_plane_ts_tests.test.ts @@ -0,0 +1,515 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { + chmodSync, + existsSync, + lstatSync, + mkdtempSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test, { type TestContext } from "node:test"; +import { fileURLToPath } from "node:url"; + +import { + analyzeCliArgs, + buildControlPlaneRunPlan, + buildNodeTestArgs, + createScopedCompileCache, + HEAVY_CONTROL_PLANE_TEST_FILES, + listDefaultControlPlaneTestFiles, + resolveTestConcurrency, + runControlPlaneTests, + shouldEnableCompileCache, +} from "../../scripts/run_control_plane_ts_tests.mjs"; + +const RUNNER_SCRIPT = fileURLToPath( + new URL("../../scripts/run_control_plane_ts_tests.mjs", import.meta.url), +); + +function makeTempWorkspace(t: TestContext, prefix = "loopx-ts-runner-test-") { + const root = mkdtempSync(join(tmpdir(), prefix)); + chmodSync(root, 0o700); + t.after(() => rmSync(root, { recursive: true, force: true })); + return root; +} + +function cleanRunnerEnv(extra: Record = {}) { + const env: Record = { ...process.env }; + delete env.LOOPX_TS_TEST_CONCURRENCY; + delete env.NODE_COMPILE_CACHE; + delete env.NODE_DISABLE_COMPILE_CACHE; + // Isolate nested `node --test` subprocesses from the outer runner's context. + delete env.NODE_TEST_CONTEXT; + // Clear inherited coverage directories so compile-cache tests observe clean opt-outs. + env.NODE_V8_COVERAGE = ""; + for (const [key, value] of Object.entries(extra)) { + if (value === undefined) { + delete env[key]; + } else { + env[key] = value; + } + } + return env; +} + +function runRunnerSubprocess( + args: readonly string[], + env: Record, +) { + return new Promise<{ + code: number | null; + signal: NodeJS.Signals | null; + stdout: string; + stderr: string; + }>((resolve, reject) => { + const child = spawn(process.execPath, [RUNNER_SCRIPT, ...args], { + env: env as NodeJS.ProcessEnv, + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + }); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8"); + child.stderr.setEncoding("utf8"); + child.stdout.on("data", (chunk) => { + stdout += chunk; + }); + child.stderr.on("data", (chunk) => { + stderr += chunk; + }); + child.once("error", reject); + child.once("close", (code, signal) => { + resolve({ code, signal, stdout, stderr }); + }); + }); +} + +test("resolveTestConcurrency clamps adaptive half-CPU sizing within [4, 8]", () => { + const cases: readonly [number, number][] = [ + [1, 4], + [2, 4], + [4, 4], + [8, 4], + [9, 4], + [10, 5], + [12, 6], + [14, 7], + [16, 8], + [18, 8], + [32, 8], + [0, 4], + [Number.NaN, 4], + ]; + for (const [cpus, expected] of cases) { + assert.equal( + resolveTestConcurrency({}, cpus), + expected, + `expected concurrency ${expected} for ${cpus} logical CPUs`, + ); + } +}); + +test("resolveTestConcurrency honors positive integer LOOPX_TS_TEST_CONCURRENCY and rejects invalid values", () => { + assert.equal(resolveTestConcurrency({ LOOPX_TS_TEST_CONCURRENCY: "1" }, 16), 1); + assert.equal(resolveTestConcurrency({ LOOPX_TS_TEST_CONCURRENCY: "7" }, 16), 7); + assert.equal( + resolveTestConcurrency({ LOOPX_TS_TEST_CONCURRENCY: " 16 " }, 8), + 16, + ); + + for (const invalid of [ + "", + " ", + "0", + "-4", + "4.5", + "4abc", + "Infinity", + "NaN", + "99999999999999999999", + ]) { + assert.equal( + resolveTestConcurrency({ LOOPX_TS_TEST_CONCURRENCY: invalid }, 16), + 8, + `invalid override ${JSON.stringify(invalid)} must fall back to clamped CPU concurrency`, + ); + } +}); + +test("shouldEnableCompileCache and createScopedCompileCache enforce opt-outs and 0o700 permissions", (t) => { + const tmpRoot = makeTempWorkspace(t); + + assert.equal(shouldEnableCompileCache({}), true); + assert.equal(shouldEnableCompileCache({ NODE_V8_COVERAGE: "" }), true); + assert.equal( + shouldEnableCompileCache({ NODE_COMPILE_CACHE: "/tmp/custom-cache" }), + false, + ); + assert.equal( + shouldEnableCompileCache({ NODE_DISABLE_COMPILE_CACHE: "1" }), + false, + ); + assert.equal( + shouldEnableCompileCache({ NODE_V8_COVERAGE: "/tmp/v8-cov" }), + false, + ); + + const disabled = createScopedCompileCache({ + env: { NODE_DISABLE_COMPILE_CACHE: "1" }, + tmpRoot, + }); + assert.equal(disabled.cacheDir, null); + assert.deepEqual(readdirSync(tmpRoot), []); + + const enabled = createScopedCompileCache({ env: {}, tmpRoot }); + assert.notEqual(enabled.cacheDir, null); + assert.equal(existsSync(enabled.cacheDir!), true); + if (typeof process.getuid === "function") { + assert.equal(lstatSync(enabled.cacheDir!).mode & 0o777, 0o700); + } + enabled.cleanup(); + enabled.cleanup(); + assert.equal(existsSync(enabled.cacheDir!), false); +}); + +test("buildNodeTestArgs resolves sorted defaults, handles flag-only argv, and preserves explicit targets", (t) => { + const repoRoot = makeTempWorkspace(t); + const testDir = join(repoRoot, "tests", "control_plane_ts"); + mkdirSync(testDir, { recursive: true }); + writeFileSync(join(testDir, "zeta.test.ts"), ""); + writeFileSync(join(testDir, "alpha.test.ts"), ""); + writeFileSync(join(testDir, "helper.ts"), ""); + mkdirSync(join(testDir, "nested.test.ts")); + + assert.deepEqual(listDefaultControlPlaneTestFiles(repoRoot), [ + "tests/control_plane_ts/alpha.test.ts", + "tests/control_plane_ts/zeta.test.ts", + ]); + + const flagOnly = buildNodeTestArgs( + ["--test-name-pattern", "matching", "--test-reporter=tap"], + { env: {}, availableParallelism: 12, repoRoot }, + ); + assert.deepEqual(flagOnly, [ + "--no-warnings", + "--experimental-sqlite", + "--experimental-strip-types", + "--test", + "--test-concurrency=6", + "--test-name-pattern", + "matching", + "--test-reporter=tap", + "tests/control_plane_ts/alpha.test.ts", + "tests/control_plane_ts/zeta.test.ts", + ]); + + const explicitTarget = buildNodeTestArgs( + ["--test-concurrency=2", "tests/control_plane_ts/custom.test.ts"], + { env: {}, availableParallelism: 12, repoRoot }, + ); + assert.deepEqual(explicitTarget, [ + "--no-warnings", + "--experimental-sqlite", + "--experimental-strip-types", + "--test", + "--test-concurrency=2", + "tests/control_plane_ts/custom.test.ts", + ]); + + assert.deepEqual( + analyzeCliArgs(["--test-name-pattern", "plain-word"]), + { hasExplicitTestTargets: false, hasExplicitConcurrency: false }, + ); + assert.deepEqual( + analyzeCliArgs(["--", "tests/control_plane_ts/alpha.test.ts"]), + { hasExplicitTestTargets: true, hasExplicitConcurrency: false }, + ); +}); + +test("runner creates and cleans 0o700 NODE_COMPILE_CACHE, respects opt-outs, and propagates args and failures", async (t) => { + const root = makeTempWorkspace(t); + const probeTmp = join(root, "tmp"); + const callerCache = join(root, "caller-cache"); + const coverageDir = join(root, "v8-cov"); + mkdirSync(probeTmp, { mode: 0o700 }); + mkdirSync(callerCache, { mode: 0o700 }); + mkdirSync(coverageDir, { mode: 0o700 }); + + const probeTest = join(root, "probe.test.ts"); + writeFileSync( + probeTest, + `import assert from "node:assert/strict"; +import { lstatSync } from "node:fs"; +import test from "node:test"; + +test("selected pass case", () => { + const cacheDir = process.env.NODE_COMPILE_CACHE ?? null; + const cacheMode = cacheDir ? (lstatSync(cacheDir).mode & 0o777) : null; + console.log("PROBE_ENV=" + JSON.stringify({ cacheDir, cacheMode, cov: process.env.NODE_V8_COVERAGE || null })); +}); + +test("optional fail case", () => { + assert.equal(process.env.LOOPX_PROBE_SHOULD_FAIL, undefined, "intentional probe failure"); +}); +`, + ); + + // 1. Default auto-created compile cache (0o700) + forwarded --test-name-pattern + cleanup. + const autoPass = await runRunnerSubprocess( + ["--test-name-pattern", "selected pass case", probeTest], + cleanRunnerEnv({ TMPDIR: probeTmp, TMP: probeTmp, TEMP: probeTmp }), + ); + assert.equal(autoPass.code, 0, autoPass.stderr); + const autoMatch = autoPass.stdout.match(/PROBE_ENV=(\{.*\})/); + assert.ok(autoMatch, `missing PROBE_ENV in:\n${autoPass.stdout}`); + const autoPayload = JSON.parse(autoMatch[1]!) as { + cacheDir: string | null; + cacheMode: number | null; + cov: string | null; + }; + assert.ok(autoPayload.cacheDir?.startsWith(probeTmp)); + if (typeof process.getuid === "function") { + assert.equal(autoPayload.cacheMode, 0o700); + } + assert.equal(existsSync(autoPayload.cacheDir!), false); + assert.deepEqual(readdirSync(probeTmp), []); + + // 2. Failing test propagates non-zero exit code and still cleans up compile cache. + const autoFail = await runRunnerSubprocess( + ["--test-name-pattern", "optional fail case", probeTest], + cleanRunnerEnv({ + TMPDIR: probeTmp, + TMP: probeTmp, + TEMP: probeTmp, + LOOPX_PROBE_SHOULD_FAIL: "1", + }), + ); + assert.notEqual(autoFail.code, 0); + assert.deepEqual(readdirSync(probeTmp), []); + + // 3. Explicit NODE_COMPILE_CACHE is preserved intact without creating a scoped dir. + const explicit = await runRunnerSubprocess( + ["--test-name-pattern", "selected pass case", probeTest], + cleanRunnerEnv({ + TMPDIR: probeTmp, + TMP: probeTmp, + TEMP: probeTmp, + NODE_COMPILE_CACHE: callerCache, + }), + ); + assert.equal(explicit.code, 0, explicit.stderr); + const explicitPayload = JSON.parse( + explicit.stdout.match(/PROBE_ENV=(\{.*\})/)![1]!, + ) as { cacheDir: string | null }; + assert.equal(explicitPayload.cacheDir, callerCache); + assert.equal(existsSync(callerCache), true); + assert.deepEqual(readdirSync(probeTmp), []); + + // 4. NODE_DISABLE_COMPILE_CACHE=1 and NODE_V8_COVERAGE suppress temp cache creation. + for (const extra of [ + { NODE_DISABLE_COMPILE_CACHE: "1" }, + { NODE_V8_COVERAGE: coverageDir }, + ]) { + const suppressed = await runRunnerSubprocess( + ["--test-name-pattern", "selected pass case", probeTest], + cleanRunnerEnv({ TMPDIR: probeTmp, TMP: probeTmp, TEMP: probeTmp, ...extra }), + ); + assert.equal(suppressed.code, 0, suppressed.stderr); + const suppressedPayload = JSON.parse( + suppressed.stdout.match(/PROBE_ENV=(\{.*\})/)![1]!, + ) as { cacheDir: string | null; cov: string | null }; + assert.equal(suppressedPayload.cacheDir, null); + if ("NODE_V8_COVERAGE" in extra) { + assert.equal(suppressedPayload.cov, coverageDir); + } + assert.deepEqual(readdirSync(probeTmp), []); + } +}); + +test( + "runner cleans NODE_COMPILE_CACHE and propagates signal on SIGTERM", + { skip: process.platform === "win32" }, + async (t) => { + const root = makeTempWorkspace(t); + const probeTmp = join(root, "tmp"); + const readyFile = join(root, "cache-ready.txt"); + const readyTmp = join(root, "cache-ready.tmp"); + mkdirSync(probeTmp, { mode: 0o700 }); + const waitTest = join(root, "wait.test.ts"); + writeFileSync( + waitTest, + `import { renameSync, writeFileSync } from "node:fs"; +import test from "node:test"; +test("blocks until terminated", async () => { + writeFileSync(${JSON.stringify(readyTmp)}, process.env.NODE_COMPILE_CACHE ?? "", "utf8"); + renameSync(${JSON.stringify(readyTmp)}, ${JSON.stringify(readyFile)}); + await new Promise((resolve) => setTimeout(resolve, 30_000)); +}); +`, + ); + + const child = spawn(process.execPath, [RUNNER_SCRIPT, waitTest], { + env: cleanRunnerEnv({ + TMPDIR: probeTmp, + TMP: probeTmp, + TEMP: probeTmp, + }) as NodeJS.ProcessEnv, + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + }); + + let stderr = ""; + child.stderr.setEncoding("utf8"); + child.stderr.on("data", (chunk) => { + stderr += chunk; + }); + + const deadline = Date.now() + 15_000; + while (!existsSync(readyFile)) { + if (Date.now() > deadline) { + child.kill("SIGKILL"); + assert.fail(`timed out waiting for readyFile (${stderr})`); + } + await new Promise((resolve) => setTimeout(resolve, 25)); + } + const cacheDir = readFileSync(readyFile, "utf8").trim(); + assert.ok(cacheDir.length > 0, "expected NODE_COMPILE_CACHE in worker env"); + assert.equal(existsSync(cacheDir), true); + child.kill("SIGTERM"); + + const closed = await new Promise<{ + code: number | null; + signal: NodeJS.Signals | null; + }>((resolve) => { + child.once("close", (code, signal) => resolve({ code, signal })); + }); + assert.equal(closed.signal, "SIGTERM"); + assert.equal(existsSync(cacheDir), false); + assert.deepEqual(readdirSync(probeTmp), []); + }, +); + +test("buildControlPlaneRunPlan partitions heavy conformance tests and falls back to single lane", (t) => { + const repoRoot = makeTempWorkspace(t); + const testDir = join(repoRoot, "tests", "control_plane_ts"); + mkdirSync(testDir, { recursive: true }); + for (const name of [ + "alpha.test.ts", + "authority_store.test.ts", + "nokv_authority_store.test.ts", + "nokv_jsonl_transport.test.ts", + "sqlite_authority_store.test.ts", + "zeta.test.ts", + ]) { + writeFileSync(join(testDir, name), ""); + } + + const twoLane = buildControlPlaneRunPlan([], { + env: {}, + availableParallelism: 18, + repoRoot, + }); + assert.deepEqual(twoLane, { + mode: "two_lane", + totalConcurrency: 8, + heavyConcurrency: 2, + standardConcurrency: 6, + heavyFiles: [...HEAVY_CONTROL_PLANE_TEST_FILES], + standardFiles: [ + "tests/control_plane_ts/alpha.test.ts", + "tests/control_plane_ts/nokv_authority_store.test.ts", + "tests/control_plane_ts/nokv_jsonl_transport.test.ts", + "tests/control_plane_ts/zeta.test.ts", + ], + }); + assert.deepEqual(HEAVY_CONTROL_PLANE_TEST_FILES, [ + "tests/control_plane_ts/sqlite_authority_store.test.ts", + "tests/control_plane_ts/authority_store.test.ts", + ]); + + // Fallback on concurrency < 6, NODE_V8_COVERAGE, explicit flags, or explicit targets. + for (const [argv, env, cpus] of [ + [[], {}, 8], + [[], { LOOPX_TS_TEST_CONCURRENCY: "5" }, 18], + [[], { NODE_V8_COVERAGE: "/tmp/cov" }, 18], + [["--test-reporter=tap"], {}, 18], + [["tests/control_plane_ts/alpha.test.ts"], {}, 18], + ] as const) { + const fallback = buildControlPlaneRunPlan([...argv], { + env: { ...env }, + availableParallelism: cpus, + repoRoot, + }); + assert.equal(fallback.mode, "single"); + } +}); + +test("two-lane runner executes both lanes with shared compile cache and propagates heavy failures", async (t) => { + const root = makeTempWorkspace(t); + const repoRoot = join(root, "repo"); + const probeTmp = join(root, "tmp"); + const testDir = join(repoRoot, "tests", "control_plane_ts"); + mkdirSync(testDir, { recursive: true }); + mkdirSync(probeTmp, { mode: 0o700 }); + + const envLog = join(root, "lanes.jsonl"); + const passTemplate = (label: string) => `import { appendFileSync } from "node:fs"; +import test from "node:test"; +test("${label}", () => { + appendFileSync(${JSON.stringify(envLog)}, JSON.stringify({ + label: ${JSON.stringify(label)}, + cache: process.env.NODE_COMPILE_CACHE ?? null, + }) + "\\n"); +}); +`; + writeFileSync(join(testDir, "sqlite_authority_store.test.ts"), passTemplate("heavy-sqlite")); + writeFileSync(join(testDir, "authority_store.test.ts"), passTemplate("heavy-file")); + writeFileSync(join(testDir, "alpha.test.ts"), passTemplate("std-alpha")); + writeFileSync(join(testDir, "beta.test.ts"), passTemplate("std-beta")); + + const ok = await runControlPlaneTests([], { + env: cleanRunnerEnv({ TMPDIR: probeTmp, TMP: probeTmp, TEMP: probeTmp }), + availableParallelism: 18, + repoRoot, + tmpRoot: probeTmp, + }); + assert.equal(ok.status, 0); + assert.equal(ok.signal, null); + assert.notEqual(ok.cacheDir, null); + assert.equal(existsSync(ok.cacheDir!), false); + assert.deepEqual(readdirSync(probeTmp), []); + + const records = readFileSync(envLog, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line) as { label: string; cache: string | null }); + assert.deepEqual( + records.map((entry) => entry.label).sort(), + ["heavy-file", "heavy-sqlite", "std-alpha", "std-beta"], + ); + assert.ok(records.every((entry) => entry.cache === ok.cacheDir)); + + // Failing heavy-lane file must fail the overall run even when standard lane passes. + writeFileSync( + join(testDir, "authority_store.test.ts"), + `import assert from "node:assert/strict"; +import test from "node:test"; +test("heavy fail", () => { assert.equal(1, 2); }); +`, + ); + const failed = await runControlPlaneTests([], { + env: cleanRunnerEnv({ TMPDIR: probeTmp, TMP: probeTmp, TEMP: probeTmp }), + availableParallelism: 18, + repoRoot, + tmpRoot: probeTmp, + }); + assert.notEqual(failed.status, 0); + assert.deepEqual(readdirSync(probeTmp), []); +}); diff --git a/tests/fixtures/nokv_fake_sdk/nokv/__init__.py b/tests/fixtures/nokv_fake_sdk/nokv/__init__.py index fe1ebaf403..c44b64710c 100644 --- a/tests/fixtures/nokv_fake_sdk/nokv/__init__.py +++ b/tests/fixtures/nokv_fake_sdk/nokv/__init__.py @@ -63,8 +63,7 @@ def __init__(self, message: str, expected: str) -> None: class Client: def __init__(self, **_values: Any) -> None: - self._bytes: bytes | None = None - self._generation: int | None = None + self._objects: dict[tuple[str, str], tuple[bytes, int]] = {} def find_workspaces(self, **_values: Any) -> dict[str, Any]: return { @@ -80,15 +79,17 @@ def find_workspaces(self, **_values: Any) -> dict[str, Any]: } def read(self, workbench: str, path: str) -> dict[str, Any]: - if self._bytes is None or self._generation is None: + entry = self._objects.get((workbench, path)) + if entry is None: raise FileNotFoundError("missing") + raw, generation = entry return { - "bytes": self._bytes, + "bytes": raw, "metadata": { "workbench": workbench, "path": path, "workspace_incarnation_id": _CURRENT_INCARNATION, - "generation": self._generation, + "generation": generation, }, } @@ -115,19 +116,22 @@ def publish_bytes( def _publish( self, workbench: str, path: str, payload: bytes, values: dict[str, Any] ) -> dict[str, Any]: + key = (workbench, path) + existing = self._objects.get(key) + current_generation = existing[1] if existing is not None else None expected = values["expected_generation"] - if expected is None and self._generation is not None: + if expected is None and current_generation is not None: raise FileExistsError("already exists") - if expected is not None and expected != self._generation: + if expected is not None and expected != current_generation: raise RuntimeError("generation conflict") - self._generation = (self._generation or 0) + 1 - self._bytes = payload + next_generation = (current_generation or 0) + 1 + self._objects[key] = (payload, next_generation) return { "operation_id": values["operation_id"], "artifact_revision_id": values["artifact_revision_id"], "workbench": workbench, "path": path, - "generation": self._generation, + "generation": next_generation, } diff --git a/tsconfig.control-plane.json b/tsconfig.control-plane.json index 45cf9059b5..d7147f4a06 100644 --- a/tsconfig.control-plane.json +++ b/tsconfig.control-plane.json @@ -128,6 +128,7 @@ "tests/control_plane_ts/goal_instance_identity.test.ts", "tests/control_plane_ts/chat_session_lifecycle.test.ts", "tests/control_plane_ts/test_python_runtime.test.ts", + "tests/control_plane_ts/run_control_plane_ts_tests.test.ts", "tests/control_plane_ts/direction_authority.test.ts", "tests/control_plane_ts/direction_baseline.test.ts", "tests/control_plane_ts/material_wave_ranking.test.ts",