Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion docs-site/src/content/docs/es/reference/cli/lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ Si OpenCodex no puede confirmar que un envoltorio terminó porque no dispone de
de objeto de proceso (handle), como puede ocurrir en ARM64, compruébalo en el Administrador de tareas desde la sesión
de su propietario, detenlo si sigue en ejecución y vuelve a intentarlo.

Si no puede demostrarse que el servicio se detuvo, `ocx stop` no envía una solicitud de parada al proxy, deja intacta la configuración del cliente y falla. Con `--json`, el resumen conserva `outcome: "failed"` y `proxy: "unknown"`, y añade `serviceStopReason`:
Si no puede demostrarse que el servicio se detuvo, `ocx stop` no envía una solicitud de parada al proxy ni continúa con la restauración nativa compartida. En un Child de Remote Link, el prevuelo puede haber eliminado ya las integraciones de archivos propiedad del Link y pausado la sincronización; repara la parada del servicio y vuelve a ejecutar `ocx stop`. El comando falla. Con `--json`, el resumen conserva `outcome: "failed"` y `proxy: "unknown"`, y añade `serviceStopReason`:

| `serviceStopReason` | Significado | Qué hacer |
|---|---|---|
Expand Down
8 changes: 5 additions & 3 deletions docs-site/src/content/docs/reference/cli/lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,11 @@ eligible for termination, stop it from its owning Windows session using Task Man
If OpenCodex cannot confirm a wrapper's exit without a process handle, as can happen on ARM64,
check it in Task Manager from its owning session, stop it if it is still running, and retry.

When the service cannot be proven stopped, `ocx stop` sends no stop request to the proxy, leaves
your client configuration alone, and fails. With `--json` the summary keeps `outcome: "failed"`
and `proxy: "unknown"`, and adds `serviceStopReason`:
When the service cannot be proven stopped, `ocx stop` sends no stop request to the proxy and
does not proceed to shared native restoration. On a Remote Link Child, preflight may already have
removed Link-owned file integrations and paused sync; repair the service stop and retry `ocx stop`.
The command fails. With `--json` the summary keeps `outcome: "failed"` and `proxy: "unknown"`,
and adds `serviceStopReason`:

| `serviceStopReason` | Meaning | What to do |
|---|---|---|
Expand Down
3 changes: 3 additions & 0 deletions scripts/test-layout/layout-clients.json
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,9 @@
"client-link-runtime.test.ts": "clients",
"client-link-stop.test.ts": "clients",
"client-link-stop-recovery.test.ts": "clients",
"windows-stop-owner-identity.test.ts": "windows",
"client-recycle-exclusion.test.ts": "clients",
"client-restart-rollback-lock.test.ts": "clients",
"client-link-stop-sibling.test.ts": "clients",
"link-routes.test.ts": "clients",
"client-link-state.test.ts": "clients",
Expand Down
29 changes: 29 additions & 0 deletions src/client/runtime-recycle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { withConfigMutationLockSync } from "../config";
import type { OcxClientConnectionConfig } from "../types";
import { withLinkApply } from "./link-home";
import { clientConnectionEnded } from "./runtime-restart";
import { pendingClientConnectMayOwnToken, readClientConnectionStateWithEvidence } from "./state";

/**
* Called outside L: Link apply exclusion is outermost in the apply -> N -> L -> C order.
* Once admitted, keep it through all teardown awaits; a new connect cannot commit halfway.
*/
export async function runClientRecycleWithAdmission(
served: OcxClientConnectionConfig,
allowed: () => boolean,
teardown: () => Promise<void>,
): Promise<boolean> {
let admitted = false;
try {
return await withLinkApply(async () => {
admitted = withConfigMutationLockSync(() => allowed() && !pendingClientConnectMayOwnToken()
&& clientConnectionEnded(served, readClientConnectionStateWithEvidence()));
if (!admitted) return false;
await teardown();
return true;
});
} catch (error) {
if (admitted) throw error; // A started teardown must not masquerade as an admission refusal.
return false;
}
}
29 changes: 29 additions & 0 deletions src/client/runtime-rollback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { ConfigMutationLockError } from "../config";
import { CLIENT_RESTART_REBIND_WAIT_MS } from "../lib/system-restart-contract";

export type ClientRollbackAttempt = "published" | "busy" | "refused";

export function retryableClientRollbackLock(error: unknown): boolean {
if (error && typeof error === "object" && "code" in error && error.code === "client_lifecycle_busy") return true;
const cause = error instanceof ConfigMutationLockError ? error.cause : undefined;
const code = cause && typeof cause === "object" && "code" in cause ? cause.code : undefined;
return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED";
}

/** Each busy attempt must close its unpublished listener before this helper may yield. */
export async function retryClientRollback(
attempt: (remainingMs: number) => Promise<ClientRollbackAttempt>,
io: { now?: () => number; sleep?: (ms: number) => Promise<unknown>; budgetMs?: number } = {},
): Promise<boolean> {
const now = io.now ?? (() => performance.now());
const deadline = now() + (io.budgetMs ?? CLIENT_RESTART_REBIND_WAIT_MS);
while (now() < deadline) {
const result = await attempt(Math.max(0, deadline - now()));
if (result === "published") return true;
if (result !== "busy") return false;
const remaining = deadline - now();
if (remaining <= 0) return false;
await (io.sleep ?? Bun.sleep)(Math.min(50, remaining));
}
return false;
}
104 changes: 66 additions & 38 deletions src/client/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import { createLocalAttestationSecret } from "../lib/local-management-attestatio
import { loadServiceTokenFromFile, serviceApiTokenFingerprint } from "../lib/service-secrets";
import { handledSignalExitCode } from "../lib/handled-signal-exit";
import {
CLIENT_RESTART_REBIND_WAIT_MS,
DESKTOP_RESTART_EXIT_CODE,
DESKTOP_SUPERVISED_ENV,
DESKTOP_SUPERVISED_PORT_WAIT_MS,
Expand All @@ -39,9 +38,11 @@ import { createLinkParityReporter, type LinkParityReporter } from "./link-parity
import { restoreLinkClientRoutingBeforeExit } from "./stop-routing";
import { observeClientStopOwner } from "./stop-teardown-owner";
import { SUPERVISOR_MARKER_ENVS } from "../lib/supervisor-markers";
import { markClientRuntimeStopping, markClientRuntimeStoppingWithRetry } from "./sync-runtime";
import { isPublishedRuntimeStopping, markClientRuntimeStopping, markClientRuntimeStoppingWithRetry } from "./sync-runtime";
import { startRouteIntentTick, type RouteIntentTick } from "../integrations/route-intent-tick";
import { startRouteIntentWatch, type RouteIntentRuntimeWatch } from "./route-intent-watch";
import { runClientRecycleWithAdmission } from "./runtime-recycle";
import { retryClientRollback, retryableClientRollbackLock, type ClientRollbackAttempt } from "./runtime-rollback";

let activeServer: Server<unknown> | null = null;
let activePort: number | null = null;
Expand All @@ -60,6 +61,7 @@ let clientStopping = false;
let explicitClientStopRequested: boolean | undefined;
let explicitClientStopOwner: ClientStopOwner | undefined;
let standaloneRecycleAllowed = () => !clientStopping;
let activeLinkForRecycle: OcxClientConnectionConfig | undefined;

/**
* When this runtime's process started (OCX-6, P5): what `/healthz` reports as `startedAt` and the
Expand Down Expand Up @@ -90,6 +92,8 @@ const LINK_BIND_ATTEMPTS = 3;
export interface ClientRuntimeIo {
/** Link-mode port budget; defaults to {@link LINK_PORT_WAIT_MS}. */
portWaitMs?: number;
/** Rollback bind attempts share one deadline instead of restarting the port wait. */
bindDeadlineAt?: number;
startListener?: typeof startMachineListener;
/** Which supervisor owns this process for a bound restart; tests replace the production check. */
restartSupervisor?: () => Promise<"service" | "desktop" | null>;
Expand Down Expand Up @@ -200,27 +204,36 @@ export async function recycleStandalone(
const exit = io.exitProcess ?? ((code: number) => { process.exit(code); });
// Capture the one-use sibling handoff before this process removes its runtime record.
const serviceSupervised = (io.serviceSupervised ?? (() => process.env.OCX_SERVICE === "1"))();
const replacementEnv = port && !serviceSupervised
? withSiblingMarker(standaloneRecycleEnv(process.env, disconnectedTokenFingerprint), issueSiblingHandoff)
: null;
activeCredentialObservation?.stop(); activeCredentialObservation = null;
activeHubRelayRefresh?.stop(); activeHubRelayRefresh = null;
activeReporter?.stop(); activeReporter = null;
activeRouteWatch?.stop(); activeRouteWatch = null;
activeRouteSync?.stop(); activeRouteSync = null;
try {
await activeSupervisor?.stop();
} catch (error) {
console.warn(`[client] link supervisor stop failed: ${error instanceof Error ? error.message : String(error)}`);
}
activeSupervisor = null;
try {
activeServer?.stop(true);
} catch (error) {
console.warn(`[client] listener stop failed: ${error instanceof Error ? error.message : String(error)}`);
}
cleanup();
await flushLinkDiagnostics();
let replacementEnv: NodeJS.ProcessEnv | null = null;
const teardown = async () => {
replacementEnv = port && !serviceSupervised
? withSiblingMarker(standaloneRecycleEnv(process.env, disconnectedTokenFingerprint), issueSiblingHandoff)
: null;
activeCredentialObservation?.stop(); activeCredentialObservation = null;
activeHubRelayRefresh?.stop(); activeHubRelayRefresh = null;
activeReporter?.stop(); activeReporter = null;
activeRouteWatch?.stop(); activeRouteWatch = null;
activeRouteSync?.stop(); activeRouteSync = null;
try {
await activeSupervisor?.stop();
} catch (error) {
console.warn(`[client] link supervisor stop failed: ${error instanceof Error ? error.message : String(error)}`);
}
activeSupervisor = null;
try {
await activeServer?.stop(true);
} catch (error) {
console.warn(`[client] listener stop failed: ${error instanceof Error ? error.message : String(error)}`);
}
cleanup();
await flushLinkDiagnostics();
};
if (activeLinkForRecycle) {
if (!(await runClientRecycleWithAdmission(activeLinkForRecycle, standaloneRecycleAllowed, teardown))) {
recycleScheduled = false;
return;
Comment on lines +232 to +234

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retry scheduled recycle after transient apply-lock contention

When a Home-initiated Link Child is disconnected via /api/machine/disconnect while an existing Home sync still holds withLinkApply, the scheduled 50 ms recycle fails admission here and is silently discarded. That runtime has no tunnel supervisor to schedule another recycle, and the API has already returned 202; releasing the apply lock later does not trigger another attempt. The disconnected Link listener consequently remains bound instead of handing the port to a standalone proxy. Distinguish transient apply/config-lock contention from durable ownership refusals and reschedule it with bounded backoff while rechecking admission.

Useful? React with 👍 / 👎.

}
} else await teardown();
// Recycling back to standalone after `ocx disconnect` must actually bring a standalone
// proxy back, under every launch shape.
//
Expand Down Expand Up @@ -289,25 +302,28 @@ export async function bindClientListener(
): Promise<{ server: Server<unknown>; port: number }> {
const { linkMode } = request;
const portWaitMs = io.portWaitMs ?? (linkMode ? linkPortWaitMs() : LINK_PORT_WAIT_MS);
const deadline = Date.now() + portWaitMs;
const deadline = io.bindDeadlineAt ?? Date.now() + portWaitMs;
const remaining = () => Math.max(0, deadline - Date.now());
const busy = (cause: unknown) => new Error(
`link mode needs port ${request.configuredPort}; free it or change port`,
{ cause },
);
let port: number;
try {
if (io.bindDeadlineAt !== undefined && remaining() <= 0) throw busy("rollback deadline expired");
if (linkMode) {
const { reclaimListenPort } = await import("../server/port-reclaim");
await reclaimListenPort(request.configuredPort, "127.0.0.1", {
timeoutMs: portWaitMs,
timeoutMs: io.bindDeadlineAt === undefined ? portWaitMs : Math.min(portWaitMs, remaining()),
intervalMs: 100,
scanIntervalMs: 500,
killOcxHolders: false,
dropTcpRows: true,
});
}
port = await findAvailablePort(request.preferred, "127.0.0.1", {
preferRetryMs: request.explicitPort ? PINNED_PREFER_RETRY_MS : 750,
preferRetryMs: Math.min(request.explicitPort ? PINNED_PREFER_RETRY_MS : 750,
io.bindDeadlineAt === undefined ? Infinity : remaining()),
preferRetryIntervalMs: 50,
allowEphemeralFallback: linkMode ? false : !request.explicitPort,
});
Expand All @@ -318,6 +334,7 @@ export async function bindClientListener(
const startListener = io.startListener ?? startMachineListener;
for (let attempt = 1; ; attempt += 1) {
try {
if (io.bindDeadlineAt !== undefined && remaining() <= 0) throw busy("rollback deadline expired");
const server = startListener(port, {
state: request.state,
machineApi: { scheduleStandaloneRecycle },
Expand All @@ -332,8 +349,8 @@ export async function bindClientListener(
} catch (error) {
// Check-then-bind: the port can be taken between the probe and Bun.serve.
if (!linkMode || !isAddrInUse(error)) throw error;
const waitMs = Math.max(1_000, deadline - Date.now());
if (attempt >= LINK_BIND_ATTEMPTS
const waitMs = io.bindDeadlineAt === undefined ? Math.max(1_000, remaining()) : remaining();
if (attempt >= LINK_BIND_ATTEMPTS || waitMs <= 0
|| !(await waitForPortAvailable(port, "127.0.0.1", { timeoutMs: waitMs, intervalMs: 100 }))) {
throw busy(error);
}
Expand Down Expand Up @@ -384,7 +401,7 @@ export async function startClientRuntime(
&& (!explicitClientStopOwner || observeClientStopOwner(explicitClientStopOwner) !== "confirmed-stale");
};
// An unpublishable rollback closes the new listener before the caller considers a recycle.
const serve = async (rollback?: { port: number; portWaitMs: number }): Promise<boolean> => {
const serve = async (rollback?: { port: number; portWaitMs: number }): Promise<ClientRollbackAttempt> => {
const supervisor = supervised
? createClientLinkSupervisor({
diagnostic: recordLinkDiagnostic,
Expand Down Expand Up @@ -413,17 +430,20 @@ export async function startClientRuntime(
...(linkReadiness ? { linkReadiness } : {}),
...(supervisor ? { linkConnectionGeneration: () => supervisor.connectionGeneration() }
: homeInitiated && link ? { linkConnectionGeneration: () => verifiedHomeConnection(link.linkId) } : {}),
}, rollback === undefined ? io : { ...io, portWaitMs: rollback.portWaitMs });
}, rollback === undefined ? io : { ...io, portWaitMs: rollback.portWaitMs, bindDeadlineAt: Date.now() + rollback.portWaitMs });
let servingGeneration: string;
const publishRecord = (): void => {
// A parent stop can arrive after restart admission. Never clear its fence on rollback;
// a fresh process has another attestation identity and cannot inherit this request.
if (rollback) observeExplicitStop();
writePid(process.pid);
// A new generation refuses commits from syncs admitted before the failed restart.
writeRuntimePort({ ...clientRuntimeRecord(process.pid, boundPort, attestationSecret), servingGeneration: randomUUID(),
servingGeneration = randomUUID();
writeRuntimePort({ ...clientRuntimeRecord(process.pid, boundPort, attestationSecret), servingGeneration,
clientLinkOwner });
};
const activate = (): void => {
activeLinkForRecycle = linkMode ? state.value : undefined;
activeServer = server;
activePort = boundPort;
servedPort = boundPort;
Expand All @@ -437,15 +457,18 @@ export async function startClientRuntime(
if (linkMode && state.value.link && linkKey) {
activeReporter = createLinkParityReporter({ connection: state.value, linkKey, runtimeStartedAt: CLIENT_RUNTIME_STARTED_AT });
activeReporter.start();
const scheduler = startRouteIntentTick(state.value, { onApplied: () => activeReporter?.requestReport() });
const scheduler = startRouteIntentTick(state.value, {
deferPeriodic: () => isPublishedRuntimeStopping({ pid: process.pid, port: boundPort, attestationSecret, servingGeneration }),
onApplied: () => activeReporter?.requestReport(),
});
activeRouteSync = scheduler;
activeRouteWatch = startRouteIntentWatch(state.value, linkKey, { requestSync: () => scheduler.requestSync() });
}
};
if (!rollback) {
publishRecord();
activate();
return true;
return "published";
}
// Admission and publication are synchronous after bind. A busy lock must close the
// rebound listener before yielding. Link takes C to preserve an explicit stop fence.
Expand All @@ -454,15 +477,16 @@ export async function startClientRuntime(
publishRecord();
return true;
};
let published = false;
let published = false, busy = false;
try {
published = withClientLifecycleSync(() => linkMode ? withConfigMutationLockSync(publishIfOwned) : publishIfOwned());
} catch { /* failed admission */ }
} catch (error) { busy = retryableClientRollbackLock(error); }
if (published) activate();
else {
try { await server.stop(true); } catch { /* never published */ }
// Do not retain an unrecorded listener across the contention retry's await.
await server.stop(true);
}
return published;
return published ? "published" : busy ? "busy" : "refused";
};

// Stop everything this process serves, giving in-flight requests up to `drainMs`.
Expand Down Expand Up @@ -553,7 +577,11 @@ export async function startClientRuntime(
await recycleAfterRollback();
return;
}
if (!(await serve({ port: servedPort, portWaitMs: CLIENT_RESTART_REBIND_WAIT_MS }))) {
if (!(await retryClientRollback(async remainingMs => {
observeExplicitStop();
if (clientRestartRollbackAction(state.value, readClientConnectionState()) === "recycle") return "refused";
return serve({ port: servedPort, portWaitMs: remainingMs });
}))) {
await recycleAfterRollback();
Comment on lines +584 to 585

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Fail rollback when the unchanged connection cannot be republished

When an unsupervised Link restart's replacement fails and lifecycle-lock contention lasts for the 10-second rollback budget, every serve() attempt closes its rebound listener and retryClientRollback() returns false. This fallback then calls recycleStandalone(), but its new clientConnectionEnded admission rejects the unchanged connection and returns normally. resume() therefore resolves with activeServer === null and a retained stopping record, leaving the process alive without serving requests instead of taking the controller's failed-resume exit path. Handle unchanged-connection exhaustion as a failed resume, or successfully rebind, rather than treating a refused recycle as recovery.

Useful? React with 👍 / 👎.

}
},
Expand Down
Loading
Loading