Skip to content

feat(relay): capability-gated owner reset with a durable preparation journal (#16741 T3 R1) - #24418

Merged
OrcaWin merged 1 commit into
mainfrom
OrcaWin/node-rt-p3-t3-r1
Oct 1, 2026
Merged

OrcaWin merged 1 commit into
mainfrom
OrcaWin/node-rt-p3-t3-r1

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1336 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1336
Prod 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​850 $\color{#cf222e}{\Huge{\mathbf{−}}}$​42 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​808

This is T3 slice R1 of the #16741 port (SSH reset): the relay half of a new "owner reset", with no client caller yet. It builds on the relay owner probes #24414 added.

ELI5

The program Orca runs on an SSH host (the relay) learns a new, carefully staged way to shut itself down when its owner asks. It also learns to leave a note on disk saying "I agreed to reset", so the request can be confirmed later even if the relay has already exited. The desktop app doesn't use any of this yet. We ship the host side first because people update their desktop app and their SSH hosts at different times.

What Changed

Before: a relay could only shut down on its own idle timer or on a signal. Nothing let its owning client ask for an orderly shutdown and later prove that the shutdown was agreed.

After: user-visible behavior is unchanged. Underneath:

  • New relay methods:
    • relay.reset asks the relay to prepare a shutdown. Only the current session owner can send it, and it must match the relay's runtime incarnation and the owner's generation and lease.
    • relay.recoverPreparedReset lets a reconnected owner confirm a reset that was already prepared, without repeating the disposal.
  • New capabilities in relay.status:
    • relay.ownerReset.v1 (plus the relay's runtime incarnation);
    • relay.durableResetPreparation.v1, advertised once a journal exists.
  • Durable journal: each prepared reset is written to <endpointDir>/owner-reset-preparations as immutable evidence that it was agreed. It is never treated as evidence that processes exited.
  • Reader mode: relay.js --read-reset-preparation is a read-only mode that reads that journal from stdin and stdout without starting a daemon. A client can confirm a prepared reset after the relay is gone.
  • Shutdown split: relay shutdown is now prepareShutdown (dispose PTYs and owned processes, keep the transport up) followed by finishShutdown (exit). That way a reset's reply reaches the client before the process ends.
    • Idle and signal shutdown behave exactly as before: same order, the same deferred retry when disposal fails, and no new wait on in-flight requests.
    • Only a reset waits for admitted requests to drain.

Why

Relays and clients update independently, so mixed versions are the normal state. Shipping the host side first means that by the time a client starts calling relay.reset, many hosts already support it.

Negotiation is explicit:

  • Old relays advertise neither capability and answer method-not-found, which a client must treat as "reset unavailable", never "reset done".
  • Old clients never call the new methods, so a new relay with an old client sees only the shutdown refactor.

Splitting the existing shutdown, rather than adding a second shutdown path, keeps one place where the relay exits. The new tests pin today's idle and signal behavior, and the idle and deferred-retry cases pass against main's original lifecycle too.

Left out:

  • network-tunnel draining (T4);
  • the PTY ownership-transfer fence (T7);
  • all Bun handling;
  • the client side (records, transaction and wiring, which are parked until the T7/T8 callers are scheduled).

Linked Issue

Part of the Node runtime plan, Phase 3, T3 slice R1. Ported from #16741 (a68b6f3). Builds on #24414.

Visual Proof

N/A. This is a relay-side protocol with no client caller and no UI.

Testing

  • New tests:

    • owner reset (prepare, replay, refusal and authority checks);
    • registration and status capabilities;
    • preparation journal;
    • reader, including an integration run of the esbuild-bundled relay.js under Node with an empty PATH;
    • real-dispatcher replay across same-transport, reconnect and new-coordinator;
    • preparation contract;
    • a wire-contract test pinning relay.ownerReset.v1, relay.durableResetPreparation.v1, relay.reset, relay.recoverPreparedReset and --read-reset-preparation;
    • relay-grace-lifecycle.test.ts: idle exit with no request drain, the deferred-shutdown retry, no retry while a client is attached, and reset prepare/finish, join, refusal and retry.
  • Regression: every relay test plus the shared relay contract, relay-session and relay-deploy tests, on current main: 246 files, 2,342 passed.

  • Node 18: relay code uses no APIs newer than Node 18.

  • The changed-code quality gate passes.

  • Tested on macOS locally; CI covers Linux and Windows.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Wire: this adds optional status fields and new methods only (rule 1 of remote-wire-compatibility.md); there are no new stream opcodes. The relay transport is outside the cross-version harness, so the names are pinned by a contract test instead.
  • SSH: a prepared reset is recorded as "prepared", never "exited". The SSH execution-boundary vocabulary is unchanged.
  • Windows and peer-close: the reader argv is checked after the runtime self-test and the Windows breakaway launch. Peer-close invalidation is exercised in the reconnect replay test.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[Critical risk] Adds owner-initiated relay shutdown with durable preparation state.

The PR is not yet safe to merge because a failed reset preparation can leave a running relay unable to accept ordinary requests.

Findings

  1. P1 Failed reset leaves admission closed ▶

Summary

The PR adds capability-gated relay owner reset, a durable preparation journal, and a read-only recovery path. The changes since the previous review are from a rebase onto main; none alter the PR’s relay implementation.

Diagram
sequenceDiagram
  participant Owner
  participant Relay
  participant Journal
  Owner->>Relay: relay.reset
  Relay->>Relay: Drain admitted work and prepare shutdown
  Relay->>Journal: Persist preparation
  Relay-->>Owner: Prepared acknowledgment
  Owner->>Relay: Settle response
  Relay->>Relay: Finish shutdown
Loading

Reviews (2) · Last reviewed commit: "feat(relay): capability-gated owner rese..."

Comment on lines +189 to +194
this.shutdownPreparation = preparation.catch((error: unknown) => {
this.shutdownPreparation = null
this.shutdownInitiator = undefined
this.shutdownInFlight = false
throw error
})

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 Failed reset leaves admission closed

If PTY disposal or owned-process cleanup fails after the reset starts draining work, this catch allows another attempt but never reopens ordinary requests. The relay stays running, yet a connected client receives relay_work_admission_closed for operations such as fs.readFile and pty.attach. Restore admission when preparation fails, or complete the shutdown.

Knowledge Base Used: Relay protocol and transport

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

A prepared reset whose response never settles ok leaves the daemon alive but unusable, and makes SIGTERM/SIGINT a no-op. Details below.

Reviewed changes

  • Shutdown split — RelayGraceLifecycle now separates prepareShutdown (dispose PTYs and owned processes, keep the transport up, optionally drain admitted work) from finishShutdown (dispose runtime, process.exit(0)); idle and signal shutdown route through the same split.
  • Owner-reset state machine — new RelayOwnerReset admits only the active session owner matching runtime incarnation + owner generation/lease, prepares shutdown, persists evidence, and finishes only after the reset response settles ok; recoverPreparedReset replays a retained result on a reconnected transport.
  • Registration and status — registerRelayOwnerReset registers relay.reset / relay.recoverPreparedReset, advertises relay.ownerReset.v1 and relay.durableResetPreparation.v1, and publishes the journal binding to the authenticated owner only; relay.status merges these capabilities.
  • Durable journal + reader — RelayOwnerResetPreparationJournal writes immutable per-request evidence under <endpointDir>/owner-reset-preparations; relay.js --read-reset-preparation reads it from stdin/stdout without starting a daemon.
  • Drain admission — both reset methods are admitted during a work drain; wire names are pinned by a contract test.

I ran the eight new/changed specs locally: 87 passed. The idle/signal ordering, deferred-retry, and double-call guard appear preserved against the pre-refactor lifecycle.

⚠️ A prepared-but-unsettled reset can leave the daemon alive, unusable, and unkillable by SIGTERM

finishShutdown() is the only host-side exit, and a reset reaches it only when its response settles ok. If the response instead settles ok: false (peer close, rpc.cancel, or a write the client never confirms), the settlement callback returns without finishing, while prepareShutdown has already cancelled the grace timer, disposed PTYs and owned processes, closed work admission, and set shutdownInFlight — which is only cleared on preparation failure, never after a successful preparation. Every subsequent shutdown entry point (grace expiry, pool watchers, and the SIGTERM/SIGINT handlers) early-returns on that flag, and the transport is deliberately kept up, so the process neither exits nor serves work until a reconnecting owner issues recoverPreparedReset. Pre-refactor shutdown() exited unconditionally; this wedge is new.

Technical details
# Prepared reset with no successful settlement never exits

## Affected sites
- `src/relay/relay-grace-lifecycle.ts:159-194` — `shutdownInFlight = true` is set on entry; the `.catch(...)` at `:189` is the only place it is reset, and it runs only when preparation *rejects*.
- `src/relay/relay-grace-lifecycle.ts:115-118` — `shutdown()` early-returns while `shutdownInFlight` is true; this is also the `SIGTERM`/`SIGINT` handler (`:105-106`).
- `src/relay/relay-grace-lifecycle.ts:92, :96-101, :213` — pool watchers and config-driven grace are gated on `shutdownInFlight`.
- `src/relay/relay-owner-reset.ts:165-178` — the reset's settlement callback returns early on `!settlement.ok` and only then calls `finish()`.
- `src/relay/relay-work-admission.ts:55-67` — `draining` is set and never cleared (no `endDrain`).

## Required outcome
- A prepared reset must not be able to wedge the relay indefinitely. Either give the host its own completion budget/watchdog after a successful preparation, or ensure a negative/lost settlement still converges to exit, while keeping the "prepared ≠ exited" evidence semantics.

## Reachable sequence
1. Authenticated session owner calls `relay.reset` (registered unconditionally).
2. `prepareShutdown` cancels grace, disposes PTYs + owned processes, opens work admission, sets `shutdownPrepared` and `shutdownInFlight`.
3. Response settles `ok: false` (transport closes, cancel/staleness, or lost write).
4. `finish()` is never called; every later idle/grace/SIGTERM path hits the `shutdownInFlight` guard.

## Open questions for the human
- Is a host-owned completion timeout intended for a later slice, or should a lost confirmation fall back to the pre-refactor unconditional exit? The SSH execution-boundary rule ("loss of contact is never evidence of process death") argues against inferring exit from silence, but does not obviously require an unusable, signal-immune daemon.
- Today no shipped client calls `relay.reset`, so this is latent; the method is still registered and reachable by any authenticated session owner.

ℹ️ Nitpicks

  • src/relay/relay-owner-reset.ts:48-49, :66-67, :121-122, :135-136 — context.clientId !== clientId and context.transportGeneration !== generation compare a context's field to a local captured from that same context object, so they are always false. isStale() already pins the transport generation; consider dropping the tautological checks or comparing against the retained record where that was the intent.
  • src/relay/relay-daemon.ts:106 calls registerRelayOwnerReset without runtimeIncarnation, so the advertised incarnation is a fresh randomUUID() per daemon. That is a valid runtime incarnation, but the registration.test.ts case named "uses the daemon incarnation shared with network tunnel ownership" tests an option production does not exercise yet.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

…journal (#16741 T3 R1)

The relay gains an owner-reset surface that no current client calls. A
session-owner client will be able to ask its relay to prepare a shutdown
(`relay.reset`), have that preparation journaled durably beside the relay
endpoint, and later recover it (`relay.recoverPreparedReset`, or the read-only
`--read-reset-preparation` exec mode if the daemon is gone). Relay status
advertises `relay.ownerReset.v1` and, when a journal is configured,
`relay.durableResetPreparation.v1`.

Why ahead of its caller: relays and clients update independently, so the
host side has to be deployed before any client can rely on it. Old relays
answer method-not-found and advertise neither capability, which a client
reads as "unavailable", never as "reset".

- relay-grace-lifecycle: shutdown is split into prepareShutdown and
  finishShutdown so a reset can settle its response before the process exits.
  Idle and signal shutdown keep today's behavior, including the deferred
  retry when disposal fails, and still do not wait on admitted requests; only
  a reset initiator drains work around owned-process disposal.
- relay-work-drain-contract: both reset requests are admitted during a drain.
- relay.ts / relay-daemon.ts: register the reset, its journal under
  `<endpointDir>/owner-reset-preparations`, the status capabilities, and the
  reader argv (checked after the self-test and Windows breakaway launch).

Porting note (source: #16741 a68b6f3, merge-base 277c289):
- Based on #24414, which already adds the adapter's activeSessionOwner and
  assertOwnerPublicationSettled with code identical to #16741's.
- Dropped: network-tunnel fencing (T4), the PTY ownership-transfer fence and
  its refusal test case (T7), the Bun arm of the reader integration test,
  the Bun runtimeVersion status field, and #16741's lazy entry imports.
- Adapted: wire parsers use a record guard instead of casts; the idle path
  no longer gains an unbounded work drain.
- Added: relay-grace-lifecycle tests (idle exit, deferred retry, attached
  client, reset preparation, joining and retry) and a wire-contract test
  pinning the capability, method and flag names.
@OrcaWin
OrcaWin force-pushed the OrcaWin/node-rt-p3-t3-r1 branch from 49c963e to 33680d6 Compare October 1, 2026 17:42
@OrcaWin
OrcaWin requested a review from brennanb2025 as a code owner October 1, 2026 17:42
@OrcaWin
OrcaWin changed the base branch from OrcaWin/node-rt-p3-t2-p5 to main October 1, 2026 17:42
@OrcaWin OrcaWin closed this Oct 1, 2026
@OrcaWin OrcaWin reopened this Oct 1, 2026
@OrcaWin
OrcaWin merged commit 34a582b into main Oct 1, 2026
73 of 105 checks passed
OrcaWin added a commit that referenced this pull request Oct 2, 2026
* Revert "feat(orcad): source-side dormant export of a relay-hosted SSH target (#16741 T6-8) (#24519)"

This reverts commit 783101b.

* Revert "feat(ssh): update, roll back, recover and stop a managed orcad server (#16741 T6-5 follow-up) (#24463)"

This reverts commit 38c2d1d.

* Revert "feat(ssh): deploy and pair an empty managed orcad server over SSH (#16741 T6-5) (#24453)"

This reverts commit 8b76683.

* Revert "fix(ssh): orcad GC honors the activation journal; readiness requires proven daemon coverage (#16741 T6 follow-up) (#24451)"

This reverts commit d3f8c50.

* Revert "feat(ssh): remote orcad stop by request file and journaled decommission (#16741 T6-4) (#24449)"

This reverts commit 43d9b43.

* Revert "feat(orcad): supervisable server: stop requests, managed stop receipts and a lifetime that keeps its lock on failed teardown (#16741 T6-3) (#24433)"

This reverts commit b093d3a.

* Revert "feat(ssh): crash-safe orcad activation, rollback and recovery (#16741 T6-2) (#24423)"

This reverts commit 1a9ac0e.

* Revert "feat(runtime): SSH access links for paired servers in a downgrade-safe sidecar (#16741 T5-1+T5-2) (#24420)"

This reverts commit 99db2bf.

* Revert "feat(relay): capability-gated owner reset with a durable preparation journal (#16741 T3 R1) (#24418)"

This reverts commit 34a582b.

* Revert "feat(ssh): track connection-manager drains, test probes and provider continuations (#16741 T2 P3+P8a) (#24407)"

This reverts commit d53063d.

* Revert "feat(daemon): idle retirement, session census and recovery-only provider (#16741 T2 P4b) (#24409)"

This reverts commit ff212db.

* Revert "feat(ssh): add pty.resumeClient and split SSH PTY process listing (#16741 T2 P5+P6) (#24414)"

This reverts commit 92cb717.

* Revert "feat(relay): await owned watcher and agent children on shutdown (#16741 T2 P1) (#24400)"

This reverts commit 6b36e4f.

* Revert "feat(session): retry failed renderer session writes and verify local folder PTYs (#16741 T2 P9) (#24406)"

This reverts commit d23ecef.

* Revert "feat(ssh): remote orcad primitives on the pinned Node runtime (#16741 T6-1) (#24419)"

This reverts commit dd87ae5.

* Revert "fix(runtime): fence runtime-environment subscriptions and status probes by identity (#16741 T5-3) (#24421)"

This reverts commit ece9e4d.

* Revert "feat(orcad): migration manifest and dormant-state contracts (#16741 T6-7) (#24422)"

This reverts commit 3fbdaba.

* Revert "feat(ssh): wire SshConnection through the work and transport close ledgers (#16741 T2 P2) (#24401)"

This reverts commit 4e8edc8.

* Revert "feat(profiles): carry markdown frontmatter visibility in project transfers (#16741 T2 P7) (#24405)"

This reverts commit 60c9326.

* Revert "fix(runtime): project the PTY incarnation onto mobile session tabs (#24413)"

This reverts commit 99e0303.

* Revert "feat(daemon): tag daemon stream data with the PTY incarnation id (#16741 T2 P4a) (#24402)"

This reverts commit 817af76.

* Revert "feat(ssh): port the SSH connection work ledger and transport close ledger (#16741 T2) (#24210)"

This reverts commit c991893.

* Revert "feat(relay): fence and drain file and git response streams on shutdown (#24185)"

This reverts commit dc08ffe.

* Revert "refactor(runtime-rpc): extract the Node WebSocket lifecycle; opt-in pinned port (#24186)"

This reverts commit a789233.

* Revert "feat(relay): route relay handlers through work admission; producer publication drain (#24181)"

This reverts commit 0b812bd.

* Revert "feat(relay): land the #16741 T1 seam (work drain, publication drain, release gate) (#24156)"

This reverts commit 3aa2d3a.

---------

Co-authored-by: m4air <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant