build: separate runtime artifacts and supervise command ownership

This commit is contained in:
morluto
2026-10-09 20:11:17 +08:00
parent c8544b1574
commit abc4f47683
32 changed files with 795 additions and 786 deletions
@@ -1,63 +0,0 @@
import { execFile } from "node:child_process";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { z } from "zod";
import { GENERATED_MCP_TOOL_CATALOG } from "../../src/generatedMcpToolCatalog.js";
const execute = promisify(execFile);
const fixture = fileURLToPath(
new URL("../fixtures/contractPresentation.mjs", import.meta.url),
);
const resultSchema = z.object({
catalog: z.array(
z.object({
name: z.string(),
inputSchema: z.record(z.string(), z.unknown()),
outputSchema: z.record(z.string(), z.unknown()),
}),
),
responses: z.array(
z.object({ name: z.string(), response: z.record(z.string(), z.unknown()) }),
),
});
it.each(["original", "reversed"])(
"preserves advertised schemas and handler meaning with %s presentation",
async (presentation) => {
const { stdout } = await execute(
process.execPath,
[fixture, presentation],
{
timeout: 20_000,
maxBuffer: 16 * 1024 * 1024,
},
);
const result = resultSchema.parse(JSON.parse(stdout));
expect(result.catalog).toHaveLength(GENERATED_MCP_TOOL_CATALOG.length);
expect(new Set(result.catalog.map(({ name }) => name))).toEqual(
new Set(GENERATED_MCP_TOOL_CATALOG.map(({ name }) => name)),
);
for (const advertised of result.catalog) {
const canonical = GENERATED_MCP_TOOL_CATALOG.find(
({ name }) => name === advertised.name,
);
expect(advertised.inputSchema).toEqual(canonical?.inputSchema);
expect(advertised.outputSchema).toEqual(canonical?.outputSchema);
}
for (const { name, response } of result.responses) {
if (name === "reconcile_javascript_runtime") {
expect(response.isError).not.toBe(true);
expect(response.structuredContent).toMatchObject({
evidence: { operation: name },
});
} else {
expect(response.isError, name).toBe(true);
expect(response.structuredContent, name).toMatchObject({
error: { details: { operation: name } },
});
}
}
},
);
@@ -0,0 +1,56 @@
import { execFile } from "node:child_process";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { z } from "zod";
import { GENERATED_MCP_TOOL_CATALOG } from "../../fixtures/mcpToolCatalog.js";
const execute = promisify(execFile);
const fixture = fileURLToPath(
new URL("../../fixtures/contractPresentation.mjs", import.meta.url),
);
const resultSchema = z.object({
catalog: z.array(
z.object({
name: z.string(),
inputSchema: z.record(z.string(), z.unknown()),
outputSchema: z.record(z.string(), z.unknown()),
}),
),
responses: z.array(
z.object({ name: z.string(), response: z.record(z.string(), z.unknown()) }),
),
});
it("preserves advertised schemas and handler meaning when presentation order changes", async () => {
const { stdout } = await execute(process.execPath, [fixture, "reversed"], {
timeout: 20_000,
maxBuffer: 16 * 1024 * 1024,
});
const result = resultSchema.parse(JSON.parse(stdout));
expect(result.catalog).toHaveLength(GENERATED_MCP_TOOL_CATALOG.length);
expect(new Set(result.catalog.map(({ name }) => name))).toEqual(
new Set(GENERATED_MCP_TOOL_CATALOG.map(({ name }) => name)),
);
for (const advertised of result.catalog) {
const canonical = GENERATED_MCP_TOOL_CATALOG.find(
({ name }) => name === advertised.name,
);
expect(advertised.inputSchema).toEqual(canonical?.inputSchema);
expect(advertised.outputSchema).toEqual(canonical?.outputSchema);
}
for (const { name, response } of result.responses) {
if (name === "reconcile_javascript_runtime") {
expect(response.isError).not.toBe(true);
expect(response.structuredContent).toMatchObject({
evidence: { operation: name },
});
} else {
expect(response.isError, name).toBe(true);
expect(response.structuredContent, name).toMatchObject({
error: { details: { operation: name } },
});
}
}
});
+23 -3
View File
@@ -7,7 +7,7 @@ import { z } from "zod";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { emptyArraySchema } from "../../../src/domain/emptyArraySchema.js";
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../../fixtures/mcpToolCatalog.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
interface ToolSchemas {
@@ -94,6 +94,23 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
idempotentHint: false,
openWorldHint: false,
},
export_web_scripts: {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: false,
},
capture_process_scenario: {
openWorldHint: true,
},
export_evidence_bundle: {
readOnlyHint: false,
destructiveHint: true,
},
import_evidence_bundle: {
readOnlyHint: false,
destructiveHint: false,
},
} as const;
for (const [name, annotations] of Object.entries(expected))
@@ -383,8 +400,11 @@ describe("MCP root input schemas", () => {
for (const contract of TOOL_CONTRACTS) {
const inputSchema = advertised.get(contract.name)!.inputSchema;
expect(inputSchema.type, contract.name).toBe("object");
expect(inputSchema.properties, contract.name).toBeDefined();
expect(inputSchema.anyOf, contract.name).toBeUndefined();
expect(
inputSchema.properties !== undefined ||
Array.isArray(inputSchema.anyOf),
contract.name,
).toBe(true);
const validate = ajv.compile(inputSchema);
for (const example of contract.examples)
expect(
@@ -1,240 +0,0 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { browserCaptureComparisonInputSchema } from "../../../src/domain/browserCaptureComparison.js";
import { webPageInspectionSchema } from "../../../src/domain/browserObservation.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
function resolveLocalReference(root: unknown, reference: string): unknown {
if (reference === "#") return root;
if (!reference.startsWith("#/")) return undefined;
let current = root;
for (const part of reference.slice(2).split("/")) {
const key = part.replaceAll("~1", "/").replaceAll("~0", "~");
if (!isRecord(current) || !Object.hasOwn(current, key)) return undefined;
current = current[key];
}
return current;
}
// Count object/array and composition levels, following references per path.
// Definitions, property maps, and literal example/default data are not levels.
function inputDepth(
schema: unknown,
root: unknown = schema,
activeReferences: readonly string[] = [],
): number {
if (!isRecord(schema)) return 0;
let referenceDepth = 0;
if (typeof schema.$ref === "string") {
if (activeReferences.includes(schema.$ref)) return Number.POSITIVE_INFINITY;
const target = resolveLocalReference(root, schema.$ref);
if (target === undefined) return Number.POSITIVE_INFINITY;
referenceDepth = inputDepth(target, root, [
...activeReferences,
schema.$ref,
]);
}
const childDepths: number[] = [];
for (const key of ["properties", "patternProperties", "dependentSchemas"]) {
const group = schema[key];
if (isRecord(group))
for (const child of Object.values(group))
childDepths.push(inputDepth(child, root, activeReferences));
}
for (const key of [
"items",
"additionalProperties",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"unevaluatedProperties",
"unevaluatedItems",
])
childDepths.push(inputDepth(schema[key], root, activeReferences));
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
const children = schema[key];
if (Array.isArray(children))
for (const child of children)
childDepths.push(inputDepth(child, root, activeReferences));
}
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
const container = types.includes("object") || types.includes("array") ? 1 : 0;
const composition = ["anyOf", "oneOf", "allOf"].some((key) =>
Array.isArray(schema[key]),
)
? 1
: 0;
return Math.max(
referenceDepth,
container + composition + Math.max(0, ...childDepths),
);
}
function inputDepthViolations(
tools: readonly { name: string; inputSchema: unknown }[],
) {
return tools.flatMap(({ name, inputSchema }) => {
const depth = inputDepth(inputSchema);
return depth > 10 ? [{ name, depth }] : [];
});
}
async function withCatalog(
verify: (client: Client, calls: ReadonlyMap<string, number>) => Promise<void>,
): Promise<void> {
const server = new McpServer({ name: "wire-limits", version: "0" });
const calls = new Map<string, number>();
for (const contract of TOOL_CONTRACTS)
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async () => {
calls.set(contract.name, (calls.get(contract.name) ?? 0) + 1);
return { content: [], isError: true };
},
);
const client = new Client({ name: "wire-limits", version: "0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await verify(client, calls);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
}
describe("complete catalog input compatibility profile (#919)", () => {
it("follows shared and escaped references without treating data as schemas", () => {
const diamond = {
type: "object",
properties: {
left: { $ref: "#/$defs/a~1b~0c" },
right: { $ref: "#/$defs/a~1b~0c" },
},
$defs: {
"a/b~c": { type: "object", properties: { id: { type: "string" } } },
unused: { $ref: "#/$defs/unused" },
},
examples: [{ $ref: "#" }],
default: { $ref: "#" },
};
expect(inputDepth(diamond)).toBe(2);
expect(
inputDepth({ type: "object", properties: { child: { $ref: "#" } } }),
).toBe(Number.POSITIVE_INFINITY);
expect(
inputDepth({
type: "object",
properties: {
values: {
anyOf: [
{ type: "array", items: { type: "object" } },
{ type: "null" },
],
},
},
}),
).toBe(4);
});
it("keeps every live and generated input within ten structural levels", async () => {
await withCatalog(async (client) => {
const { tools } = await client.listTools();
expect(tools.map(({ name }) => name).sort()).toEqual(
TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
expect(inputDepthViolations(tools)).toEqual([]);
expect(inputDepthViolations(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
});
});
it("describes capture round trips without altering domain or scenario schemas", () => {
const contract = TOOL_CONTRACTS.find(
({ name }) => name === "compare_web_captures",
);
if (contract === undefined)
throw new Error("Missing capture comparison contract");
const original = z.toJSONSchema(browserCaptureComparisonInputSchema, {
io: "input",
});
const projected = z.toJSONSchema(contract.inputSchema, { io: "input" });
expect(inputDepth(original)).toBeGreaterThan(10);
expect(inputDepth(projected)).toBeLessThanOrEqual(10);
expect(isRecord(original.properties)).toBe(true);
expect(isRecord(projected.properties)).toBe(true);
if (!isRecord(original.properties) || !isRecord(projected.properties))
throw new Error("Missing comparison properties");
for (const key of ["normalization"])
expect(projected.properties[key], key).toEqual(original.properties[key]);
expect(z.toJSONSchema(webPageInspectionSchema).properties).toHaveProperty(
"network",
);
for (const example of contract.examples)
expect(contract.inputSchema.parse(example.input)).toEqual(
browserCaptureComparisonInputSchema.parse(example.input),
);
const example = contract.examples[0];
if (example === undefined) throw new Error("Missing scenario example");
for (const malformed of [
{ before_scenario: {}, after_scenario: {} },
{
...example.input,
before: { inspection: {} },
after: { inspection: {} },
},
{ ...example.input, __unexpected_root_key__: true },
]) {
const originalResult =
browserCaptureComparisonInputSchema.safeParse(malformed);
const projectedResult = contract.inputSchema.safeParse(malformed);
expect(originalResult.success).toBe(false);
expect(projectedResult.success).toBe(false);
if (!originalResult.success && !projectedResult.success)
expect(projectedResult.error.issues).toEqual(
originalResult.error.issues,
);
}
});
it("rejects incomplete round-trip payloads before invoking the handler", async () => {
await withCatalog(async (client, calls) => {
const tool = (await client.listTools()).tools.find(
({ name }) => name === "compare_web_captures",
);
if (tool === undefined)
throw new Error("Missing advertised comparison tool");
const incomplete = {
before: { inspection: {} },
after: { inspection: {} },
};
const validate = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(tool.inputSchema);
expect(validate(incomplete)).toBe(true);
expect(
browserCaptureComparisonInputSchema.safeParse(incomplete).success,
).toBe(false);
const result = await client.callTool({
name: tool.name,
arguments: incomplete,
});
expect(result.isError).toBe(true);
expect(calls.get(tool.name) ?? 0).toBe(0);
});
});
});
@@ -3,58 +3,6 @@ import { expect, it } from "vitest";
import { auxiliaryAnalysisProviderDeclarations } from "../../../src/composition/auxiliaryAnalysisProviders.js";
import { LazyAnalysisProvider } from "../../../src/application/binary/LazyAnalysisProvider.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { GENERATED_AUXILIARY_PROVIDERS } from "../../../src/generatedMcpToolCatalog.js";
it.each(["darwin", "linux", "win32"] as const)(
"preserves canonical auxiliary metadata and host facts on %s",
async (platform) => {
const declarations = auxiliaryAnalysisProviderDeclarations(platform);
expect(declarations.map(({ identity }) => identity)).toEqual(
GENERATED_AUXILIARY_PROVIDERS.map(({ identity }) => identity),
);
const operations = new Set<string>();
for (const declaration of declarations) {
const canonical = GENERATED_AUXILIARY_PROVIDERS.find(
({ identity }) => identity.id === declaration.identity.id,
);
if (canonical === undefined)
throw new Error("Missing canonical provider");
const expected = canonical.capabilities.map((capability) => {
if (platform === "darwin") return capability;
if (capability.provider.id === "native-macos")
return {
...capability,
available: false,
availabilityCode: "unsupported_host",
reason: "Native macOS utilities require macOS.",
};
if (capability.operation === "inspect_asset_catalog")
return {
...capability,
available: false,
availabilityCode: "unsupported_host",
reason: "Apple asset catalogs require macOS assetutil.",
};
return capability;
});
expect(declaration.capabilities).toEqual(expected);
const first = await declaration.load();
const second = await declaration.load();
expect(first).not.toBe(second);
expect(first.identity()).toEqual(declaration.identity);
expect(first.capabilities()).toEqual(declaration.capabilities);
expect(second.capabilities()).toEqual(declaration.capabilities);
for (const capability of declaration.capabilities) {
expect(operations.has(capability.operation)).toBe(false);
operations.add(capability.operation);
expect(Object.isFrozen(capability)).toBe(true);
expect(Object.isFrozen(capability.effects)).toBe(true);
expect(Object.isFrozen(capability.limitations)).toBe(true);
}
}
expect(operations.has("inspect_native_dispatch_metadata")).toBe(true);
},
);
it("keeps declaration discovery and client creation lazy and independently owned", async () => {
const target = await parseBinaryTarget(process.execPath);
@@ -40,6 +40,25 @@ describe("development test selection", () => {
expect(plan.vitestArguments).not.toContain("--changed");
});
it("prepares test catalogs and managed evidence only for their consumers", () => {
const ordinary = developmentTestPlan(
parseDevelopmentTestRequest("focused", [
"tests/boundary/mcp/sessionMcp.test.ts",
]),
);
expect(ordinary.artifactTasks).toEqual([]);
const consumers = developmentTestPlan(
parseDevelopmentTestRequest("focused", [
"tests/boundary/mcp/toolSchemaValidity.test.ts",
"tests/boundary/filesystem/setupSkill.test.ts",
]),
);
expect(consumers.artifactTasks).toEqual([
"artifacts:mcp-catalog",
"artifacts:managed-evidence",
]);
});
it("uses the resolved branch merge base for committed source changes", () => {
const request = parseDevelopmentTestRequest("changed", ["--base", "main"]);
const plan = developmentTestPlan(request, "a".repeat(40));
-10
View File
@@ -159,18 +159,8 @@ describe("incremental module import boundaries", () => {
["src/domain/probe.test.ts", "../dotnet/ManagedMemberInspector.js", false],
["src/server/probe.ts", "../composition/android.js", true],
["src/application/probe.ts", "../browser/CdpCaptureValues.js", true],
["src/hopper/probe.ts", "../generatedMcpToolCatalog.js", false],
["src/ghidra/probe.ts", "../generatedMcpToolCatalog.ts", false],
["src/ida/probe.ts", "../generatedMcpToolCatalog.js", false],
["src/artifacts/probe.ts", "../generatedMcpToolCatalog.js", false],
["src/browser/probe.ts", "../generatedMcpToolCatalog.js", false],
["src/ghidra/probe.ts", "../generatedPackageMetadata.js", true],
["src/hopper/probe.ts", "../contracts/officialToolContracts.js", true],
[
"src/application/binary/probe.ts",
"../../generatedMcpToolCatalog.js",
true,
],
])("checks %s importing %s", async (file, dependency, allowed) => {
const temporary = await createTestTempDirectory("rea-module-boundary-");
const fixture = join(temporary, file);
+2 -1
View File
@@ -1,3 +1,4 @@
import { silentLogger } from "../../dist/logger.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { BROWSER_TOOL_CONTRACTS } from "../../dist/contracts/browserToolContracts.js";
@@ -22,7 +23,7 @@ if (process.argv[2] === "reversed") {
const { createServer } = await import("../../dist/server/createServer.js");
const config = parseConfig({});
if (!config.ok) throw config.error;
const session = createBinarySession(config.value);
const session = createBinarySession(config.value, silentLogger, {});
const server = createServer(session, session);
const client = new Client({ name: "contract-presentation", version: "1" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+65
View File
@@ -0,0 +1,65 @@
import { readFileSync } from "node:fs";
import type { ToolAnnotations } from "@modelcontextprotocol/server";
import type { CapabilityDescriptor } from "../../src/application/AnalysisProvider.js";
import type { ToolKind } from "../../src/contracts/toolContractTypes.js";
import type { ToolEffects } from "../../src/contracts/toolEffects.js";
interface GeneratedTool {
readonly name: string;
readonly analysisOperation: CapabilityDescriptor["operation"] | null;
readonly title: string;
readonly description: string;
readonly kind: ToolKind;
readonly requiresSession: boolean;
readonly inputSchema: Readonly<Record<string, unknown>>;
readonly outputSchema: Readonly<Record<string, unknown>>;
readonly annotations: ToolAnnotations;
readonly effects: ToolEffects;
}
interface GeneratedPayload {
readonly catalog: readonly GeneratedTool[];
}
const generatedPayload: unknown = JSON.parse(
readFileSync(
new URL("../../.cache/mcp-tool-catalog.json", import.meta.url),
"utf8",
),
);
if (!isGeneratedPayload(generatedPayload))
throw new TypeError(
"Generated MCP catalog payload is invalid; run npm run mcp-catalog:generate",
);
/** Canonical schemas advertised through the pinned MCP SDK. */
export const GENERATED_MCP_TOOL_CATALOG = generatedPayload.catalog;
function isGeneratedPayload(value: unknown): value is GeneratedPayload {
return (
isRecord(value) &&
Array.isArray(value.catalog) &&
value.catalog.every(isGeneratedTool)
);
}
function isGeneratedTool(value: unknown): value is GeneratedTool {
return (
isRecord(value) &&
typeof value.name === "string" &&
(typeof value.analysisOperation === "string" ||
value.analysisOperation === null) &&
typeof value.title === "string" &&
typeof value.description === "string" &&
typeof value.kind === "string" &&
typeof value.requiresSession === "boolean" &&
isRecord(value.inputSchema) &&
isRecord(value.outputSchema) &&
isRecord(value.annotations) &&
isRecord(value.effects)
);
}
function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+207 -41
View File
@@ -1,58 +1,224 @@
import { spawn } from "node:child_process";
import { access } from "node:fs/promises";
import { readFile, utimes, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { setTimeout as delay } from "node:timers/promises";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
const runnerPath = fileURLToPath(
new URL("../../scripts/run-exclusive.mjs", import.meta.url),
);
it.runIf(process.platform !== "win32")(
"escalates cancellation when an owned command ignores SIGTERM",
"holds ownership until an uncooperative command has finished cancellation",
async () => {
const lockName = `runner-cancel-${String(process.pid)}`;
const lockPath = join(".cache", "rea-command-locks", `${lockName}.lock`);
const runner = spawn(
process.execPath,
[
"scripts/run-exclusive.mjs",
lockName,
process.execPath,
"-e",
'process.on("SIGTERM", () => {}); process.stdout.write("ready"); setInterval(() => {}, 1000);',
],
{ stdio: ["ignore", "pipe", "pipe"] },
const directory = await createTestTempDirectory("rea-runner-cancel-");
const runner = launch(
directory,
'process.on("SIGTERM", () => {}); process.stdout.write("ready"); setInterval(() => {}, 1000);',
);
let output = "";
const ready = new Promise<void>((resolveReady) => {
runner.stdout.on("data", (chunk) => {
output += chunk.toString();
if (output.includes("ready")) resolveReady();
});
});
const closed = new Promise<{
code: number | null;
signal: NodeJS.Signals | null;
}>((resolveClosed) => {
runner.once("close", (code, signal) => resolveClosed({ code, signal }));
});
try {
await withTimeout(ready, "runner child did not start");
runner.kill("SIGTERM");
const result = await withTimeout(
closed,
"runner did not finish cancellation",
);
expect(result).toEqual({ code: 143, signal: null });
await runner.ready;
runner.child.kill("SIGTERM");
expect(await runner.closed).toMatchObject({ code: 143, signal: null });
const replacement = launch(directory, 'process.stdout.write("ready");');
expect(await replacement.closed).toMatchObject({ code: 0, signal: null });
} finally {
if (runner.exitCode === null) runner.kill("SIGKILL");
await withTimeout(closed, "runner cleanup did not finish");
if (runner.child.exitCode === null) runner.child.kill("SIGKILL");
await runner.closed;
}
expect(output).toContain("ready");
await expect(access(lockPath)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(process.platform !== "win32")(
"retains the lock when the command exits but a descendant ignores cancellation",
async () => {
const directory = await createTestTempDirectory("rea-runner-descendant-");
const pidPath = join(directory, "descendant.pid");
const activityPath = join(directory, "activity.log");
const descendant = `
const fs = require("node:fs");
process.on("SIGTERM", () => {});
fs.writeFileSync(${JSON.stringify(activityPath)}, "active\\n");
fs.writeFileSync(${JSON.stringify(pidPath)}, String(process.pid));
setInterval(() => fs.appendFileSync(${JSON.stringify(activityPath)}, "active\\n"), 20);
`;
const runner = launch(
directory,
`
const fs = require("node:fs");
require("node:child_process").spawn(process.execPath, ["-e", ${JSON.stringify(descendant)}], { stdio: "ignore" });
const ready = setInterval(() => {
if (fs.existsSync(${JSON.stringify(pidPath)})) {
clearInterval(ready);
process.stdout.write("ready");
}
}, 10);
setInterval(() => {}, 1000);
`,
);
let descendantPid: number | undefined;
try {
await runner.ready;
descendantPid = Number(await readFile(pidPath, "utf8"));
runner.child.kill("SIGTERM");
const contender = launch(
directory,
'process.stdout.write("unexpected");',
);
expect(await contender.closed).toMatchObject({
code: 1,
stderr: expect.stringContaining("already running"),
});
expect(await runner.closed).toMatchObject({ code: 143 });
const stopped = await readFile(activityPath, "utf8");
await delay(100);
expect(await readFile(activityPath, "utf8")).toBe(stopped);
expect(
await launch(directory, 'process.stdout.write("done");').closed,
).toMatchObject({ code: 0 });
} finally {
if (runner.child.exitCode === null) runner.child.kill("SIGTERM");
await runner.closed;
// Also clean up when this regression is run against the broken runner.
if (descendantPid !== undefined) stopIfPresent(descendantPid);
}
},
);
it("does not treat an old database timestamp as permission to replace a live owner", async () => {
const directory = await createTestTempDirectory("rea-runner-live-");
const runner = launch(
directory,
'process.stdout.write("ready"); setTimeout(() => {}, 1500);',
);
try {
await runner.ready;
const old = new Date("2000-01-01T00:00:00Z");
await utimes(
join(directory, ".cache/rea-command-locks/test.sqlite"),
old,
old,
);
const contender = launch(directory, 'process.stdout.write("unexpected");');
expect(await contender.closed).toMatchObject({
code: 1,
stderr: expect.stringContaining("already running"),
stdout: "",
});
expect(await runner.closed).toMatchObject({ code: 0 });
} finally {
if (runner.child.exitCode === null) runner.child.kill("SIGKILL");
await runner.closed;
}
});
it.runIf(process.platform !== "win32")(
"recovers after abrupt owner death and keeps simultaneous contenders exclusive",
async () => {
const directory = await createTestTempDirectory("rea-runner-recover-");
// Killing the public runner disconnects its supervisor, which retains
// ownership while cancelling the group before automatic OS lock release.
const interrupted = launch(
directory,
'process.on("SIGTERM", () => {}); process.stdout.write("ready"); setInterval(() => {}, 1000);',
);
await interrupted.ready;
interrupted.child.kill("SIGKILL");
expect(await interrupted.closed).toMatchObject({
code: null,
signal: "SIGKILL",
});
const activityPath = join(directory, "active");
const logPath = join(directory, "activity.log");
await writeFile(logPath, "");
const command = `
const fs = require("node:fs");
const active = ${JSON.stringify(activityPath)};
const log = ${JSON.stringify(logPath)};
try { fs.closeSync(fs.openSync(active, "wx")); }
catch { process.stderr.write("commands overlapped"); process.exit(77); }
fs.appendFileSync(log, "start\\n");
setTimeout(() => {
fs.appendFileSync(log, "end\\n");
fs.unlinkSync(active);
}, 250);
`;
const results = await Promise.all(
Array.from({ length: 8 }, () => launch(directory, command).closed),
);
expect(results.some(({ code }) => code === 0)).toBe(true);
for (const result of results) {
expect([0, 1]).toContain(result.code);
if (result.code === 1) expect(result.stderr).toContain("already running");
expect(result.stderr).not.toContain("commands overlapped");
}
const events = (await readFile(logPath, "utf8")).trim().split("\n");
expect(events.length).toBeGreaterThan(0);
for (let index = 0; index < events.length; index += 2)
expect(events.slice(index, index + 2)).toEqual(["start", "end"]);
expect(
await launch(directory, 'process.stdout.write("done");').closed,
).toMatchObject({ code: 0, stdout: "done" });
},
);
function stopIfPresent(pid: number): void {
try {
process.kill(pid, "SIGKILL");
} catch (cause) {
if (
!(cause instanceof Error) ||
!("code" in cause) ||
cause.code !== "ESRCH"
)
throw cause;
}
}
function launch(directory: string, command: string) {
const child = spawn(
process.execPath,
[runnerPath, "test", process.execPath, "-e", command],
{ cwd: directory, stdio: ["ignore", "pipe", "pipe"] },
);
let stdout = "";
let stderr = "";
let notifyReady: (() => void) | undefined;
const ready = withTimeout(
new Promise<void>((resolveReady) => {
notifyReady = resolveReady;
}),
"runner child did not start",
);
// Some scenarios intentionally never print a ready marker.
void ready.catch(() => {});
child.stdout.on("data", (chunk) => {
stdout += chunk.toString();
if (stdout.includes("ready")) notifyReady?.();
});
child.stderr.on("data", (chunk) => (stderr += chunk.toString()));
const closed = withTimeout(
new Promise<{
code: number | null;
signal: NodeJS.Signals | null;
stdout: string;
stderr: string;
}>((resolveClosed, reject) => {
child.once("error", reject);
child.once("close", (code, signal) => {
notifyReady?.();
resolveClosed({ code, signal, stdout, stderr });
});
}),
"runner did not finish",
);
return { child, ready, closed };
}
function withTimeout<T>(promise: Promise<T>, message: string): Promise<T> {
let timeout: NodeJS.Timeout | undefined;
return Promise.race([