Skip to content

fix(daemon): recover provider rental fences after restart - #5052

Merged
thymikee merged 14 commits into
0.22from
t3/persist-provider-recovery-fences
Nov 24, 2026
Merged

thymikee merged 14 commits into
0.22from
t3/persist-provider-recovery-fences

Conversation

@thymikee

@thymikee thymikee commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #4972. Record rental scope before create and exact identity before allocation succeeds. Restore reservations before admitting overlapping work. Require matching recovery proof before either recovery hook runs.

Before / after

  • Limrun reconciles lost create responses by rental key. Empty or ambiguous results keep the reservation. The recovery principal binds the API URL, effective authorization, and headers configured on the SDK client. SDK telemetry changes leave it stable. If the SDK configuration or request cannot supply proof, Limrun stays registered and recovery stays fenced.
  • Revyl uses a fresh key per create. A 404 for a key-only stop leaves release unconfirmed.
  • Shutdown retries failed journal retirement after the bounded provider wait without sending another stop.

Validation

  • At 65166c0695, 996 focused tests passed, including the eager-import guard and Limrun recovery. Format, lint, and typecheck passed. All 12 runnable affected checks passed. Local receipt run-Sj7pZm. Hosted Coverage was rerun after a fake-daemon timeout.
  • At 42ed83d00a, formatting, lint, typecheck, layering, and 55 focused tests passed. Two regression cases failed at b235a0239f. Coverage caught the eager import fixed above.
  • At 65166c0695, live Limrun exact-ID and rental-key recovery passed after SIGKILL. The keyed lookup returned one match. Both exact-instance DELETE requests returned HTTP 200, and both journals ended empty. The PR evidence comment includes the journal snapshots.
  • Before downgrading to a daemon that predates the rental journal, settle all journaled rentals.

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 5.06 MB 5.06 MB +6.6 kB
Package (unpacked) 5.06 MB 5.06 MB +6.6 kB
Package (download) 1.54 MB 1.54 MB +2.2 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 49.3 ms 35.3 ms -14.0 ms
CLI --help 92.5 ms 64.6 ms -27.9 ms

@thymikee
thymikee marked this pull request as ready for review November 23, 2026 20:00
@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Apex Sentinel: 1 new finding on ac19dde. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

Review of ac19dde found one regression in lease_allocate, one missing live check, and four restart-recovery gaps. The 14 passing checks include unit and integration. Two cancelled Body rules runs (superseded after body edits) and one check still in progress look unrelated to the diff. No conflicts. Before merge, fix the first finding below and attach the live Limrun run from the second.

lease-registry.ts:141 runs assertLeaseIdAvailable(chosenLeaseId) before the issuedLeaseIds check, and it matches every journal entry, including the live rental of a lease this daemon issued. When a caller sends lease_allocate with the id of a live provider lease and a different device, tenant or run, it now gets DEVICE_IN_USE with "Lease release is unknown". The base returned INVALID_ARGS with idInUse. The caller waits and retries a request that can never succeed, and the daemon reports a release outcome that does not exist. The rule: assertLeaseIdAvailable refuses only ids whose rental this daemon inherited. Move it below the issuedLeaseIds check, or check only inherited entries. Please add a lease_allocate case with a live provider lease id and a mismatched scope that expects INVALID_ARGS idInUse.

The real Limrun create request now carries a new rentalKey label (runtime.ts:577), and restart recovery depends on the list API answering provider=limrun,rentalKey=<uuid> with exactly that instance. Every test mocks @limrun/api, so hosted CI cannot catch a label that is rejected, dropped or not selectable. In that case, every Limrun allocation fails or every key-only recovery stays fenced forever. Before merge, please run this on real credentials. Allocate a Limrun lease and show provider-rentals.json holding reconciliationKey before the create and instanceId after it. SIGKILL the daemon once instanceId is recorded, restart, and show the DELETE of that exact instance and an empty rentals array. Then remove instanceId from the journal entry and restart. The run must list by provider=limrun,rentalKey=<key>, find the one instance, record it and delete it. Attach the journal snapshots and the provider_rental diagnostics.

A second independent pass found that Revyl can clear a rental using a 404 from a different backend. Start an embedded daemon with revyl({ apiKey, apiUrl: originA }) and crash after Revyl returns the session id. Restart the same state directory with originB. The plugin leaves both option values out of the environment fingerprint (index.ts:23-42), so recovery uses originB, and a 404 there counts as proof (runtime.ts:122-132). The original rental may still run on originA while the same scope is admitted. The rule: rental recovery may confirm absence only against the account and origin that created the rental. Please persist the resolved runtime identity in provider-rental-journal.ts:96 and keep the reservation when it differs. Revyl already computes it in runtime-instance.ts:9-20.

A second independent pass found a second Revyl gap at runtime.ts:304. start_device reaches Revyl, the response is lost, and creation is still running. The failed start returns the preassigned session id as a potential rental (revyl-session.ts:140-150). Live cleanup treats a stop 404 for that key as confirmed, so the journal entry is deleted (lease-release.ts:22-29, lease-registry.ts:892-904). If the daemon restarts and Revyl finishes creating the device, the next overlapping allocation reaches Revyl, and the key-only recovery guard cannot help. The rule: a 404 confirms absence only when the provider identified the target. Please carry whether each stop target was provider-identified or only the submitted key, apply that to live cleanup and recovery, and keep the durable entry on a key-only 404.

A second independent pass found that a failed exact-id write does not stop allocation (provider-rental-journal.ts:145). The scope and key writes succeed and the provider returns an exact id. Then the journal rewrite fails with ENOSPC, and rented() logs and returns. Setup and cleanup go on with an id that exists only in memory, and Revyl can echo a different session id (revyl-session.ts:193-204). A crash before cleanup succeeds leaves only the requested key, so restart cannot target the session the daemon already received. The rule: an allocation is not settled while an exact id is unrecorded. Please retain the id in the live provider owner and retry the durable write, or settle by confirming the exact instance ended. Propagate the journal failure to the allocation path and keep the scope fenced until one proof exists.

A second independent pass found that existing recovery is lost for providers that implement only recoverExpiredLease (provider-lease-expiry.ts:338). On the base, a successful allocation is written to the live journal and restart calls that hook. At head, the new reservation suppresses the legacy record. Restart then skips recovery because the identity is empty (line 272) or gets false from the composed missing hook (provider-device-runtime.ts:185-188). The rental stays billed and the scope stays blocked. The rule: a provider that advertises only recoverExpiredLease keeps its proven recovery route. Please keep the legacy recovery identity for those providers, reserve the scope before create as now, and use recoverRental for providers that implement it.

A second independent pass found that a transient journal write error can turn a confirmed release into a permanent fence (provider-rental-journal.ts:155). A WebDriver provider without restart recovery confirms session deletion, but removing the rental record fails. confirmReleased logs the error and the registry clears the in-memory ending reservation (lease-registry.ts:892-904). After the filesystem recovers and the daemon restarts, the stale rental returns as unknown and blocks the same scope indefinitely. The base retried its journal rewrite once the filesystem was writable. The rule: a confirmed release must reach the journal eventually. Please keep a pending update for confirmed release, retry it while this daemon owns registration, and flush it at shutdown.

Not blocking, and they can be taken or left: key-only entries are fenced forever when the crash lands between reserve and beforeCreate (a missing key proves no create was sent, and no operator route clears a reconciled fence besides editing provider-rentals.json), so a follow-up could let a runtime declare it reconciles before create and add an operator clear route; plugins.md should say that restart recovery uses only recoverRental and recoverExpiredLease covers legacy entries only, and that a throwing beforeCreate means the create must not be submitted (plugins.md:139); the two runtime throws in the journal (reserve, record) and restore() should be typed AppErrors, with a deliberate choice between failing startup and fencing the provider on an unreadable journal (provider-rental-journal.ts:88); and the seven unrelated comment deletions in daemon-runtime.ts:374 can be reverted or moved to their own commit..

Could the journal be smaller? One option is to make provider-rentals.json the only durable lease record. Reserve in LeaseRegistry.issueLease for every lease whose provider needs a runtime. On startup, read live-provider-leases.json and expired-provider-leases.json once, adopt their entries as rentals with no identity (recovered by recoverExpiredLease), and delete the files. That removes writeJournal, persistPendingLeases, the retry timer, the seven hasRentalRecord filters in provider-lease-expiry.ts and the inherited/legacy branching in canRecover. A provider could also declare "reconciles before create", so an empty identity confirms release instead of fencing. It would first need one release that only reads the legacy journals, and an ADR 0040 amendment naming the rental journal as the single record. What would make that unworkable?

Not verified here: the real Limrun API's handling of the rentalKey label and selector, any shipped third-party plugin that implements recoverExpiredLease without recoverRental, and the Revyl lease table's handling of control.rented on the session-mismatch and no-run-id failure paths. No tests were run for this review, and the 956-test local receipt in the PR body is not attached.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

@apex-sentinel-staging review

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Apex Sentinel: 1 new finding on 5d8393b. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

All six code problems from the earlier review are fixed at 5d8393b. Three problems remain, and one needs a live run.

Every Limrun create now carries a rentalKey label (runtime.ts:593). Restart recovery, and live cleanup of a lost create (lease-release.ts:128), both rely on the list API answering provider=limrun,rentalKey=<uuid> with exactly that instance. Every test mocks @limrun/api, and the PR body says live label lookup and exact deletion are unverified. If Limrun rejects or cannot select by the label, every Limrun allocation fails, or every lost create stays fenced as release unknown. Hosted CI cannot catch this. Please attach the live run on real credentials: (1) allocate a Limrun lease and show provider-rentals.json with reconciliationKey before the create and instanceId after it; (2) SIGKILL the daemon once instanceId is recorded, restart, and show the DELETE of that exact instance and an empty rentals array; (3) allocate again, SIGKILL, remove instanceId from the entry, restart, and show the list call with provider=limrun,rentalKey=<key> finding one instance, the id being recorded, the DELETE, and an empty array. Please attach the journal snapshots and the provider_rental diagnostics. This run is required before merge.

A second independent pass found a stuck fence in lease-registry.ts:903. Close a session on a journaled provider lease and pause the provider stop after close moves the lease to Ending. Send a concurrent authenticated lease_release. It can start endSessionsForLease, which waits on the execution lock held by close (lease.ts:213-227, lease-session-end.ts:156-174). Now let stop confirm and make the first retirement write fail. The confirmRequestProviderRelease path creates a fresh allowRelease promise through the expiry callback (daemon-runtime.ts:335-352). The session ender sees the existing cleanup, waits for it, and drops the new callback (lease-session-end.ts:321-329). The provider releaser waits on that unresolved promise (provider-lease-expiry.ts:392-403). Retry and shutdown join the same attempt, so the lease stays retiring even after storage is writable again. A provider without restart reconciliation then keeps a permanent fence for a rental it already ended. The rule: once the provider confirms the end, the journal retirement is queued directly in the provider releaser, without waiting on session cleanup. The write is retried while the daemon owns registration and is attempted during shutdown. The contention reservation stays until the separate session and claim cleanup is confirmed.

A second independent pass found that recovery proof can come from a different account in daemon-composition.ts:203. Register a third-party recovering provider with the stable module owner instance android, and pass its API account and URL as plugin options. The public contract allows both (plugins.md:108-134, validate.ts:644-658). Create a rental on endpoint A, then restart the same state directory with endpoint B. An options-only provider can have no environment credential digest (credential-fingerprint.ts:16-49), and the owner instance still matches, so provider-rental-journal.ts:124-129 allows recovery. The plugin can correctly find the exact id absent on B, return true, and make provider-lease-expiry.ts:453-461 drop the fence while A still bills. The new comparison fixes built-in Revyl, whose owner includes its resolved account and origin. It accepts any matching module-owner name for registered plugins. The rule: recovery of a new rental needs an explicit, non-secret principal derived from the provider's effective account and origin. That principal is persisted and compared for either recovery hook. The reservation stays unknown when the provider cannot give a matching principal.

Not blocking, and these can be taken or left: no test covers the production providerRentalPolicy at daemon-composition.ts:197, because the restart tests inject their own policy, so returning runtimeIdentity: undefined or inverting legacyRecovery passes the suite; no test makes the exact-id journal write fail and asserts that lease_allocate errors and leaves the scope fenced, so deleting persistProviderRentalInstance(lease) at lease.ts:171 passes the suite; and runtimeIdentity at provider-rental-journal.ts:127 is the full owner instance, which for Limrun also hashes iosModel, so changing it and restarting fences inherited rentals the same account could still delete.

The two earlier inline threads no longer apply and can be resolved. The legacy-only recovery thread is fixed: the rental now carries legacyLeaseId and canRecover takes the recoverExpiredLease branch (#5052 (comment)). The invalid-journal thread is unchanged on purpose: failing startup closed keeps reservations that may still bill, and the journal is new, atomically written, and named in the error (#5052 (comment)).

The only failing check is Body rules, which lints the PR description and not code. No file in the diff is on that route. The second run was cancelled by a later run, so the check still fails until the body passes. One possible cause is that the ## Before / after section must show up to 3 calls with output that differs at base and head. Not verified here: the exact failing rule, because the failure log was not read. There are no conflicts.

Not verified here: the real Limrun API's handling of the label and selector for create, list and delete; whether Revyl start_device accepts a random v4 session_id per create; the PR body's local receipt run, which is not attached; and whether any shipped third-party plugin implements recoverExpiredLease without recoverRental. No tests were run, and the hosted unit and integration checks are green. Before merge, the live Limrun SIGKILL and restart run must be attached, the two code problems above fixed, and the PR body must pass Body rules.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Both code blockers from the earlier review (5d8393b) are fixed at 9a4aef3, but the live Limrun check is still missing, and a second pass found three new problems.

The earlier request is unchanged: restart recovery and cleanup of a lost create depend on the real Limrun list API selecting provider=limrun,rentalKey=<uuid> and on exact-instance DELETE (runtime.ts:231). Every test mocks @limrun/api for those calls, and the PR body still says live recovery is unverified. This head also reads the SDK's built Authorization header at plugin setup (runtime.ts:228-238), and no live run has exercised that. If Limrun cannot select by the label, every lost create and restarted rental stays fenced as release unknown. Hosted CI cannot catch this. Required before merge: attach a live run on real Limrun credentials. (1) Allocate a lease and show provider-rentals.json with reconciliationKey and a principal-<hex> rentalRecoveryPrincipal before the create, and instanceId after it. (2) SIGKILL the daemon once instanceId is recorded, restart with the same credentials, and show the DELETE of that exact instance and an empty rentals array. (3) Allocate again, SIGKILL, remove instanceId from the entry, and restart. Show the list call with provider=limrun,rentalKey=<key> finding one instance, the id being recorded, the DELETE, and an empty array. Attach the journal snapshots and the provider_rental diagnostics.

A second independent pass found that provider-lease-expiry.ts:582 can lose a retirement on shutdown. Let a journaled lease expire and hold its provider stop in flight until shutdown enters drain(). The drain visits the retirement queue at line 498 before awaiting the stop. If the provider confirms during the wait and the first retirement write fails transiently, the attempt queues the retirement and resolves. The drain then reports the entry pending, and shutdown cancels its retry timer at lines 604-612, though storage may be writable again. The old entry survives, and the next daemon fences it indefinitely if the runtime has no recovery hook. An inherited recovery call that confirms during the drain behaves the same way. An in-memory check of the exact-head releaser showed one stop and only one retirement write despite a first-write-only failure. The rule: retirements queued while shutdown drains provider calls must be flushed. Flush confirmed retirements again after the bounded wait, before collecting the drain result and closing the releaser. Keep that flush journal-only so it cannot send another provider stop.

A second independent pass found that plugin.ts:74 can make instance attachment fail. Start with valid iOS or Android instance access plus LIMRUN_API_KEY, and set LIMRUN_BASE_URL to a value without a scheme, such as api.limrun.com. On the base, the SDK stores the URL without parsing it, and attach uses only the instance URL and token. At this head, the unconditional account probe at runtime.ts:228-233 runs during setup, and SDK 0.69.1 calls new URL on the malformed URL. Setup rejects, Limrun is never registered, and an attached-instance lease that worked before is refused. The rule: a failed account request build must count as unavailable recovery proof, not a setup failure. Keep the runtime registered for instance access and leave the principal absent, so inherited rentals stay fenced.

A second independent pass found that runtime.ts:234 can retire a live rental fence. Run Limrun through a gateway set by LIMRUN_BASE_URL that takes one bearer and routes to separate provider accounts by a custom tenant header. Allocate on tenant A and persist the instance ID. Then restart with LIMRUN_CUSTOM_HEADERS selecting tenant B, keeping the gateway URL and bearer. The pinned SDK sends the changed header on DELETE, but the principal hashes only Authorization and the base URL. Recovery targets B, where the exact ID returns 404, and client-options.ts:67-73 treats that 404 as confirmed. The daemon then retires A's live rental fence. The earlier options-only plugin case is fixed by the new principal contract, but this route uses the new built-in Limrun derivation. The rule: the recovery principal must change whenever the account the DELETE reaches can change. Include the effective custom account-routing headers in the opaque digest. If an override cannot be bound to the principal, keep recovery unverified.

The two resolved-benign inline threads (#5052 (comment) on identity-free journal restore, #5052 (comment) on fail-closed startup) do not apply, so the author can resolve them: the first is an intentional release-unknown fence, and the second is deliberate to avoid overlapping allocations of rentals that may still bill.

The remaining check is 'Body rules', which was cancelled as superseded. It lints the PR description, not code, and no file in the diff is on that route, so it looks unrelated. It still blocks merge until a run on the current body passes. No conflicts. Hosted unit and integration checks are green at 9a4aef3. Not verified here: tests were not run locally, the new daemon and composition tests were read but not executed, and real Limrun behavior for the label, list selection and exact DELETE needs credentials. The next step before merge is the live Limrun run above, plus fixes for the three new findings.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

@apex-sentinel-staging review

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Review of 798a059: one regression in the restart principal needs a fix, and the live Limrun run is still missing. The earlier request at 9a4aef3 for a live run is not met yet. The only check not passing is "Body rules", which was cancelled as superseded after a body edit; no file in the diff is on that route, but a run on the current body must pass before merge. Not verified here: tests were not run locally, and the SDK header behavior was read from the @limrun/api 0.69.1 package source, not observed in a running process.

The principal now hashes every header the SDK builds, not just the account and origin (runtime.ts:236). Those headers include User-Agent (agent-device version and SDK version), X-Stainless-Package-Version, X-Stainless-Runtime-Version (process.version), X-Stainless-OS/Arch and X-Stainless-Timeout. They change with the agent-device, SDK or Node version, not with the account. A journaled rental survives a crash or a version-mismatch takeover whose provider stop does not confirm in the 2 s drain. The next daemon then runs on a new version, and provider-rental-journal.ts:117-118 sees a different principal. canRecover returns false, the rental is marked release-unknown, and it is never retried. The Limrun instance keeps billing, and overlapping lease_allocate stays refused until the exact old versions run again or someone edits provider-rentals.json. This is a regression from the base and from 9a4aef3. The rule: the principal changes only when the account or origin that the DELETE reaches can change. Derive it from baseURL, the built Authorization header and the effective custom headers (the parsed LIMRUN_CUSTOM_HEADERS), and nothing generated by the SDK. The principal test should also change clientVersion and a stubbed User-Agent or SDK version header, and expect the same principal. The current test always uses clientVersion "test-version" on one Node version, so it cannot catch this.

A second independent pass found the same problem from the Node side (runtime.ts:237). With identical API key, API URL and custom headers, the lockfile SDK and this digest gave different principals under Node v26.11.1 and v26.13.1. The journal then rejects the match, and provider-lease-expiry.ts:267-275 skips the exact-ID recovery. The same fix covers it: exclude generated SDK headers unless the operator configured them explicitly, so routing overrides stay bound.

Restart recovery and lost-create cleanup depend on the real Limrun API: listing by the rentalKey label, exact-instance DELETE, and the SDK-built principal at plugin setup (runtime.ts:231). Every test mocks @limrun/api, and hosted CI cannot detect a rejected label or an unstable principal. Before merge, after the fix above, attach a run on real Limrun credentials. (1) Allocate a lease, and show provider-rentals.json with reconciliationKey and a principal- rentalRecoveryPrincipal before the create, and with instanceId after it. (2) SIGKILL the daemon once instanceId is recorded, restart with the same credentials, and show the DELETE of that exact instance and an empty rentals array. (3) Allocate again, SIGKILL, remove instanceId from the entry, and restart. Show the list call with provider=limrun,rentalKey= finding one instance, the id being recorded, the DELETE, and an empty array. Attach the journal snapshots and the provider_rental diagnostics.

The two open inline threads (identity-free journal entry fence, fail-closed startup on an invalid journal) no longer apply: both behaviors are deliberate and unchanged by this delta, so they can be resolved. #5052 (comment) #5052 (comment)

Next, make the principal ignore SDK version, Node and User-Agent headers, then attach the live SIGKILL and restart run.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

@apex-sentinel-staging review

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The principal problem from 798a059 (#5052 (comment)) is fixed at b235a02, but the new principal derivation has header-source gaps, and the live Limrun run is still missing. Hosted unit and integration checks are green. The only check not passing is "Body rules", which lints the PR description. No file in this diff is on its route, so it looks unrelated, but the body must pass it before merge. There are no conflicts.

Restart recovery and lost-create cleanup depend on real Limrun behavior that every test mocks: listing by the provider=limrun,rentalKey=<uuid> labels, exact-instance DELETE, and a principal that stays stable across a real daemon restart (runtime.ts:231). If Limrun ignores the selector or the principal changes on restart, every lost create and inherited rental stays fenced as release-unknown, and overlapping lease_allocate stays refused. Hosted CI cannot detect this. Please attach the live run requested earlier, on real credentials. (1) Allocate a lease and show provider-rentals.json with reconciliationKey and a principal-<hex> rentalRecoveryPrincipal before the create, and with instanceId after it. (2) SIGKILL the daemon once instanceId is recorded, restart with the same credentials (ideally on a different build or clientVersion, which also proves the principal fix), and show the DELETE of that exact instance and an empty rentals array. (3) Allocate again, SIGKILL, remove instanceId from the entry, and restart. Show the list call with provider=limrun,rentalKey=<key> finding one instance, the id being recorded, the DELETE, and an empty array. Please attach the journal snapshots and the provider_rental diagnostics. This run is required before merge.

A second independent pass found that the principal takes header names from host.env, while the SDK reads LIMRUN_CUSTOM_HEADERS from ambient process.env at construction (plugin.ts:74). Start the plugin with startAgentDevice and a host.env that has LIMRUN_API_KEY but no LIMRUN_CUSTOM_HEADERS. Allocate with ambient X-Account: account-a, SIGKILL after the exact ID is durable, and restart with ambient X-Account: account-b. Both principals omit X-Account, so the recovery gate accepts the match and sends DELETE to account-b. There a 404 counts as absence and can retire the reservation while account-a's rental stays live. The previous head hashed the built headers and told these requests apart. The rule: the header names must come from the same environment the SDK reads at client construction, with built header values kept. If the plugin host owns the configuration, it needs one source shared by SDK requests and the digest.

A second independent pass found that host-only header names also reach the digest (runtime-instance.ts:56). With the same embedded host and no ambient LIMRUN_CUSTOM_HEADERS, add only X-Route: region-a to host.env on restart. The SDK sends identical routing, but the principal changes from an omitted customHeaders field to a serialized x-route entry, so the journal rejects recovery and leaves the same-account rental fenced. A host-only User-Agent entry kept across an upgrade also pulls the generated User-Agent into the digest, though the SDK never applied that override. The rule: names must come only from overrides actually configured on the SDK at construction.

A second independent pass found that a host-only malformed header can stop Limrun from registering (runtime.ts:241). Start an embedded daemon with a valid host API key and host.env.LIMRUN_CUSTOM_HEADERS set to Invalid Header Name: fixture, with no ambient SDK setting. The SDK builds a valid request, then Headers.get rejects the host-only name in runtime-instance.ts:56. That runs outside the buildRequest catch at runtime.ts:234-236, so setup throws before registration. The malformed-header test mirrors the host and ambient environments, so the SDK fails at an earlier seam and the test misses this. The rule: derive the name list from the SDK's actual construction configuration, and keep the whole proof derivation inside the failure boundary so an unusable proof leaves the runtime registered.

The two open inline threads on provider-lease-expiry.ts (#5052 (comment)) and on fail-closed startup (#5052 (comment)) were resolved without a change and need no further work. Both are intentional: the identity-free journal entry is a release-unknown fence, and an invalid journal stops startup to avoid overlapping allocations while rentals may still bill.

Not blocking, and these can be taken or left: the first header-source gap above could also be closed by passing the parsed host.env custom headers to the Limrun constructor as defaultHeaders, so the SDK and the digest read one value, or by taking the names from process.env. It is also unverified whether the daemon's HostEnvironment.env equals process.env in every composing root.

Not verified here: tests were not run, and the SDK header-merge order and env parsing were read from a locally installed @limrun/api 0.49.3 rather than the pinned 0.69.1. Real Limrun label selection, exact DELETE and principal stability across a restart were not observed.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 65166c0

Since the review of b235a02: 0 new · 0 still open · 0 no longer raised

No open findings.

Reviewed with this repository's own Sentinel configuration (ecb2089867e9).

💬 Talking to Sentinel

In a finding's thread, reply with:

Command What it does
@apex-sentinel-staging note <context> Adds context; Sentinel re-checks the cited code
@apex-sentinel-staging pivot <why> Says the finding is wrong; Sentinel re-checks the cited code
@apex-sentinel-staging like Marks the finding as useful
@apex-sentinel-staging dislike <why> Marks it as not useful, so it is not raised again

On this conversation, comment @apex-sentinel-staging review to run a full review once again.

@thymikee

Copy link
Copy Markdown
Member Author

The three code problems from the earlier review (#5052 (comment)) are fixed at 65166c0. One problem remains: the restart recovery has no live proof yet.

Restart recovery and lost-create cleanup depend on real Limrun behavior that every test mocks (https://github.com/callstack/agent-device/blob/65166c0/packages/provider-limrun/src/runtime.ts#L230). The rule: a restarted daemon must find and delete every rental it created, using only the journal. That needs three things from Limrun: the provider=limrun,rentalKey=<uuid> label selector on list, the exact-instance DELETE, and a principal that stays stable across a real restart. The principal derivation now also reads the SDK's private _options field. If Limrun ignores the selector or the principal changes, every lost create and inherited rental stays fenced as release-unknown. Then overlapping lease_allocate stays refused and billable rentals stay live. Hosted CI cannot catch this, and the earlier review asked for this run before merge. Please attach a live run on real credentials that reaches these states. (1) Allocate a lease and show provider-rentals.json with reconciliationKey and a principal-<hex> rentalRecoveryPrincipal before the create, and with instanceId after it. (2) SIGKILL the daemon once instanceId is durable. Restart with the same credentials, ideally on a different build or clientVersion. Show the DELETE of that exact instance and an empty rentals array. (3) Allocate again and SIGKILL. Remove instanceId from the entry and restart. Show the list call with provider=limrun,rentalKey=<key> finding one instance, the recorded id, the DELETE, and an empty array. Include the provider_rental diagnostics for each case.

The two open inline threads (#5052 (comment) and #5052 (comment)) do not need more work. Both were resolved before the earlier review and describe intended behavior: the identity-free journal entry is a release-unknown fence, and startup fails closed on an invalid journal so allocations cannot overlap while rentals may still bill. This update does not touch either one, so they can stay resolved.

Not verified here: the tests were not run locally, and real Limrun label selection, exact DELETE, and principal stability across a real restart. The SDK constructor and header merge were read from the local @limrun/api 0.68.1 source, not the pinned 0.69.1. CI runs the principal tests against the pinned SDK and they pass. They would fail if _options.defaultHeaders were absent, because the routed-header principals would then be equal.

The only check not passing is Body rules, which was cancelled. It lints the PR description and runs no code, and no file in the diff is on its route, so it looks unrelated. A run on the current body must still pass before merge. The next step is the live run above. After that, Body rules must pass on the current body.

@thymikee

Copy link
Copy Markdown
Member Author

Live Limrun restart recovery passed at 65166c069534c63b5c3a7cfe6b79e88607db8c72 against the real provider. The probe ran the checkout’s daemon and Limrun plugin in isolated subprocesses. It observed SDK HTTP requests and responses while sending them to Limrun unchanged.

The table shows the provider-rentals.json snapshots with resource IDs, keys and principal hashes abbreviated. Each journal was version 1. The same principal was recorded before create and used on restart.

Snapshot or provider operation Exact ID Rental key
Before create principal-…, reconciliationKey: key-A principal-…, reconciliationKey: key-B
After create (HTTP 200) key-A, instanceId: instance-A key-B, instanceId: instance-B
Before restart After SIGKILL, journal retained instance-A After SIGKILL, removed only instanceId from this probe’s journal
Recovery lookup No list request HTTP 200 for provider=limrun,rentalKey=key-B, exactly one match, instance-B
Journal immediately before DELETE instanceId: instance-A instanceId: instance-B recorded again
Exact-instance DELETE instance-A, HTTP 200 instance-B, HTTP 200
Final journal {"version":1,"rentals":[]} {"version":1,"rentals":[]}

The trace recorded a valid principal-<64 hex> in both pre-create snapshots. Neither run emitted a provider_rental_release_unknown or provider_rental_journal_write_failed diagnostic. Both restarted daemons exited cleanly after recovery.

@thymikee

Copy link
Copy Markdown
Member Author

The live Limrun run at 65166c0 covers the evidence the review asked for: the journal holds the reconciliation key and principal before create, the same principal is used after a SIGKILL restart, the exact-ID case deletes the recorded instance without a list call, the rental-key case recovers the instance through the provider=limrun,rentalKey= selector with exactly one match and then deletes it, and both journals end empty with no release or journal-write failure diagnostics. The code findings were already closed at this head, so this is ready for human review. The Body rules check still fails on the current PR body.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 24, 2026
@thymikee
thymikee merged commit e9a2f43 into 0.22 Nov 24, 2026
22 of 24 checks passed
@thymikee
thymikee deleted the t3/persist-provider-recovery-fences branch November 24, 2026 09:37
thymikee added a commit that referenced this pull request Nov 24, 2026
* fix(daemon): recover provider rental fences after restart

* fix(daemon): keep provider release fences through reconciliation

* docs(daemon): explain pending rental retirement

* fix(daemon): retry exact rental writes before legacy recovery

* fix(limrun): reconcile live cleanup by rental key

* refactor(limrun): move heartbeat API probe to client helpers

* refactor(limrun): separate recovery identity and deletion

* fix(daemon): retire confirmed rentals independently and verify recovery principals

* test(limrun): supply recovery request identity in daemon fixtures

* fix(daemon): settle rental retirement and bind Limrun routing headers

* fix(limrun): keep recovery identity stable across SDK upgrades

* fix(limrun): read routing settings from the plugin host

* fix(limrun): derive recovery proof from the SDK client configuration

* fix(limrun): defer rental proof validation import
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant