Skip to content

Commit 8026405

Browse files
lidge-junt
andauthored
wp7: report the actual reason a proxy refused to stop (#4067)
* fix(cli): report the reason a proxy refused to stop /api/stop answers 409 for two different reasons. The original one is a scheduler wrapper under another CODEX_HOME that would respawn the proxy anyway; #4023 added a second, the proxy being the installed launchd or systemd job itself. stopProxy reported the first unconditionally, so an operator whose proxy is simply the service was told "a service installed under a different CODEX_HOME/OPENCODEX_HOME owns it. Run the stop from that home" and sent to a home that does not exist. The server already sends a precise message for each case. It is now carried through to the thrown error, with the previous text kept as the fallback when the body is unreadable. Found by the main-to-dev regression review for the 2.49.0 promotion. It needs a receipt-write failure plus a surviving managed proxy to reach, which is why neither the #4023 review nor its CI caught it. * test(xai): assert the 409 invariant without pinning the exact line The source oracle matched `if (res.status === 409) return "refused"` verbatim, so capturing the server's refusal reason first broke it even though the invariant it protects — a 409 returns "refused" and never falls through to the forced-kill path — still holds. It now locates the 409 branch inside stopProxyGracefully and asserts the ordering: "refused" is returned before the !res.ok fallthrough. Removing that return still turns the test red, so the oracle is no weaker than before. --------- Co-authored-by: t <[email protected]>
1 parent 02bc10e commit 8026405

3 files changed

Lines changed: 79 additions & 6 deletions

File tree

‎src/lib/process-control.ts‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,25 @@ export function gracefulStopHost(hostname: string | undefined): string {
7171
*/
7272
export type GracefulStopResult = boolean | "refused";
7373

74-
/** A proxy declined shutdown because a service under another home owns it (HTTP 409). */
74+
/**
75+
* The server's own explanation for the most recent 409, captured so `stopProxy` can report
76+
* the real reason. There is more than one: a scheduler wrapper under another home, or the
77+
* proxy being the installed service itself (#4023). Module-scoped because
78+
* `GracefulStopResult` is a public contract with several callers, and widening it to carry
79+
* the text would change every one of them for a message only this file reports.
80+
*/
81+
let lastRefusalMessage: string | null = null;
82+
83+
/** The server's explanation for the most recent 409, or `null` when it sent none. */
84+
export function lastStopRefusalMessage(): string | null {
85+
return lastRefusalMessage;
86+
}
87+
88+
/**
89+
* A proxy declined shutdown (HTTP 409). There is more than one reason it can say no — a
90+
* scheduler wrapper under another home, or the proxy being the installed service itself
91+
* (#4023) — so the server's own message is carried through rather than guessed at.
92+
*/
7593
export class ProxyOwnershipRefusedError extends Error {}
7694

7795
/**
@@ -111,7 +129,15 @@ export async function stopProxyGracefully(pid: number, io: GracefulStopIo = {}):
111129
// would respawn it anyway). That is a policy answer, not a dead endpoint — escalating to
112130
// SIGTERM here would run the daemon's cleanup and strip shared config out from under the
113131
// still-running service. Report the refusal instead of forcing.
114-
if (res.status === 409) return "refused";
132+
if (res.status === 409) {
133+
lastRefusalMessage = await res.json()
134+
.then(body => {
135+
const message = (body as { message?: unknown } | null)?.message;
136+
return typeof message === "string" && message.trim() ? message.trim() : null;
137+
})
138+
.catch(() => null);
139+
return "refused";
140+
}
115141
if (!res.ok) return false;
116142
} catch {
117143
return false;
@@ -140,8 +166,9 @@ export async function stopProxy(pid: number, io: GracefulStopIo = {}): Promise<b
140166
// The proxy refused on purpose (foreign service owns it). Forcing would strip shared
141167
// config while that service keeps the proxy alive.
142168
throw new ProxyOwnershipRefusedError(
143-
"The running proxy refused to stop: a service installed under a different "
144-
+ "CODEX_HOME/OPENCODEX_HOME owns it. Run the stop from that home.",
169+
lastRefusalMessage
170+
?? "The running proxy refused to stop: a service installed under a different "
171+
+ "CODEX_HOME/OPENCODEX_HOME owns it. Run the stop from that home.",
145172
);
146173
}
147174
if (graceful) {

‎tests/lib/process-control-graceful.test.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, test } from "bun:test";
2-
import { gracefulStopHost, stopProxyGracefully } from "../../src/lib/process-control";
2+
import { gracefulStopHost, lastStopRefusalMessage, stopProxyGracefully } from "../../src/lib/process-control";
33

44
function okResponse(): Response {
55
return new Response(JSON.stringify({ success: true }), { status: 200 });
@@ -107,3 +107,38 @@ describe("stopProxyGracefully", () => {
107107
expect(noExit).toBe(false);
108108
});
109109
});
110+
111+
describe("409 refusal reporting", () => {
112+
test("a refusal carries the server's own reason, not the ownership guess", async () => {
113+
// /api/stop answers 409 for more than one reason: a scheduler wrapper under another
114+
// home, and (since #4023) the proxy being the installed launchd/systemd job itself.
115+
// stopProxy used to report the first of those unconditionally, sending an operator
116+
// whose proxy is simply the service to a CODEX_HOME that does not exist.
117+
const selfUnload = "This proxy is running as the installed service, so stopping the manager"
118+
+ " from inside it would end this process before native Codex is restored."
119+
+ " Run `ocx stop`, which stops the service from outside and completes the restore."
120+
+ " Nothing was changed.";
121+
const result = await stopProxyGracefully(7, {
122+
readRuntime: () => ({ port: 10100 }),
123+
fetchFn: (async () => new Response(
124+
JSON.stringify({ success: false, code: "self_unload_service", message: selfUnload }),
125+
{ status: 409, headers: { "content-type": "application/json" } },
126+
)) as typeof fetch,
127+
waitExit: () => true,
128+
env: {},
129+
});
130+
expect(result).toBe("refused");
131+
expect(lastStopRefusalMessage()).toBe(selfUnload);
132+
});
133+
134+
test("a 409 with no readable body falls back rather than reporting a stale reason", async () => {
135+
const result = await stopProxyGracefully(7, {
136+
readRuntime: () => ({ port: 10100 }),
137+
fetchFn: (async () => new Response("not json", { status: 409 })) as typeof fetch,
138+
waitExit: () => true,
139+
env: {},
140+
});
141+
expect(result).toBe("refused");
142+
expect(lastStopRefusalMessage()).toBeNull();
143+
});
144+
});

‎tests/providers/xai/grok-lifecycle.test.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,18 @@ describe("POST /api/stop teardown", () => {
509509
test("a 409 does not escalate to a forced kill", () => {
510510
// Escalating would run the daemon's cleanup and strip shared config while the foreign
511511
// service keeps the proxy alive — the exact hole the ownership gate exists to close.
512-
expect(PROCESS_CONTROL_SOURCE).toContain('if (res.status === 409) return "refused"');
512+
// The 409 branch may capture the server's reason first (#4023 added a second refusal
513+
// cause), but it must still return "refused" without falling through to !res.ok.
514+
const stopGracefully = sliceFn(
515+
PROCESS_CONTROL_SOURCE,
516+
"export async function stopProxyGracefully(",
517+
"export async function stopProxy(",
518+
);
519+
const four09At = stopGracefully.indexOf("res.status === 409");
520+
expect(four09At).toBeGreaterThan(-1);
521+
expect(stopGracefully.slice(four09At)).toContain('return "refused"');
522+
expect(stopGracefully.indexOf('return "refused"', four09At))
523+
.toBeLessThan(stopGracefully.indexOf("if (!res.ok) return false;", four09At));
513524

514525
const stopProxyFn = sliceFn(PROCESS_CONTROL_SOURCE, "export async function stopProxy(", "export function killProxy(");
515526
const refusedAt = stopProxyFn.indexOf('graceful === "refused"');

0 commit comments

Comments
 (0)