Skip to content

Commit 7a1565b

Browse files
authored
fix(cli): recheck live ownership before journal recovery (#7851)
* fix(cli): recheck live ownership before journal recovery Rebased onto dev (replaces the previous dev merges). The F4 bind-host source assertion now follows the normalization into src/server/bind-host.ts. * test(cli): supply definitive startup ownership fixture negatives Refuse both exact loopback health URLs in the child transport fixture and serve a valid foreign health identity from the held auxiliary-test canary. The ownership recovery fence correctly treats unexpected fixture errors and unreadable health bodies as unknown; keep its fail-closed behavior unchanged. Add a cross-platform fixture regression requiring all six family attempts to refuse. Preserve the connected-client desktop-claim and no-publication assertions, and keep the canary response at / unchanged. --------- Co-authored-by: JUN <243035832+lidge-jun@users.noreply.github.com>
1 parent cd26e92 commit 7a1565b

23 files changed

Lines changed: 953 additions & 104 deletions

‎docs-site/src/content/docs/getting-started/quickstart.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,12 @@ It stops before publishing a new runtime or changing those settings. Retry start
154154
local connectivity recovers; an installed background service retries through its service manager.
155155
A timeout does not permanently turn the new process into a secondary instance.
156156

157+
`Proxy ownership is unverified; startup refused` means the local owner check was
158+
inconclusive. OpenCodex preserves the PID record, recovery journal and shared client
159+
settings. Retry after the owner responds or exits; a failed health probe alone does
160+
not authorize crash recovery. A dead recorded process with no listener still recovers
161+
automatically.
162+
157163
IPv6 does not need to be enabled on loopback. Startup checks whether each loopback
158164
address can be bound locally and skips an unavailable family. Timeouts on an available
159165
family still stop startup until ownership can be verified.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"cli-start-owner-absence.test.ts": "cli",
3+
"cli-start-owner-evidence.test.ts": "cli",
4+
"proxy-liveness-owner-evidence.test.ts": "server",
5+
"proxy-liveness-recovery.test.ts": "server"
6+
}

‎scripts/test-layout/layout.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"version": 1,
33
"root": "tests",
4-
"explicitShards": ["layout-clients.json", "layout-codex-collision.json", "layout-agent-assertion.json", "layout-chat.json", "layout-replay.json", "layout-adapters.json", "layout-jev.json", "layout-workbuddy.json", "layout-combos.json", "layout-credit-renewal.json", "layout-server-inbound.json", "layout-providers.json", "layout-responses.json", "layout-exec-boundary.json", "layout-persistent-dashboard.json"],
4+
"explicitShards": ["layout-clients.json", "layout-codex-collision.json", "layout-agent-assertion.json", "layout-chat.json", "layout-replay.json", "layout-adapters.json", "layout-jev.json", "layout-workbuddy.json", "layout-combos.json", "layout-credit-renewal.json", "layout-server-inbound.json", "layout-providers.json", "layout-responses.json", "layout-exec-boundary.json", "layout-persistent-dashboard.json", "layout-start-ownership.json"],
55
"explicit": { "service-desktop-recovery.test.ts": "service", "provider-input-modalities.test.ts": "providers", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "codex-provider-routing.test.ts": "codex-integration", "config-native-reasoning-retention.test.ts": "config", "server-native-reasoning-retention-merge.test.ts": "server", "server-native-reasoning-retention.test.ts": "server", "responses-retained-reasoning-stream-recovery.test.ts": "responses", "openai-native-hosted-search-history.test.ts": "adapters/openai", "responses-native-compact-search-history.test.ts": "responses", "config-hosted-search-projection.test.ts": "config", "gcp-credential-boundary.test.ts": "adapters/google", "gcp-sa-marker.test.ts": "adapters/google", "gcp-sa-adapter.test.ts": "adapters/google", "management-gcp-credential-input.test.ts": "server", "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "cli-provider-list-active.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "bridge-terminal-refusal.test.ts": "adapters", "loop-terminal-refusal.test.ts": "images", "web-search-terminal-refusal.test.ts": "web-search", "combo-terminal-refusal.test.ts": "routing", "server-terminal-refusal-wiring.test.ts": "server", "incomplete-reason-normalization.test.ts": "responses", "advisor-retention.test.ts": "advisor", "responses-native-key-cooldown.test.ts": "responses", "responses-run-turn-key-readmission.test.ts": "responses", "qoder-spawn-readmission.test.ts": "adapters", "api-key-selection-cooldown.test.ts": "providers", "api-key-auto-pause-distribution.test.ts": "providers", "explicit-key-pause-oauth-boundary.test.ts": "providers", "server-chat-native-key-selection.test.ts": "server", "compact-key-selection.test.ts": "responses", "messages-native-key-selection.test.ts": "claude-integration", "coding-agent-windows-dispatch.test.ts": "adapters", "coding-agent-native-empty-argv.test.ts": "windows",
66
"stop-restore-history-ownership.test.ts": "service",
77
"cli-stop-refusal-transport.test.ts": "cli",

‎src/cli/index.ts‎

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ import {
4949
resolveCodexHistoryJobTarget,
5050
runCodexHistoryJob,
5151
} from "../codex/history-job";
52-
import { findCrossHomeOwner, markCrossHomeSibling, markLiveHomeSibling, reconcileStartupJournal } from "./cross-home-owner";
52+
import { findCrossHomeOwner, markCrossHomeSibling, markLiveHomeSibling } from "./cross-home-owner";
5353
import { inspectClientRotationRecoveryGate, readClientConnectionState } from "../client/state";
5454
import {
5555
codexAutoStartEnabled,
@@ -165,7 +165,7 @@ import { initializeNodeLauncherContext } from "./launcher-context";
165165
import { assertConnectedClientStopSupported, clearRestoredStopReceipts, connectedClientStopSkipLine, notOwnedTeardownIsAcceptable, preflightConnectedClientStop, preserveConnectedClientRoutingOnExit, restoreBoundaryOwnership, restoreSharedClientStateAfterStop, settleUnrestoredStopBoundary } from "./stop-restore";
166166
import { stopRestoreWriteGuard } from "./stop-restore-guard";
167167
import { startClientRuntimeUnderOwnershipLease } from "./client-start-fence";
168-
import { recoverStartStateUnderOwnershipLease } from "./start-owner-fence";
168+
import { recoverStartJournalAfterOwnerRecheck, recoverStartStateUnderOwnershipLease } from "./start-owner-fence";
169169
import { handledSignalExitCode } from "../lib/handled-signal-exit";
170170
import { createLocalAttestationSecret } from "../lib/local-management-attestation";
171171
import { MEMORY_DRAIN_RESTART_MS, REPLACEMENT_READY_TIMEOUT_MS, RESTART_REOBSERVE_RESERVE_MS } from "../lib/system-restart-contract";
@@ -371,7 +371,7 @@ async function findProxyOwnerBeforeJournalRecovery(
371371
const hasRuntimeOwner = readRuntimePort() !== null;
372372
const shouldProbe = pidSnapshot !== null || hasRuntimeOwner || options.probeConfiguredPort === true;
373373
// A negative answer lets the caller walk past a proxy it was supposed to find and
374-
// deletes this home's stale pid record. Supervised starts defer that write to the
374+
// deletes this home's stale pid record. Start and ensure defer that write to the
375375
// lease-held owner recheck; journal recovery follows cross-home discovery.
376376
// One 750ms probe is not enough evidence for that (#5004) — a transport
377377
// failure is indistinguishable from an empty port, and the reported Windows duplicate
@@ -439,7 +439,14 @@ async function handleStart(options: { block?: boolean } = {}) {
439439
let siblingStart = honorSiblingMarker(process.env, consumeSiblingHandoff) !== null;
440440
// A restart replacement waits out its draining parent instead of refusing it, and bounds its handoff log (restart-handoff.ts).
441441
const restartParent = { restartParentPid: takeRestartHandoffMarkers(process.env), requestedPort, ocxService: process.env.OCX_SERVICE };
442-
const owner = await probeOwnerPastRestartParent(() => findProxyOwnerBeforeJournalRecovery({ probeConfiguredPort: true, deferPidCleanup: supervisedServiceChild }), restartParent);
442+
const owner = await probeOwnerPastRestartParent(() => findProxyOwnerBeforeJournalRecovery({ probeConfiguredPort: true, deferPidCleanup: true }), restartParent);
443+
if (!owner.live) siblingStart = await recoverStartStateUnderOwnershipLease({
444+
supervised: supervisedServiceChild,
445+
acquireLease: () => acquireOwnershipMutationLease(serviceStatePaths()),
446+
decide: () => serviceChildOwnershipDecisionForClassifiedChild(supervisedServiceChild),
447+
stayOut: refusal => { console.error("❌ " + refusal); process.exit(serviceStayOutExitCode()); },
448+
recover: () => recoverStartJournalAfterOwnerRecheck(owner, siblingStart),
449+
});
443450
if (owner.live) {
444451
// Rationale and the full decision table live on `decideStartWithLiveOwner`.
445452
const decision = decideStartWithLiveOwner({
@@ -468,18 +475,6 @@ async function handleStart(options: { block?: boolean } = {}) {
468475
+ `Startup continues only for an independent OPENCODEX_HOME; one state directory has one spend-ledger writer.`,
469476
);
470477
}
471-
siblingStart = await recoverStartStateUnderOwnershipLease({
472-
supervised: supervisedServiceChild,
473-
acquireLease: () => acquireOwnershipMutationLease(serviceStatePaths()),
474-
decide: () => serviceChildOwnershipDecisionForClassifiedChild(supervisedServiceChild),
475-
stayOut: refusal => { console.error("❌ " + refusal); process.exit(serviceStayOutExitCode()); },
476-
recover: async () => {
477-
if (!owner.live && supervisedServiceChild) removePidIfValueIs(owner.pidSnapshot);
478-
if (!owner.live && !siblingStart) siblingStart = await markCrossHomeSibling();
479-
if (!siblingStart) reconcileStartupJournal();
480-
return siblingStart;
481-
},
482-
});
483478

484479
updateRestartChild?.check();
485480
const clientState = readClientConnectionState();
@@ -531,7 +526,7 @@ async function handleStart(options: { block?: boolean } = {}) {
531526
console.error("❌ " + leasedChildOwnership.refusal);
532527
throw new StartCommandExit(serviceStayOutExitCode());
533528
}
534-
// The earlier probe owned journal cleanup. This one owns the bind decision: an
529+
// Recovery rechecked liveness under its lease. This fence owns the bind decision: an
535530
// updater may have stopped the old runtime and acquired this lease for replacement.
536531
const fencedLive = await findLiveProxy(START_OWNERSHIP_LIVENESS);
537532
if (fencedLive) {
@@ -817,8 +812,14 @@ function detachedStartEnvironment(): NodeJS.ProcessEnv {
817812
}
818813

819814
async function handleEnsure(options: { existingIsSuccess?: boolean; forceStart?: boolean; onSpawn?: (child: ReturnType<typeof spawn>) => void } = {}): Promise<boolean> {
820-
const owner = await findProxyOwnerBeforeJournalRecovery({ probeConfiguredPort: true });
821-
if (!owner.live && !(await markCrossHomeSibling())) reconcileStartupJournal();
815+
const owner = await findProxyOwnerBeforeJournalRecovery({ probeConfiguredPort: true, deferPidCleanup: true });
816+
if (!owner.live) await recoverStartStateUnderOwnershipLease({
817+
supervised: false,
818+
acquireLease: () => acquireOwnershipMutationLease(serviceStatePaths()),
819+
decide: () => ({ kind: "proceed" }),
820+
stayOut: () => { throw new Error("ordinary ensure has no service stay-out decision"); },
821+
recover: () => recoverStartJournalAfterOwnerRecheck(owner),
822+
});
822823
// A later ensure can find this home's sibling alive; the other port still owns shared clients.
823824
if (owner.live) await markLiveHomeSibling(owner.live);
824825
const config = loadConfig();

‎src/cli/loopback-family.ts‎

Lines changed: 2 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,2 @@
1-
/** A failed connect cannot distinguish an absent loopback address from a slow owner. */
2-
export type LoopbackFamilyAvailability = "available" | "unavailable" | "unknown";
3-
4-
function bindLoopback(hostname: string): { stop(): void } {
5-
return Bun.listen({ hostname, port: 0, socket: { data(socket) { socket.end(); } } });
6-
}
7-
8-
/**
9-
* Ask the kernel whether the concrete local address can be bound, independently of
10-
* routing/connect timeouts. Only address/family absence permits skipping discovery;
11-
* permissions, resource exhaustion and other failures leave owner evidence unknown.
12-
* The ephemeral listener is closed synchronously and never accepts client traffic.
13-
*/
14-
export function loopbackFamilyAvailability(
15-
hostname: string,
16-
bindFn: (hostname: string) => { stop(): void } = bindLoopback,
17-
): LoopbackFamilyAvailability {
18-
const address = hostname === "[::1]" ? "::1" : hostname;
19-
if (address !== "::1" && address !== "127.0.0.1") return "unknown";
20-
let listener: { stop(): void };
21-
try {
22-
listener = bindFn(address);
23-
} catch (error) {
24-
const code = (error as { code?: unknown } | null)?.code;
25-
return code === "EADDRNOTAVAIL" || code === "EAFNOSUPPORT"
26-
|| code === "EPROTONOSUPPORT"
27-
? "unavailable" : "unknown";
28-
}
29-
listener.stop();
30-
return "available";
31-
}
1+
// Keep the CLI discovery surface while sharing kernel family admission with recovery.
2+
export { loopbackFamilyAvailability, type LoopbackFamilyAvailability } from "../lib/loopback-family";

‎src/cli/start-owner-fence.ts‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,33 @@
11
import type { ServiceChildOwnershipDecision } from "../service/service-child-ownership";
2+
import { removePidIfValueIs } from "../config/process-state";
3+
import { observeProxyLiveness, START_OWNERSHIP_LIVENESS, type LiveProxy } from "../server/proxy-liveness";
4+
import { markCrossHomeSibling, reconcileStartupJournal } from "./cross-home-owner";
25

3-
/** Fence shared client-state recovery against a claim committed after the early owner probe. */
6+
/** Called only under the ownership lease; a negative early probe grants no mutation authority. */
7+
export async function recoverStartJournalAfterOwnerRecheck(
8+
owner: { live: LiveProxy | null; pidSnapshot: number | null },
9+
sibling = false,
10+
): Promise<boolean> {
11+
const observation = await observeProxyLiveness(START_OWNERSHIP_LIVENESS);
12+
owner.live = observation.live;
13+
if (owner.live) return sibling;
14+
if (observation.kind !== "absent") {
15+
throw new Error("Proxy ownership is unverified; startup refused. PID record and recovery journal were preserved. Retry when the owner can be verified.");
16+
}
17+
removePidIfValueIs(owner.pidSnapshot);
18+
if (!sibling) sibling = await markCrossHomeSibling();
19+
if (!sibling) reconcileStartupJournal();
20+
return sibling;
21+
}
22+
23+
/** Hold ownership stable through the final liveness check and shared-state recovery. */
424
export async function recoverStartStateUnderOwnershipLease(deps: {
525
supervised: boolean;
626
acquireLease: () => { release(): void };
727
decide: () => ServiceChildOwnershipDecision;
828
stayOut: (refusal: string) => never;
929
recover: () => Promise<boolean>;
1030
}): Promise<boolean> {
11-
if (!deps.supervised) return deps.recover();
1231
const lease = deps.acquireLease();
1332
let released = false;
1433
const release = () => {
@@ -17,7 +36,7 @@ export async function recoverStartStateUnderOwnershipLease(deps: {
1736
lease.release();
1837
};
1938
try {
20-
const decision = deps.decide();
39+
const decision = deps.supervised ? deps.decide() : { kind: "proceed" as const };
2140
if (decision.kind === "stay-out") {
2241
// stayOut exits the process, so a finally block would never release the lease.
2342
release();

‎src/lib/loopback-family.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/** A failed connect cannot distinguish an absent loopback address from a slow owner. */
2+
export type LoopbackFamilyAvailability = "available" | "unavailable" | "unknown";
3+
4+
function bindLoopback(hostname: string): { stop(): void } {
5+
return Bun.listen({ hostname, port: 0, socket: { data(socket) { socket.end(); } } });
6+
}
7+
8+
/**
9+
* Ask the kernel whether the concrete local address can be bound, independently of
10+
* routing/connect timeouts. Only address/family absence permits skipping discovery;
11+
* permissions, resource exhaustion and other failures leave owner evidence unknown.
12+
* The ephemeral listener is closed synchronously and never accepts client traffic.
13+
*/
14+
export function loopbackFamilyAvailability(
15+
hostname: string,
16+
bindFn: (hostname: string) => { stop(): void } = bindLoopback,
17+
): LoopbackFamilyAvailability {
18+
const address = hostname === "[::1]" ? "::1" : hostname;
19+
if (address !== "::1" && address !== "127.0.0.1") return "unknown";
20+
let listener: { stop(): void };
21+
try {
22+
listener = bindFn(address);
23+
} catch (error) {
24+
const code = (error as { code?: unknown } | null)?.code;
25+
return code === "EADDRNOTAVAIL" || code === "EAFNOSUPPORT"
26+
|| code === "EPROTONOSUPPORT"
27+
? "unavailable" : "unknown";
28+
}
29+
listener.stop();
30+
return "available";
31+
}

‎src/server/bind-host.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/** The public listener's bind spelling, shared with ownership discovery. */
2+
export function normalizeBindHostname(hostname: string | undefined): string {
3+
const configuredHost = hostname?.trim();
4+
return !configuredHost || /^localhost\.?$/i.test(configuredHost) ? "127.0.0.1" : configuredHost;
5+
}

‎src/server/index.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { remoteWorkspaceEnabled } from "../remote-control/workspace-activation";
22
import { scheduleDesktopCompatibilityStartup } from "./index/desktop-compatibility-startup";
33
import { AuxiliaryListenerBindError } from "./ports";
4+
import { normalizeBindHostname } from "./bind-host";
45
import { configureInboundBodyBudget, runAdmittedBodyWork } from "./inbound-body-admission";
56
import {
67
buildWarmupCompletionFrames,
@@ -327,8 +328,7 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe
327328
// resolves localhost→127.0.0.1): on Windows `localhost` resolves ::1-first, but the injected URL
328329
// is 127.0.0.1, so binding literal "localhost" would reintroduce the F4 refusal. Wildcards
329330
// (0.0.0.0/::) and specific hosts are left untouched so intentional exposure is preserved.
330-
const configuredHost = config.hostname?.trim();
331-
const bindHost = !configuredHost || /^localhost\.?$/i.test(configuredHost) ? "127.0.0.1" : configuredHost;
331+
const bindHost = normalizeBindHostname(config.hostname);
332332

333333
// Unauthenticated loopback listener (#1102). Off unless explicitly enabled.
334334
// A port-less enabled entry is the companion form: same port as the public listener, on

0 commit comments

Comments
 (0)