Repository navigation
fix(link): restore guarded stop cleanup with native Windows owner proof #8933
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
bd2ba44
9914824
e3c6154
8e8623b
d04a6d0
6eb933c
8e4d926
fae4f45
0ac89ad
79e4b63
456946c
2d3a18a
8de1bcf
b50f314
1a037e9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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; | ||
| } | ||
| } |
| 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; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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, | ||
|
|
@@ -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; | ||
|
|
@@ -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 | ||
|
|
@@ -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>; | ||
|
|
@@ -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; | ||
| } | ||
| } else await teardown(); | ||
| // Recycling back to standalone after `ocx disconnect` must actually bring a standalone | ||
| // proxy back, under every launch shape. | ||
| // | ||
|
|
@@ -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, | ||
| }); | ||
|
|
@@ -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 }, | ||
|
|
@@ -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); | ||
| } | ||
|
|
@@ -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, | ||
|
|
@@ -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; | ||
|
|
@@ -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. | ||
|
|
@@ -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`. | ||
|
|
@@ -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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When an unsupervised Link restart's replacement fails and lifecycle-lock contention lasts for the 10-second rollback budget, every Useful? React with 👍 / 👎. |
||
| } | ||
| }, | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a Home-initiated Link Child is disconnected via
/api/machine/disconnectwhile an existing Home sync still holdswithLinkApply, 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 👍 / 👎.