Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
5ee7ab5
fix(mcp): address remaining MCP_harden inline review follow-ups
tonythethompson Aug 8, 2026
ffd9d35
fix: Delay malformed lock reclamation
qodo-code-review[bot] Aug 8, 2026
6c6a4d3
fix(mcp): publish smoke lock PID atomically and grace empty reclaim
tonythethompson Aug 8, 2026
a5fdac8
fix(mcp): publish smoke locks via temp file and linkSync
tonythethompson Aug 8, 2026
11aea72
Merge branch 'main' into fix/mcp-harden-inline-followups
tonythethompson Aug 8, 2026
89e08ab
[CodeFactor] Apply fixes
code-factor Aug 8, 2026
3d370b5
fix(mcp): treat partial lock PIDs as incomplete and harden stub tests
tonythethompson Aug 8, 2026
8080cd9
test(mcp): cover smoke lock EPERM reclaim falling through to sleep
tonythethompson Aug 8, 2026
4ae7cf9
test(mcp): reuse makeFs for ENOTSUP smoke lock fallback coverage
tonythethompson Aug 8, 2026
002e739
fix(mcp): compare lock body before reclaim unlink
tonythethompson Aug 8, 2026
70f8a8f
fix(mcp): return stub timeout failures and serialize lock reclaim
tonythethompson Aug 8, 2026
90f515c
fix(mcp): recover orphaned smoke-lock reclaim mutex
tonythethompson Aug 8, 2026
f4a7a8a
fix(mcp): honor stub deadline remaining sleep and drain test teardown
tonythethompson Aug 8, 2026
a80371e
fix(mcp): never age-clear live reclaim mutexes; re-verify gate ownership
tonythethompson Aug 8, 2026
031d14c
fix(mcp): age-clear incomplete orphaned reclaim mutexes after grace
tonythethompson Aug 8, 2026
09a14ac
fix(mcp): publish reclaim gate via temp+link like the main lock
tonythethompson Aug 8, 2026
6a8834c
fix(mcp): publish lock via COPYFILE_EXCL when hardlinks fail
tonythethompson Aug 8, 2026
db80284
fix(mcp): type smoke-lock copyFileSync mock as PathLike
tonythethompson Aug 8, 2026
e0d2d45
fix(mcp): invoke mcporter via node argv on Windows smoke
tonythethompson Aug 8, 2026
1f90b97
Update vite.config.ts
tonythethompson Aug 8, 2026
ada73eb
fix(mcp): publish smoke locks via rename when hardlinks fail
tonythethompson Aug 8, 2026
de08c25
fix(mcp): never POSIX-rename over a live smoke lock
tonythethompson Aug 8, 2026
c9ee116
fix(mcp): harden smoke lock publish and agent-smoke helpers
tonythethompson Aug 8, 2026
a14699d
fix(mcp): never age-reclaim incomplete smoke lock bodies
tonythethompson Aug 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions scripts/mcp-agent-smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,7 @@ async function cleanup() {
function failExitCode(signal) {
if (signal === "SIGINT") return 130;
if (signal === "SIGTERM") return 143;
if (signal === "SIGHUP") return 129;
return STRICT ? 1 : 0;
}

Expand Down
32 changes: 25 additions & 7 deletions scripts/studioConfigSmokeLock.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
mkdirSync,
openSync,
readFileSync,
rmSync,
rmdirSync,
statSync,
unlinkSync,
writeFileSync,
} from "node:fs";
Expand All @@ -35,6 +36,7 @@ export function isProcessAlive(pid) {
* closeSync?: typeof closeSync,
* writeFileSync?: typeof writeFileSync,
* readFileSync?: typeof readFileSync,
* statSync?: typeof statSync,
* unlinkSync?: typeof unlinkSync,
* mkdirSync?: typeof mkdirSync,
* isProcessAlive?: (pid: number) => boolean,
Expand All @@ -50,6 +52,7 @@ export async function acquireStudioConfigSmokeLock(lockPath, deps = {}) {
const close = deps.closeSync ?? closeSync;
const write = deps.writeFileSync ?? writeFileSync;
const read = deps.readFileSync ?? readFileSync;
const stat = deps.statSync ?? statSync;
const unlink = deps.unlinkSync ?? unlinkSync;
const mkdir = deps.mkdirSync ?? mkdirSync;
const alive = deps.isProcessAlive ?? isProcessAlive;
Expand Down Expand Up @@ -87,13 +90,28 @@ export async function acquireStudioConfigSmokeLock(lockPath, deps = {}) {
try {
Comment thread
tonythethompson marked this conversation as resolved.
Resolved
const body = read(lockPath, "utf8");
const holder = Number.parseInt(String(body).trim().split(/\r?\n/)[0] ?? "", 10);
if (Number.isFinite(holder) && !alive(holder)) {
// A freshly-created lock can be temporarily empty before its creator
// writes the PID. Give malformed locks a grace period before reclaiming
// them, while still reclaiming dead finite holders immediately.
const malformed = !Number.isFinite(holder);
let reclaimable = !malformed && !alive(holder);
if (malformed) {
try {
const ageMs = Date.now() - stat(lockPath).mtimeMs;
reclaimable = ageMs >= Math.max(1_000, pollMs * 4);
} catch {
/* unable to establish age — leave the lock in place */
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Only skip the poll sleep after unlink succeeds so failed reclaim
// cannot busy-spin.
if (reclaimable) {
try {
unlink(lockPath);
continue;
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
} catch {
/* lost race to another reclaim */
/* lost race / still held — fall through to poll */
}
continue;
}
} catch {
/* lock vanished mid-read */
Expand All @@ -110,12 +128,12 @@ export async function acquireStudioConfigSmokeLock(lockPath, deps = {}) {
/**
* Best-effort removal of an empty `.olive-studio` dir after the lock file is gone.
* @param {string} dir
* @param {{ rmSync?: typeof rmSync }} [deps]
* @param {{ rmdirSync?: typeof rmdirSync }} [deps]
*/
export function tryRemoveEmptyStudioConfigDir(dir, deps = {}) {
const rm = deps.rmSync ?? rmSync;
const rmdir = deps.rmdirSync ?? rmdirSync;
try {
rm(dir, { recursive: false });
rmdir(dir);
} catch {
/* not empty, missing, or busy */
}
Expand Down
11 changes: 9 additions & 2 deletions scripts/studioConfigSnapshot.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@
* Used by mcp-agent-smoke so policy patches never leave lossy booleans or a
* newly created config file behind.
*/
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import {
existsSync,
mkdirSync,
readFileSync,
rmdirSync,
rmSync,
writeFileSync,
} from "node:fs";
import path from "node:path";

/** Top-level marker written while mcp-agent-smoke owns policy patches. */
Expand Down Expand Up @@ -115,7 +122,7 @@ export function restoreStudioConfigFile(configPath, snapshot, opts = {}) {
// If smoke created `.olive-studio/` solely for the patch, drop the empty dir.
const dir = path.dirname(configPath);
try {
rmSync(dir, { recursive: false });
rmdirSync(dir);
} catch {
/* dir missing, not empty, or not removable — leave alone */
}
Expand Down
21 changes: 21 additions & 0 deletions src/lib/__tests__/resolvePython.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,27 @@ describe("resolvePython", () => {
).toBe("python3");
});

it("prefers python3 over python when both are on PATH", () => {
const spawnSync = vi.fn(() => ({ status: 0 }));
expect(
resolvePython(root, {
existsSync: () => false,
spawnSync: spawnSync as never,
platform: "linux",
}),
).toBe("python3");
expect(spawnSync).toHaveBeenCalledWith(
"python3",
["--version"],
expect.objectContaining({ encoding: "utf8" }),
);
expect(spawnSync).not.toHaveBeenCalledWith(
"python",
["--version"],
expect.anything(),
);
});

it("throws when no candidate is executable", () => {
expect(() =>
resolvePython(root, {
Expand Down
12 changes: 10 additions & 2 deletions src/lib/__tests__/studioConfigSmokeLock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ describe("studioConfigSmokeLock", () => {
pollMs: 10,
});
expect(store.get("/tmp/lock")).toBe("4242\n");
// Foreign PID must not be unlinked by our release().
store.set("/tmp/lock", "9999\n");
lock.release();
expect(store.get("/tmp/lock")).toBe("9999\n");
// Restore ownership and confirm own-pid release clears the lock.
store.set("/tmp/lock", "4242\n");
lock.release();
expect(store.has("/tmp/lock")).toBe(false);
});
Expand Down Expand Up @@ -102,9 +108,11 @@ describe("studioConfigSmokeLock", () => {
});

it("tryRemoveEmptyStudioConfigDir ignores busy dirs", () => {
const rmSync = vi.fn(() => {
const rmdirSync = vi.fn(() => {
throw Object.assign(new Error("ENOTEMPTY"), { code: "ENOTEMPTY" });
});
expect(() => tryRemoveEmptyStudioConfigDir("/x", { rmSync: rmSync as never })).not.toThrow();
expect(() =>
tryRemoveEmptyStudioConfigDir("/x", { rmdirSync: rmdirSync as never }),
).not.toThrow();
});
});
104 changes: 85 additions & 19 deletions src/server/services/olive/jobRunner.idempotency.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
/**
* Concurrent MCP submit locking + idempotent reuse via startOliveJob.
* Keeps setup CPU-only: mocked spawn/fs, drained detached setup before cleanup.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
*/
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import fs from "fs";
import { preflightOliveRecipe } from "./jobPreflight.ts";
import { mcpSubmitLockTailCount, startOliveJob } from "./jobRunner.ts";
import { clearIdempotencyIndex } from "./jobIdempotency.ts";
import { jobRegistry } from "./state.ts";

const childProcessMocks = vi.hoisted(() => ({
execFileImpl: null as null | ((...args: unknown[]) => unknown),
spawnImpl: null as null | ((...args: unknown[]) => unknown),
execFileCalls: [] as unknown[][],
}));

vi.mock("child_process", async (importOriginal) => {
const { childProcessVitestMockFactory } = await import("../../__tests__/childProcessTestMocks.ts");
return childProcessVitestMockFactory(childProcessMocks, { includeSpawn: true })(importOriginal);
});

vi.mock("./jobPreflight.ts", () => ({
preflightOliveRecipe: vi.fn(() => ({
valid: true,
Expand All @@ -25,14 +37,35 @@ vi.mock("../venv/index.ts", () => ({
python: "python",
family: "default",
})),
buildOliveRunEnvironment: vi.fn(() => ({})),
buildOliveRunEnvironment: vi.fn(async () => ({})),
resolveOliveCommand: vi.fn(() => ({ executable: "echo", args: ["ok"] })),
}));

afterEach(() => {
const { mcpSubmitLockTailCount, startOliveJob } = await import("./jobRunner.ts");

/** Waiters that ensure detached MCP setup has left `setting_up` before registry clear. */
const pendingSetups: Promise<unknown>[] = [];

async function drainPendingSetups(): Promise<void> {
for (let i = 0; i < 20; i += 1) {
if (pendingSetups.length === 0) return;
const batch = pendingSetups.splice(0, pendingSetups.length);
await Promise.allSettled(batch);
await Promise.resolve();
}
}

beforeEach(() => {
vi.spyOn(fs, "mkdirSync").mockReturnValue(undefined as unknown as string);
vi.spyOn(fs, "writeFileSync").mockReturnValue(undefined);
});

afterEach(async () => {
await drainPendingSetups();
jobRegistry.clear();
clearIdempotencyIndex();
vi.clearAllMocks();
vi.restoreAllMocks();
vi.mocked(preflightOliveRecipe).mockImplementation(() => ({
valid: true,
provider: "CPUExecutionProvider",
Expand All @@ -44,12 +77,37 @@ afterEach(() => {
}));
});

/** Track fire-and-forget MCP setup so afterEach can drain before clearing the registry. */
async function startOliveJobTracked(
...args: Parameters<typeof startOliveJob>
): ReturnType<typeof startOliveJob> {
const before = new Set(jobRegistry.keys());
const result = await startOliveJob(...args);
if (result.ok && !result.reused) {
const job = jobRegistry.get(result.jobId);
if (job && !before.has(result.jobId)) {
const settled = (async () => {
const deadline = Date.now() + 5_000;
while (Date.now() < deadline) {
const current = jobRegistry.get(result.jobId);
if (!current || current.finishedAt != null || current.status !== "setting_up") {
return;
}
await new Promise((r) => setTimeout(r, 10));
}
})();
pendingSetups.push(settled);
}
}
return result;
}

describe("startOliveJob MCP idempotency lock", () => {
it("serializes concurrent submits with the same idempotency key into one job", async () => {
const recipe = { input_model: {}, passes: {}, engine: {}, systems: {} } as never;
const [a, b] = await Promise.all([
startOliveJob({ recipe, source: "mcp", idempotencyKey: "same-key" }),
startOliveJob({ recipe, source: "mcp", idempotencyKey: "same-key" }),
startOliveJobTracked({ recipe, source: "mcp", idempotencyKey: "same-key" }),
startOliveJobTracked({ recipe, source: "mcp", idempotencyKey: "same-key" }),
]);
expect(a.ok).toBe(true);
expect(b.ok).toBe(true);
Expand All @@ -64,8 +122,8 @@ describe("startOliveJob MCP idempotency lock", () => {
it("serializes key-bearing and fingerprint-only submits for the same recipe", async () => {
const recipe = { input_model: {}, passes: {}, engine: {}, systems: {} } as never;
const [withKey, fpOnly] = await Promise.all([
startOliveJob({ recipe, source: "mcp", idempotencyKey: "agent-key-1" }),
startOliveJob({ recipe, source: "mcp" }),
startOliveJobTracked({ recipe, source: "mcp", idempotencyKey: "agent-key-1" }),
startOliveJobTracked({ recipe, source: "mcp" }),
]);
expect(withKey.ok).toBe(true);
expect(fpOnly.ok).toBe(true);
Expand All @@ -78,8 +136,8 @@ describe("startOliveJob MCP idempotency lock", () => {

it("reuses a fingerprint-only admission when a keyed submit arrives afterward", async () => {
const recipe = { input_model: {}, passes: {}, engine: {}, systems: {} } as never;
const fpOnly = await startOliveJob({ recipe, source: "mcp" });
const withKey = await startOliveJob({
const fpOnly = await startOliveJobTracked({ recipe, source: "mcp" });
const withKey = await startOliveJobTracked({
recipe,
source: "mcp",
idempotencyKey: "after-fp-key",
Expand All @@ -91,7 +149,7 @@ describe("startOliveJob MCP idempotency lock", () => {
expect(withKey.reused).toBe(true);

// Same adopted key must replay onto the fingerprint-only job.
const replay = await startOliveJob({
const replay = await startOliveJobTracked({
recipe,
source: "mcp",
idempotencyKey: "after-fp-key",
Expand All @@ -106,8 +164,8 @@ describe("startOliveJob MCP idempotency lock", () => {

it("still allows a distinct idempotency key to start a new job after the first settles", async () => {
const recipe = { input_model: {}, passes: {}, engine: {}, systems: {} } as never;
const first = await startOliveJob({ recipe, source: "mcp", idempotencyKey: "key-a" });
const second = await startOliveJob({ recipe, source: "mcp", idempotencyKey: "key-b" });
const first = await startOliveJobTracked({ recipe, source: "mcp", idempotencyKey: "key-a" });
const second = await startOliveJobTracked({ recipe, source: "mcp", idempotencyKey: "key-b" });
expect(first.ok).toBe(true);
expect(second.ok).toBe(true);
if (!first.ok || !second.ok) return;
Expand All @@ -133,7 +191,7 @@ describe("startOliveJob MCP idempotency lock", () => {
});

for (let i = 0; i < 20; i += 1) {
const result = await startOliveJob({
const result = await startOliveJobTracked({
recipe,
source: "mcp",
idempotencyKey: `unique-key-${i}`,
Expand All @@ -160,12 +218,20 @@ describe("startOliveJob MCP idempotency lock", () => {

// Distinct keys share fp:fp-hold lock; second replaces the map entry while first still holds.
// First release must not delete the newer tail (ownership check); both finish and map is empty.
const results = await Promise.all([
startOliveJob({ recipe, source: "mcp", idempotencyKey: "hold-1" }),
startOliveJob({ recipe, source: "mcp", idempotencyKey: "hold-2" }),
startOliveJob({ recipe, source: "mcp" }), // fingerprint-only overlaps fp lock
// Serialized waiters: hold-1 then hold-2 create distinct jobs; fingerprint-only reuses hold-2.
const [hold1, hold2, fpOnly] = await Promise.all([
startOliveJobTracked({ recipe, source: "mcp", idempotencyKey: "hold-1" }),
startOliveJobTracked({ recipe, source: "mcp", idempotencyKey: "hold-2" }),
startOliveJobTracked({ recipe, source: "mcp" }),
]);
expect(results.every((r) => r.ok)).toBe(true);
expect(hold1.ok && hold2.ok && fpOnly.ok).toBe(true);
if (!hold1.ok || !hold2.ok || !fpOnly.ok) return;
expect(hold1.jobId).not.toBe(hold2.jobId);
expect(hold1.reused).toBe(false);
expect(hold2.reused).toBe(false);
expect(fpOnly.reused).toBe(true);
expect(fpOnly.jobId).toBe(hold2.jobId);
expect([...jobRegistry.keys()].sort()).toEqual([hold1.jobId, hold2.jobId].sort());
expect(mcpSubmitLockTailCount()).toBe(0);
});
});
14 changes: 13 additions & 1 deletion src/server/services/olive/jobRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,20 @@ async function continueOliveJobSetup(
);
if (stubSetup) {
pushLog(job, "[stub] Olive job setup stubbed; waiting for cancel.");
// Exit when cancelled or when another path finalizes the job without a status flip.
const rawTimeout = Number(process.env.OLIVE_JOB_SETUP_STUB_TIMEOUT_MS);
const stubTimeoutMs =
Number.isFinite(rawTimeout) && rawTimeout > 0 ? rawTimeout : 120_000;
const deadline = Date.now() + stubTimeoutMs;
// Exit when cancelled, externally finalized, or the stub wait times out.
while (job.status === "setting_up" && job.finishedAt == null) {
if (Date.now() >= deadline) {
job.status = "failed";
pushLog(
job,
`[stub] Setup stub timed out after ${stubTimeoutMs}ms waiting for cancel/finalize.`,
Comment thread
tonythethompson marked this conversation as resolved.
Resolved
);
break;
}
Comment thread
tonythethompson marked this conversation as resolved.
Resolved
await new Promise((r) => setTimeout(r, 200));
}
cleanupJobArtifacts(job);
Expand Down
Loading