Repository navigation
fix(process): forward-port startup cleanup and shared lineage fixes - #192386
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR extends startup cleanup waiting, preserves the original startup error alongside cleanup failures, and shares inherited lineage across module copies. Example: A stdio server fails to start and its admitted process cleanup completes after 750 ms.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this maintainer-authored PR repairs cleanup and lineage behavior still present on main; no actionable introduced defect was found, but required CI remains red. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherMCP, LSP, and command execution use the shared process adapters, which accept launch parameters and return readiness, output, exit results, and independently confirmed cleanup. flowchart TD
A[MCP LSP and command callers] --> B[Owned stdio and child adapter]
B --> C[Service child relay host]
D[Shared inherited lineage] --> C
C --> E[Native process owner]
E --> F[Command and descendants]
E --> G[Startup and cleanup results]
G --> B
Technical reviewBest possible solution: Land this focused forward-port through the existing process owners once the required CI failures are resolved or independently attributed. Do we have a high-confidence way to reproduce the issue? Main's 500 ms wait demonstrably misclassifies a cleanup promise settling after 750 ms; source also shows startup errors being displaced by cleanup rejection and lineage bindings isolated per module instance. Is this the best way to solve the issue? The patch is a small, coherent repair: it adjusts the existing bounded wait, retains both failures, and replaces module-local lineage state with the existing singleton mechanism. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 57c207777674. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +38, Tests +92, Other +2. Total +132 across 8 files. Added test files: 1. View PR surface stats
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed November 4, 2026, 5:11 PM ET / 22:11 UTC (Revision 2). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Co-authored-by: RomneyDa <[email protected]> Forward-port of ba42adb from release/2026.10.10.
When an owned stdio process failed to start and its cleanup also failed, the relay host rethrew the cleanup rejection instead of the anchor's startup error, and owned stdio replaced the message again with "stdio startup cleanup did not confirm closure". The Docker CLI backend lane only showed the identity-loss cleanup error, never why startup failed. Throw the startup failure first with the cleanup failure as a secondary AggregateError member, and lead the owned stdio message with the startup failure plus the next step (restart the Gateway before retrying). On main this also changes the refused-launch hard-deadline case from #187137: the refusal now leads and the hard-deadline cleanup failure follows as the secondary member; the cleanup fence itself is unchanged. Forward-port of e51fa64 from release/2026.10.10.
The CLI backend live lane runs its Gateway from source under vitest while bundled plugins load from dist. The anthropic plugin's openclaw/plugin-sdk import is natively aliased to the source SDK, so src/process/supervisor loads a second time outside vitest's graph. That copy never saw the test's bindInheritedNativeProcessOwner(dist anchor) and fell back to the source anchor. Inherited lineage fds and the native process owner are process state, so keep them in one global singleton slot that every module copy shares. Forward-port of 7dc3350 from release/2026.10.10.
82fcb52 to
2e37fc6
Compare
Stronger local real-process proof (2026-11-04)Tested PR head PR-specific before/after proofThe pre-fix control used the same head checkout and identical harness, replacing only the four changed production files with their versions from base
Pre-fix result: 3 failed / 1 passed, all failures at the expected behavioral assertions—not setup failures. Initial candidate run: 4/4 passed (delayed cleanup: 909 ms). Final restored-head combined replay: 12 passed, 2 Windows-only skipped, across six test files. The missing-receipt case intentionally remains a cleanup failure: eventual OS process-group disappearance is observed separately for fixture retirement; it is not substituted for the missing protocol certificate. The longer startup wait does not turn unconfirmed cleanup into success. Existing native integration coverage replayed
ReproductionSave the disposable harness below as node scripts/run-vitest.mjs \
src/process/supervisor/pr192386-local-proof.real.test.ts \
src/process/owned-stdio.real.test.ts \
src/process/supervisor/supervisor.prelaunch-initiation.real.test.ts \
src/process/supervisor/service-child-relay-host.readiness.real.test.ts \
src/process/supervisor/service-child-relay.native-owner.test.ts \
src/process/supervisor/supervisor.root-exit.real.test.ts \
--maxWorkers=1For the pre-fix control in a disposable checkout, replace these files from the stated base, run only the new harness, then restore the head versions:
Limits: this is local process-component integration proof, not a full interactive Gateway/provider session, packaged plugin release test, or native Linux/Windows qualification. The duplicate-module test independently transpiles the real module into a second ESM graph; it does not install a shipped plugin. The missing/delayed closing frames are explicit fault injection in a temporary wrapper around the real anchor. No mocked completion receipts or fake timers are used. Two Windows-specific tests were skipped; no Linux/Windows result is claimed. PR source/head is unchanged; the disposable harness is included here for review/reproduction rather than added to permanent test allocation. Disposable live-proof harness (complete)import { once } from "node:events";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { stripTypeScriptTypes } from "node:module";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { expect, it } from "vitest";
import { resolveRuntimeProcessEntrypointUrl } from "../../infra/runtime-process-url.js";
import { closeOwnedStdioProcess, createOwnedStdioProcess } from "../owned-stdio.js";
import { bindInheritedNativeProcessOwner } from "./inherited-process-lineage.js";
import { isOwnedProcessGroupGone } from "./service-child-group-ownership.js";
async function fixture() {
const root = await mkdtemp(path.join(os.tmpdir(), "pr192386-live-"));
const receipt = path.join(root, "receipt.json");
const owner = path.join(root, "owner.mjs");
const anchor = resolveRuntimeProcessEntrypointUrl("serviceChildGroupAnchor").href;
return { root, receipt, owner, anchor, dispose: async () => {
const record = await readFile(receipt,"utf8").then(JSON.parse, error => { if(error.code!=="ENOENT") throw error; });
if(record) {
const deadline=Date.now()+6000;
while(!isOwnedProcessGroupGone(record.pid) && Date.now()<deadline) await new Promise(resolve=>setTimeout(resolve,20));
expect(isOwnedProcessGroupGone(record.pid)).toBe(true);
}
await rm(root, { recursive: true, force: true });
} };
}
it("real launch consumes native owner and live socket FD bound by a separately transpiled module", async () => {
const f = await fixture();
const server = net.createServer();
server.listen(path.join(f.root, "lineage.sock"));
await once(server, "listening");
const connected = once(server, "connection");
const client = net.connect(path.join(f.root, "lineage.sock"));
await once(client, "connect");
const [peer] = await connected as [net.Socket];
let received = "";
peer.on("data", data => { received += data.toString(); });
const fd = (client as unknown as { _handle: { fd: number } })._handle.fd;
const source = await readFile(path.join(process.cwd(), "src/process/supervisor/inherited-process-lineage.ts"), "utf8");
const singleton = await readFile(path.join(process.cwd(), "src/shared/global-singleton.ts"), "utf8");
await writeFile(path.join(f.root, "singleton.mjs"), stripTypeScriptTypes(singleton));
await writeFile(path.join(f.root, "lineage.mjs"), stripTypeScriptTypes(source).replace("../../shared/global-singleton.js", "./singleton.mjs"));
const duplicate = await import(/* @vite-ignore */ pathToFileURL(path.join(f.root, "lineage.mjs")).href);
await writeFile(f.owner, `import { writeFileSync, writeSync } from "node:fs";
await import(${JSON.stringify(f.anchor)});
process.prependListener("message", start => {
if (start.type !== "start") return;
const fds = start.parentLineageFds ?? [];
writeFileSync(${JSON.stringify(f.receipt)}, JSON.stringify({pid:process.pid,fds}));
for (const fd of fds) writeSync(fd, "actual-inherited-socket\\n");
});`);
const releaseOwner = duplicate.bindInheritedNativeProcessOwner(pathToFileURL(f.owner).href);
const releaseFds = duplicate.bindInheritedProcessLineageFds([fd]);
let child;
try {
child = await createOwnedStdioProcess({ argv: [process.execPath, "-e", "process.stdin.resume();process.stdin.on('end',()=>process.stdout.write('real-child-done'))"] });
let output = "";
child.onStdout(chunk => { output += chunk; });
await closeOwnedStdioProcess(child);
expect(output).toBe("real-child-done");
expect(received).toBe("actual-inherited-socket\n");
const record = JSON.parse(await readFile(f.receipt, "utf8"));
expect(record.fds).toHaveLength(1);
expect(isOwnedProcessGroupGone(record.pid)).toBe(true);
console.log("LIVE duplicate-module: inherited socket bytes received; native owner group extinct", record);
} finally {
releaseOwner(); releaseFds();
if (child) await closeOwnedStdioProcess(child, {force:true}).catch(() => {});
client.destroy(); peer.destroy(); await new Promise<void>(resolve => server.close(() => resolve()));
await f.dispose();
}
}, 20_000);
it("real missing executable retains ENOENT and allows a subsequent owned launch", async () => {
const f = await fixture();
try {
await expect(createOwnedStdioProcess({argv:[path.join(f.root, "does-not-exist")]})).rejects.toMatchObject({code:"ENOENT"});
const child = await createOwnedStdioProcess({argv:[process.execPath, "-e", "process.stdin.resume()"]});
await closeOwnedStdioProcess(child);
await expect(child.waitForExtinction!()).resolves.toBeUndefined();
console.log("LIVE ENOENT: original OS error retained; subsequent real launch and extinction succeeded");
} finally { await f.dispose(); }
}, 20_000);
it("real ENOENT remains primary when the native anchor closing receipt is fault-injected away", async () => {
const f = await fixture();
await writeFile(f.owner, `import { writeFileSync } from "node:fs";
import { Socket } from "node:net";
writeFileSync(${JSON.stringify(f.receipt)}, JSON.stringify({pid:process.pid}));
const originalWrite = Socket.prototype.write;
Socket.prototype.write = function(chunk, ...args) {
let message; try { message=JSON.parse(String(chunk)); } catch {}
if (message?.type === "closing") {
const callback=args.find(arg=>typeof arg==="function");
if(callback) queueMicrotask(()=>callback());
return true;
}
return originalWrite.call(this,chunk,...args);
};
await import(${JSON.stringify(f.anchor)});`);
const release = bindInheritedNativeProcessOwner(pathToFileURL(f.owner).href);
try {
const error = await createOwnedStdioProcess({argv:[path.join(f.root, "does-not-exist")]}).then(() => { throw new Error("unexpected launch"); }, error => error);
const primary = error.cause instanceof AggregateError ? error.cause.errors[0] : error;
expect(primary).toBeInstanceOf(AggregateError);
expect(primary.errors[0]).toMatchObject({code:"ENOENT"});
expect(String(primary.errors[1])).toMatch(/cleanup|closing|identity|receipt/i);
const record = JSON.parse(await readFile(f.receipt, "utf8"));
const deadline=Date.now()+6000;
while(!isOwnedProcessGroupGone(record.pid) && Date.now()<deadline) await new Promise(resolve=>setTimeout(resolve,20));
expect(isOwnedProcessGroupGone(record.pid)).toBe(true);
console.log("LIVE missing receipt: OS ENOENT is first cause; cleanup remains a separate failure; native group extinct", {message:error.message, primary:primary.errors.map((e:Error)=>e.message), pid:record.pid});
} finally { release(); await f.dispose(); }
}, 20_000);
it("real admitted child cleanup delayed 900ms retains the original admission error", async () => {
const f = await fixture();
await writeFile(f.owner, `import { writeFileSync } from "node:fs";
import { Socket } from "node:net";
writeFileSync(${JSON.stringify(f.receipt)}, JSON.stringify({pid:process.pid}));
const originalWrite = Socket.prototype.write;
Socket.prototype.write = function(chunk, ...args) {
let message; try { message=JSON.parse(String(chunk)); } catch {}
if (message?.type === "closing") {
setTimeout(()=>originalWrite.call(this,chunk,...args),900);
return true;
}
return originalWrite.call(this,chunk,...args);
};
await import(${JSON.stringify(f.anchor)});`);
const release = bindInheritedNativeProcessOwner(pathToFileURL(f.owner).href);
const admissionError = new Error("proof: admission revoked after real native ready");
let calls = 0;
let failedAt = 0;
try {
const error = await createOwnedStdioProcess({
argv:[process.execPath,"-e","process.stdin.resume()"],
assertCurrent:()=>{ if(++calls===4) { failedAt=performance.now(); throw admissionError; } }
}).then(child => closeOwnedStdioProcess(child).then(()=>new Error("unexpected launch")), error => error);
const elapsed = performance.now()-failedAt;
console.log("LIVE delayed cleanup", {calls,elapsed,error:error.message});
expect(calls).toBe(4);
expect(error).toBe(admissionError);
expect(elapsed).toBeGreaterThanOrEqual(800);
const record=JSON.parse(await readFile(f.receipt,"utf8"));
expect(isOwnedProcessGroupGone(record.pid)).toBe(true);
} finally {
release();
// The 500ms baseline fails before the real delayed receipt arrives. Join fixture retirement.
const record=JSON.parse(await readFile(f.receipt,"utf8"));
const deadline=Date.now()+6000;
while(!isOwnedProcessGroupGone(record.pid) && Date.now()<deadline) await new Promise(resolve=>setTimeout(resolve,20));
expect(isOwnedProcessGroupGone(record.pid)).toBe(true);
await f.dispose();
}
},20_000); |
Carry the final reviewed changes from #191830, #192378, #192379, #192380, #192383, #192385, and #192386. Preserve #191838's existing file-transfer import fix. Adapt Gateway readiness to the release owner and include the narrow SQLite cold-admission prerequisite from #192586. Do not carry #192387: its Goal expectation depends on main-only Stop-to-paused behavior absent from this release. Retain regression allocations without changing the shared baseline.
…penclaw#192386) * fix(process): preserve loaded startup cleanup Co-authored-by: RomneyDa <[email protected]> Forward-port of ba42adb from release/2026.10.10. * fix(process): keep stdio startup failures ahead of cleanup errors When an owned stdio process failed to start and its cleanup also failed, the relay host rethrew the cleanup rejection instead of the anchor's startup error, and owned stdio replaced the message again with "stdio startup cleanup did not confirm closure". The Docker CLI backend lane only showed the identity-loss cleanup error, never why startup failed. Throw the startup failure first with the cleanup failure as a secondary AggregateError member, and lead the owned stdio message with the startup failure plus the next step (restart the Gateway before retrying). On main this also changes the refused-launch hard-deadline case from openclaw#187137: the refusal now leads and the hard-deadline cleanup failure follows as the secondary member; the cleanup fence itself is unchanged. Forward-port of e51fa64 from release/2026.10.10. * fix(process): share inherited process lineage across module copies The CLI backend live lane runs its Gateway from source under vitest while bundled plugins load from dist. The anthropic plugin's openclaw/plugin-sdk import is natively aliased to the source SDK, so src/process/supervisor loads a second time outside vitest's graph. That copy never saw the test's bindInheritedNativeProcessOwner(dist anchor) and fell back to the source anchor. Inherited lineage fds and the native process owner are process state, so keep them in one global singleton slot that every module copy shares. Forward-port of 7dc3350 from release/2026.10.10. * test(ci): scope process forward-port regression allocation * test(process): use deterministic startup cleanup clocks --------- Co-authored-by: roboclaw-bot <[email protected]>
Problem
Process startup failures discovered during the 2026.10.10 stable release cycle could be hidden by cleanup errors, or cleanup could be declared uncertain before a loaded native process tree had time to settle. A source-host/dist-plugin combination could also load separate inherited-lineage bindings.
This is the process-only split of #191830. It targets
maindirectly and does not depend on the other split PRs.Solution
The original commit attribution and release references are preserved:
ba42adbc70,e51fa6420f, and7dc3350cb9fromrelease/2026.10.10.Scope and regression budget
The simplify pass retains the existing process/relay owners and distinct tests for delayed cleanup, startup-vs-cleanup error precedence, and duplicate-module lineage. There is no new manager or alternate cleanup path. Product delta is +62/-24 lines; net test growth is 92 lines. A dedicated 92-line test allocation covers exactly this split's net regression growth; the original aggregate allocation is not copied.
Evidence
owned-stdio.test.ts: 4/4 passed in 2.45s wall (5ms tests).git diff --check: passed.src/agents/agent-bundle-mcp-materialize.tsandmcp-metadata.ts(missing exported McpCatalogTool and optional UI metadata versus required Pick). Scoped lint is blocked by the same declaration-emitter prerequisite. These files are unchanged from the pinned main base.34007820fa2cthroughc838f5525d7f: no production or security defects; its exact test-budget allocation and deterministic-clock findings are addressed. The later changes only add the scoped allocation and replace real waits with fake-clock advancement.Original #191830 recorded failing-without-fix regression evidence for these process changes. This split preserves the production hunks unchanged; the mocked timing regression now advances a fake clock rather than waiting in real time. Native Linux/Windows live-process lanes have not been rerun locally; broad/platform coverage remains PR CI work.
Split CI status
34007820fa2c: missingMcpCatalogToolexport inmcp-metadata.tsand consequent optional UI metadata errors. That file andagent-bundle-mcp-materialize.ts/agent-bundle-mcp-types.tsare byte-identical to the base; SDK declaration preparation propagates the same error into build/boundary/lint lanes.Exact-head CI attribution audit
Audited 2026-11-04 at
82fcb528584d78b1d31687fc6f6153a0db0a5a2e. Failed job logs were inspected individually, not inferred from their names.The MCP failures are inherited from base
34007820fa2c:src/agents/mcp-metadata.ts,agent-bundle-mcp-materialize.ts, andagent-bundle-mcp-types.tshave identical Git blob IDs at base and PR head. The missingMcpCatalogToolexport and consequent optional-property errors propagate through SDK declarations into boundary/build/lint/type lanes.The test-line ratchet is also inherited: this PR offsets its exact positive test-line delta, and its job still exceeds the adjusted ceiling by the same 47 lines already present at base (6,444,916 vs 6,444,869). No baseline increase or unrelated repair is included.
Cancelled dispatch jobs are orchestration cancellations, not passing tests or additional source defects. CI remains red; this section explains the failures rather than claiming green.
Rebase onto current main
Rebased onto
a1f99240c8367a0e012b401bed71831a3cc65026, including merged Goal-test correction #192387. New candidate:2e37fc63ad8e028ebafeb8dd467366430aada830. This PR still targets main independently.Verified the complete rebased tree equals the previous PR patch integrated with that main snapshot. No new behavior was added during rebase. Prior test and CI attribution sections remain evidence for their named old revisions; fresh CI on this head is pending, not claimed green.