Skip to content

Commit 0ef04e6

Browse files
authored
fix(cli): stop start shadowing a live configured-port proxy, and retry health (#3106)
Reimplements #3078 (author @Veritas-7) on dev. Both production hunks are right; the PR targets main and its test file does not typecheck (tests/cli-health-retry.test.ts declares const servers: Server[] while importing only IncomingMessage and ServerResponse). handleStart skipped the configured-port probe whenever the pid file and the runtime-port record were both absent. That absence proves nothing: a fallback-port sibling overwrites both records when it starts and removes them when it stops. So start shadowed a healthy configured-port proxy with an ephemeral-port copy, re-pointed client config at the copy, and the next sibling shutdown left no runtime record for discovery at all. handleEnsure already passed probeConfiguredPort: true; handleStart is the path that did not. ocx health probed once. A proxy that has only just bound can miss a single probe while its event loop is still settling startup work, so health run seconds after a service restart reported "Proxy not healthy" and exited 1 for a proxy that was serving. The stop paths already retry this exact race under SERVICE_STOP_LIVENESS (#764). Tests are dependency-injected and source-level rather than #3078's port-binding integration fixture: the retry budget is asserted through dispatchCommand's injected findLiveProxy, and the start guard through a source oracle next to the handleEnsure call site that was already correct. Mutation-checked, both restored: drop probeConfiguredPort from handleStart -> 28 pass / 1 fail, the start guard drop the health retry budget -> 28 pass / 1 fail, the health test
1 parent a3656a9 commit 0ef04e6

3 files changed

Lines changed: 85 additions & 4 deletions

File tree

‎src/cli/dispatch.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { CLI_COMMANDS } from "./registry";
1212
import { isValidProviderName } from "../config/provider-name";
1313
import type { CliHead } from "./root";
1414
import type { ReadyArgs } from "./ready";
15-
import type { LiveProxy } from "../server/proxy-liveness";
15+
import type { LivenessIo, LiveProxy } from "../server/proxy-liveness";
1616
import type { OcxConfig } from "../types";
1717
import { hasHelpFlag, printSubcommandUsage, printUsage } from "./help";
1818
import { setIntegrationEnabled, shouldSyncCodexOnStart } from "../codex/desired-state";
@@ -29,7 +29,7 @@ export interface CliDispatchDeps {
2929
command: string | undefined;
3030
head: CliHead;
3131
loadConfig: () => OcxConfig;
32-
findLiveProxy: () => Promise<LiveProxy | null>;
32+
findLiveProxy: (io?: LivenessIo) => Promise<LiveProxy | null>;
3333
probeHostname: (hostname: string | undefined) => string;
3434
waitForProxy: (timeoutMs?: number) => Promise<LiveProxy | null>;
3535
startArgv: (port?: number) => string[];
@@ -573,7 +573,12 @@ const commandRunners: Record<string, CommandRunner> = {
573573
health: async deps => {
574574
const healthArgs = deps.args.slice(1);
575575
const wantsHealthJson = healthArgs.includes("--json");
576-
const live = await deps.findLiveProxy();
576+
// A proxy that has only just bound can miss a single probe while its event loop
577+
// is still settling startup work — the same just-started race the stop paths
578+
// already retry for (#764, SERVICE_STOP_LIVENESS). Without this, `ocx health`
579+
// run seconds after a service restart reports a false negative on a proxy that
580+
// is in fact serving.
581+
const live = await deps.findLiveProxy({ attempts: 3 });
577582
if (wantsHealthJson) {
578583
console.log(JSON.stringify({ ok: !!live, pid: live?.pid ?? null, port: live?.port ?? null }));
579584
} else {

‎src/cli/index.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,14 @@ async function handleStart(options: { block?: boolean } = {}) {
240240
const present = process.env.OPENCODEX_API_AUTH_TOKEN?.trim();
241241
if (present) assertNotAdminToken(present);
242242
const requestedPort = parsePortOption();
243-
const owner = await findProxyOwnerBeforeJournalRecovery();
243+
// Always probe the configured port, even when both state files are absent. A
244+
// fallback-port sibling overwrites the pid/runtime records when it starts and
245+
// removes them on its own shutdown, so their absence proves nothing about the
246+
// configured port. Without the probe, `start` shadowed a healthy proxy with an
247+
// ephemeral-port copy and re-pointed client config at the copy; the next sibling
248+
// shutdown then left no runtime record for discovery at all. `handleEnsure`
249+
// already passes this; `handleStart` is the path that did not.
250+
const owner = await findProxyOwnerBeforeJournalRecovery({ probeConfiguredPort: true });
244251
if (owner.live) {
245252
// Service-wrapper context (opencodex-service.cmd `:loop`): a healthy proxy from
246253
// ANY source means the requested port is already served. Exit 0 so the wrapper's

‎tests/cli-dispatch.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,75 @@ describe("dispatchCommand exit codes", () => {
123123
});
124124
});
125125

126+
/**
127+
* `ocx health` probed once. A proxy that has only just bound can miss a single
128+
* probe while its event loop is still settling startup work, so health run
129+
* seconds after a service restart reported "Proxy not healthy" and exited 1 for
130+
* a proxy that was in fact serving. The stop paths already retry this exact race
131+
* under SERVICE_STOP_LIVENESS (#764); health did not.
132+
*/
133+
describe("health retries a just-started proxy", () => {
134+
test("passes a retry budget to findLiveProxy", async () => {
135+
const seen: (number | undefined)[] = [];
136+
const deps = {
137+
...fakeDeps,
138+
args: ["health"],
139+
findLiveProxy: async (io?: { attempts?: number }) => {
140+
seen.push(io?.attempts);
141+
return { pid: 4242, port: 10100 } as never;
142+
},
143+
} as unknown as CliDispatchDeps;
144+
145+
expect(await dispatchCommand({ kind: "command", command: "health", args: deps.args }, deps)).toBe(0);
146+
// More than one: a single attempt is the defect. The exact number is the
147+
// stop path's, and is asserted rather than inferred so a silent drop back to
148+
// one probe fails here.
149+
expect(seen).toEqual([3]);
150+
});
151+
152+
test("still reports an absent proxy as unhealthy", async () => {
153+
const deps = {
154+
...fakeDeps,
155+
args: ["health"],
156+
findLiveProxy: async () => null,
157+
} as unknown as CliDispatchDeps;
158+
159+
expect(await dispatchCommand({ kind: "command", command: "health", args: deps.args }, deps)).toBe(1);
160+
});
161+
});
162+
163+
/**
164+
* `handleStart` skipped the configured-port probe whenever the pid file and the
165+
* runtime-port record were both absent. That absence proves nothing: a
166+
* fallback-port sibling overwrites both records when it starts and removes them
167+
* when it stops, so `start` shadowed a healthy configured-port proxy with an
168+
* ephemeral-port copy and re-pointed client config at the copy.
169+
*
170+
* Source-level because the executable path binds real ports and spawns a real
171+
* child; this pins the one option that decides the behavior, next to the
172+
* `handleEnsure` call site that already had it right.
173+
*/
174+
describe("start probes the configured port before shadowing it (source-level)", () => {
175+
const cliSource = readFileSync(join(import.meta.dir, "../src/cli/index.ts"), "utf8");
176+
177+
test("every findProxyOwnerBeforeJournalRecovery call site asks for the probe", () => {
178+
const calls = cliSource.match(/findProxyOwnerBeforeJournalRecovery\s*\(([^)]*)\)/g) ?? [];
179+
// The declaration plus both call sites (handleStart, handleEnsure).
180+
expect(calls.length).toBeGreaterThanOrEqual(2);
181+
const invocations = calls.filter(call => !call.includes("options:"));
182+
expect(invocations.length).toBe(2);
183+
for (const call of invocations) {
184+
expect(call).toContain("probeConfiguredPort: true");
185+
}
186+
});
187+
188+
test("the probe option still gates on an explicit true", () => {
189+
// A truthy-but-not-true default would silently probe for callers that pass
190+
// nothing, which is a different behavior than the one asserted above.
191+
expect(cliSource).toContain("options.probeConfiguredPort === true");
192+
});
193+
});
194+
126195
describe("logout parses argv before touching the credential store", () => {
127196
/**
128197
* `ocx logout --json` used to lowercase `--json`, pass it to removeCredential as a provider

0 commit comments

Comments
 (0)