Skip to content

fix(daemon): fence unresolved provider allocations - #5035

Merged
thymikee merged 6 commits into
0.22from
fix/0.22-fence-provider-allocations
Nov 23, 2026
Merged

thymikee merged 6 commits into
0.22from
fix/0.22-fence-provider-allocations

Conversation

@thymikee

@thymikee thymikee commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Route each lease end through the registry. Keep the device scope reserved until provider release and local cleanup are proved. Recover both existing journals and examine durable claims before startup admission. Amend ADR 0007.

Breaking plugin change. Third-party providers must return a typed { release: 'confirmed' | 'unknown' } result from LeaseLifecycleProvider.release, with metadata under provider.

Before / after

  • lease_allocate could reach overlapping provider creation or report a missing runtime despite a recovered fence. Creating rentals now report DEVICE_LEASE_BUSY, releaseStatus: unknown, and allocationPhase: creating. Pending cleanup and unresolved release have distinct details. A definitive Limrun create rejection permits immediate reuse.
  • lease_release could report success before the claim cleared. It now returns released: false and the outstanding proof while the scope remains reserved. Close retries honor scope and human-control checks.
  • During startup, tenant allocation could return daemon-busy and host PUT could run before recovery. Both now wait. If startup fails, waiting requests receive daemon-startup-failed.

Validation

  • Tests cover allocation failure, cancellation, late creation, expiry, explicit release refusal, host DELETE, session close, provider-ended heartbeat for provider-backed and logical leases, shutdown, and restart.
  • ecfece860f passed frozen install, build, typecheck, lint, format, layering, full Coverage, integration, and all runnable affected checks. Raw store reads stayed at 187.
  • The separate hosted torture file passed 128 seeds, forced contention, and both companion tests. Nine follow-up regression cases failed on 199bbcb.
  • Hosted checks and maintainer re-review are pending.

Closes #4969

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 5.04 MB 5.05 MB +7.9 kB
Package (unpacked) 5.04 MB 5.05 MB +7.9 kB
Package (download) 1.54 MB 1.54 MB +2.1 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 48.7 ms 42.5 ms -6.2 ms
CLI --help 97.5 ms 89.4 ms -8.1 ms

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At 884b140, the fence still has gaps where an unresolved claim or provider release admits an overlapping allocation, and the new startup gate can refuse the first command after a cold start. The CI checks pass except two cancelled "Body rules" runs, a PR-body lint that later runs superseded. They look unrelated, since the diff touches no workflow or body-rule tooling. There are no conflicts. Before merge, the lease_release and host DELETE claim-failure route must keep a registry ending entry, a rejected Limrun create must not be fenced, and startup admission must wait for recovery instead of refusing. Not verified here: the tests and the daemon were not run, and every finding below is traced through the code.

The claim fence exists only when a registry ending entry already exists (lease-session-end.ts:195). Explicit lease_release, host DELETE, and a confirmed provider release all call registry.releaseLease, which deletes the lease and adds no ending entry. If the claim clear then returns unattributable or throws, onClaimReleaseUnconfirmed has no entry to mark, and the retry is skipped. The session and claim file stay, and an overlapping lease_allocate for the same tenant, run, and device is admitted. Base retried this route every 10 s, so a transient claim-lock timeout now strands the session until restart. The rule: every lease end with unresolved session or claim cleanup keeps a registry ending entry until cleanup is confirmed, and the registry is the only path that removes a lease. Please route lease_release, host DELETE, and the confirmed-provider branch through beginProviderLeaseEnd, and add a daemon-runtime test: lease_release, a failing claim clear, then an overlapping allocate that gets releaseReason device-claim-release-unconfirmed.

createSubmitted is set before the Limrun create call (runtime.ts:675). If Limrun rejects that request outright (quota, invalid model, 401), no instance exists, the label lookup is empty, and the evidence check throws. The owner stays "uncertain", the caller sees "instance could not be deleted" instead of the create error, and the lease is fenced with releaseStatus unknown. Recovery repeats the empty lookup every second and the journal restores the fence after restart, so it lasts until someone edits the state files. Base let the same run retry immediately. The rule: fence only a create whose outcome is unknown. A create the provider answered with a rejection is resolved. Please mark the create as possibly rented only when it failed without a provider answer (timeout, abort, transport error), as WebDriver does in runtime-session.ts:288. Add a test: a 4xx create, then the next allocate for the same run succeeds with no label lookup. Not verified here: that a Limrun rejection surfaces as a thrown error with no instance id.

The startup gate refuses lease_allocate and every session-locked command with daemon-busy while startingUp is true (daemon-idle-reap.ts:284). It stays true until after the "registered" phase and device-claim reconciliation, which probes devices. A client that waits for "registered" and sends its first command lands in that window, and daemon-client does not retry daemon-busy on ordinary requests. The first command after a cold start, most likely after a crash, can now fail where base admitted it. The rule: overlapping admission waits for recovery and is never refused for it. Please await a startupRecovered promise, resolved right after reconcileDeviceClaimsForDaemonStartup, before dispatching lease_allocate or session-locked commands. Keep the refusal only for quiesce, and make the quiesce test assert that the allocate completes after openGate. Not verified here: the exact timing between the client's "registered" handling and the end of reconciliation.

A second independent pass found that a keyed Limrun allocation and a keyless one for the same tenant, run, backend and provider can both reach provider creation (lease-registry.ts:831). The run-binding keys differ, and the keyless overlap rule applies only to ending entries. The reverse order has the same gap. Please treat provider creation as a reservation from issuance until the provider settles, apply the same scope comparison to allocating and ending reservations, and keep same-ID joins that cannot start a second create.

A second independent pass found that a WebDriver lease_release with a held artifact callback leaves the lease renewable (lease-release.ts:25). The provider deletes the first session before release returns, and in that gap lease_allocate with the old ID renews the lease and starts a second session. The first release then removes the daemon lease. A thrown Limrun release also leaves the lease active with no unknown outcome recorded. Please move the lease to the registry's ending state before dispatching explicit provider release, keep it on a throw or uncertain result, and let same-lease release retries join the recorded teardown.

A second independent pass found that same-key contention during a pending end returns DEVICE_LEASE_BUSY without releaseStatus (lease-registry.ts:840). A pending end starts with no releaseUnknown, and the error builder emits the status only when it is set. This covers the delete in the failed or canceled allocation test, initial creation, sweeper or startup release, and a failed journal handoff before the first recovery attempt. Please have the registry derive the status from unresolved provider creation or release, with a more specific reason when a refusal or claim failure is known.

A second independent pass found that a recovered fence is masked on the allocation route when the runtime is missing (lease.ts:135). After restart with a valid Limrun journal entry and no Limrun runtime, recovery installs the reservation, but a matching lease_allocate stops at the runtime check and returns UNSUPPORTED_OPERATION or the dormant-plugin error instead of DEVICE_LEASE_BUSY with releaseStatus unknown. The new regression test covers only the registry. Please check the existing ending reservation after authenticating and normalizing the scope, before returning a provider availability error, and keep the availability error for requests with no matching reservation.

A second independent pass found that host lease PUT bypasses startup recovery (host-lease-http.ts:77). In HTTP mode the listener and metadata are published before durable claim reconciliation, and a loopback PUT to /admin/leases/ with a macos-app scope routes straight to the registry without the startingUp check. Please apply the same startup admission state to host PUT before it mutates the registry.

A second independent pass found that startup opens normal admission before the first provider recovery attempt settles (daemon-runtime.ts:664). Journal adoption reserves scopes synchronously but detaches the promise that awaits retryPending, and startingUp clears after claim reconciliation. A nonoverlapping lease is then admitted while recovery is outstanding. Please keep startup admission closed until adoption and the initial recovery pass finish or reach a bounded outcome that leaves unresolved reservations in place.

A second independent pass found that explicit release drops the claim fence before the claim is cleared (lease-release.ts:32). The helper removes the lease and its bindings before session settlement starts, so a keyed lease whose claim file is unattributable or whose unlink throws cannot be marked, and a new same-key lease can be issued while the claim remains. Host DELETE has the same order, and non-retaining session close drops the lease before clearDeviceClaim (session-close.ts:518). Please route explicit release, host DELETE and close through a registry ending reservation, confirm settlement only after an attributable claim clear, and keep the reservation on an unattributable result or throw.

A second independent pass found that WebDriver forgets create requests that may have reached the hub (runtime-session.ts:288). If the hub creates a session and the response connection drops, the transport marks the dispatch unknown, but the manager treats only its create-timeout reason or a cleanupError as uncertain and deletes the entry. Release then returns undefined, the daemon confirms the end, and a fresh same-key allocation can create a second session. Please retain the entry for create outcomes with unknown dispatch and no positive cleanup proof, and distinguish those from a proven refusal before creation.

A second independent pass found that restart drops the new WebDriver fence (provider-lease-expiry.ts:293). After a cloud create times out or a session delete is refused, the daemon keeps an ending reservation, but recordLiveLeases filters it from the journal because the adapter has no recovery callback. A restarted daemon has no record and admits the same scope while the rental may remain. Journal recovery already fences a record when the adapter cannot recover it. Please persist the unresolved scope in the journal even without automatic recovery, restore it as release unknown, and keep requiring proof before reuse.

A second independent pass found that a definitive Limrun create refusal, such as a rate limit, permanently fences a scope that never rented (runtime.ts:675). The runtime marks createSubmitted first and then treats every failed create without an instance ID as needing lookup proof, and an empty lookup throws even though the API identifies the refusal. Base accepted the no-rental result. Please track whether the create outcome can have rented an instance, keep strict identity recovery for ambiguous results, and settle definitive refusals as no rental.

A second independent pass found that Limrun recovery loses proof when a labeled delete succeeds after its wait budget (lease-release.ts:438). The success is seen only inside the discarded wait result, so the next list is empty and the new evidence check rejects it, leaving overlap blocked after a confirmed delete. Please retain and join the exact labeled delete attempt across recovery retries and carry its late success into the result, keeping the empty-lookup refusal for leases with no positive proof.

A second independent pass found that host DELETE regresses for ordinary leases (host-lease-http.ts:84). On base, an authenticated DELETE of a tenant's proxy or backend-only lease revoked it and ended its sessions. At this head it returns released:false and leaves the lease active, while remote-device-lease-contracts.md still tells callers to use host DELETE. These leases have no provider rental to bypass. Please preserve host DELETE for logical leases, and for leases that need a provider runtime either route through fenced provider release or refuse that group explicitly.

Not blocking, and fine to take or leave: no test asserts the wiring from onClaimReleaseUnconfirmed to the registry (daemon-runtime.ts:497), so deleting it keeps every test green; error-reasons.md:795 lists provider-release-unconfirmed as details.reason when callers get it as details.releaseReason on DEVICE_LEASE_BUSY, and the other release reasons and provider.releaseStatus are undocumented; the precedence check repeated at lease-registry.ts:798 would be simpler with a separate claimRelease field on the ending entry; Limrun recovery retries every second for the life of the daemon when the lookup has no evidence, including an instance Limrun already reaped, so back off while keeping the fence and journal entry; the ADR 0007 amendment adds Revyl (#4158) and run-label renewal (#4947) sentences that do not describe this change; the removed comment that explains why claim reconciliation runs after publishDaemonInfo still holds and is worth restoring; and lease_release answers released: true while the scope stays reserved, so it should report released: false or a releaseStatus.

Could the PR be simpler by sending every lease end through one registry entry point, for example beginLeaseEnd(lease, { sessionsSettled, providerRelease }), used for release, expiry, provider-ended, allocation failure or cancel, and shutdown, with confirmExpiredLeaseEnd as the only removal and no direct forget path in registry.releaseLease? The claim reason would then always have an entry to land on, and lease_release would report what the entry says. On the provider side, a typed release outcome such as { release: 'confirmed' | 'unknown' } on LeaseLifecycleProvider.release would replace the thrown error and the payload key, so the four releaseStatus === 'unknown' reads collapse into one place, with each adapter returning unknown only for an unanswered create or delete. That needs a contract change in @agent-device/contracts/device first, and neither it nor the removal needs an ADR beyond the ADR 0007 amendment already here.

@thymikee

Copy link
Copy Markdown
Member Author

Follow-up to the 16:12 UTC review in 123ff7cf8149c4519b14fad7efff6151bebbb8b5.

  • Registry removal — every end enters beginLeaseEnd. The registry removes the ending entry after both proofs.
  • Claim failure — explicit release and close keep the reservation and report the typed claim refusal. The daemon-runtime test checks claim precedence while provider release is also unknown.
  • Limrun create rejection — an answered 4xx other than request timeout preserves the create error, skips label lookup, and allows the next allocation, including after a cancellation that arrives with a confirmed refusal.
  • Cold-start requests — lease allocation and session commands wait for recovery. Quiesce still returns busy during startup.
  • Keyed and keyless creation — both directions share the overlap test used for ending scopes. Same-ID allocation keeps the existing join.
  • WebDriver artifact window — explicit release fences before provider dispatch, so a held provider reply cannot admit renewal.
  • Pending contention — the registry gives DEVICE_LEASE_BUSY a release status and reason as soon as an overlapping end takes the lease.
  • Missing runtime — a recovered overlap reports the fence before the normal provider availability error.
  • Host PUT — authenticated PUT waits on the same recovery promise before changing the registry.
  • Initial journal recovery — startup waits for the first attempt within a bounded window and leaves unresolved entries reserved.
  • Ordinary close — it fences before teardown, keeps claim proof on the entry, and lets the owner retry without renewal.
  • Lost WebDriver create response — the adapter retains the entry when dispatch is unknown.
  • WebDriver restart — the existing live journal retains provider scopes without a recovery hook and restores their unknown status.
  • Late Limrun labeled delete — recovery observes the exact delete to completion and uses its confirmation.
  • Host DELETE — logical leases remain revocable. Provider-backed leases use the same fenced release and can be retried.
  • Release contract and receipts — plugins now return a typed release outcome. Explicit release reports the registry's result.
  • Claim callback wiring — the daemon-runtime test sees the claim reason win while the provider result is also unknown.
  • Error docs — documented releaseStatus and releaseReason where the API returns them, including the three reason values.
  • Retry policy — failed provider recovery backs off while the journal and scope reservation stay in place.
  • Startup diagnostics — restored the comment explaining why claim reconciliation follows daemon publication.
  • ADR 0007 — removed the Revyl and run-label changes.

@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: 3 new findings on 123ff7c. The verdict and the full list are in the summary comment.

Port the concurrency torture harness to the lease-end transition.
@thymikee

Copy link
Copy Markdown
Member Author

199bbcbce2bf972e3182cce0409c11eb875d748c also ports both concurrency torture harness release sites to beginLeaseEnd and confirmation. The exact hosted file passed all 128 seeded interleavings, the 40-seed forced contention case, and both companion tests.

@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 199bbcb. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

At 199bbcb the three inline threads from the earlier review (#5035 (comment)) are fixed, and three problems remain.

Closing a leased session now moves its lease into the ending state at the start of teardown (session-close.ts:475). When teardown then fails with a claim-blocking error, or the provider shutdown was not prepared, close keeps the session but the lease is already out of the active registry. After that, lease_heartbeat returns LEASE_NOT_FOUND, other commands on the session are refused as an inactive lease, and the TTL sweep never releases the provider rental. On base the lease stayed active and expirable. The rule: a lease enters the ending state only once close commits to ending it. Please move the call after the claim-blocking refusal, inside releaseProviderLeaseForClose after the shutdownPrepared guard, so it still runs before provider release and before the claim is cleared. Please also restore the base assertion in session-close-claim-retry.test.ts that a failed teardown leaves the lease active.

A second independent pass found that a fresh lease_allocate for a device with a create still in flight is refused with reason provider-allocation-in-progress and no releaseStatus (lease-registry.ts:903). While creation is unresolved, the refusal should stay DEVICE_LEASE_BUSY with releaseStatus unknown, and the creation phase should travel in a separate detail. daemon-runtime-lease-expiry.test.ts:254 currently asserts the opposite shape. Is there a reason callers should lose those fields here?

A second independent pass found that the new close retry for an ending lease returns the request unchanged (request-execution-scope.ts:364). The host can activate a human-control hold between the failed close and the retry, so platform close then runs during the hold. On base the retry reached assertHumanControlAdmission before device dispatch, and the admitted-mutation pass that drains work on hold activation is also skipped. The rule: a retry close of the exact ending lease keeps the ordinary scope and policy checks and takes the device mutation pass, without renewing the lease. A close-only admission path would satisfy that.

Of the older threads, #5035 (comment) (pending cleanup claim reason) is fixed at this head because releaseReason returns undefined once provider release is confirmed. #5035 (comment) (in-flight create refusal) is outdated and fixed. #5035 (comment) (startup recovery rollback) is fixed because startupRecovered is rejected before rollback.run(). All three can be resolved.

Two checks are not passing. Body rules was cancelled by a later run, and one other check is still in progress. Neither exercises the daemon lease code, so they look unrelated. No conflicts are known.

Not verified here: any behavior at runtime, since no tests or daemon were run. Also not verified here: that fromLimrunOrgApi gives every Limrun refusal a numeric details.status, that a create with wait:true never answers 4xx after Limrun created the instance (runtime.ts:588-590 would then drop the fence), the WebDriver restart path to a DEVICE_LEASE_BUSY releaseStatus unknown reply, and the author's regression counts.

Before merge, close must begin the lease end only after the teardown-failure and shutdown-preparation refusals, so a failed close keeps its lease active and expirable as on base.

@thymikee

Copy link
Copy Markdown
Member Author

Follow-up to the close and allocation review in ecfece860fa0e0769c18d512f1cd64f58983a907.

  • Close starts the lease end after claim-blocking teardown and shutdown-preparation checks. Tests verify both refusals leave the lease active.
  • In-flight creation returns DEVICE_LEASE_BUSY, releaseStatus: unknown, and allocationPhase: creating.
  • Close retries use normal scope, policy, and human-control admission. They take the device mutation pass without renewing the lease. The regression covers hold refusal and hold activation while a retry is in flight.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of e6a47cd

Since the review of 199bbcb: 0 new · 0 still open · 1 no longer raised

No open findings.

1 finding below minor hidden (user_settings.min_severity).

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

💬 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 code at e6a47cd looks good, and the three high-priority findings from the earlier review (#5035 (comment)) are now fixed. Not verified here: no tests or daemon were run, so this reads the code only. Not verified here: a lease shared by two sessions, where a second session's close is admitted while the first session's close ends the lease; the delta does not change which sessions share a lease.

Smoke Tests was still running at this commit. It opens and closes sessions through the daemon, and this change touches the close path and close admission, so it covers the changed route. Please wait for it to pass before merge. No conflicts are known.

The open inline thread on lease expiry (#5035 (comment)) is fixed at this head, because not-required leases now confirm through the release path and the new test covers them. Three other inline threads do not apply and can be resolved: #5035 (comment) (the release reason is empty once the provider is confirmed, so cleanup-pending is the correct report), #5035 (comment) (an in-flight create refuses with unknown release status as required, and carries no release reason), and #5035 (comment) (startup recovery is rejected before rollback runs, so parked requests do not hang).

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 23, 2026
@thymikee
thymikee merged commit f6026f4 into 0.22 Nov 23, 2026
19 of 21 checks passed
@thymikee
thymikee deleted the fix/0.22-fence-provider-allocations branch November 23, 2026 19:09
thymikee added a commit that referenced this pull request Nov 24, 2026
* fix(daemon): fence unresolved provider allocations

* fix(daemon): settle lease ends through one registry transition

* fix(daemon): settle startup failures and report lease phases

Port the concurrency torture harness to the lease-end transition.

* fix(daemon): settle logical leases and admit close retries safely

* refactor(daemon): move lease settlement wait out of request scope

* fix(daemon): require the request settlement abort signal
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