Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions docs/adr/0007-remote-device-leases.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ The daemon keeps the lease end reservation when provider creation fails or the c
If creation succeeds after cancellation, the provider adapter releases the exact instance.
The daemon owns the reservation. The provider adapter owns instance creation, lookup, and release.

At startup, reserve the leases from the live and pending provider journals.
At startup, restore the ending reservations from the rental journal and from the legacy live and pending provider journals. [ADR 0040](0040-daemon-ownership-state-machines.md) defines the rental journal.
Wait for this recovery before you admit an allocation or a session command.
Examine durable device claims under the host-global lock.
Recover only rentals that the provider can attribute to the recorded lease.
Expand Down Expand Up @@ -126,7 +126,6 @@ If `doctor` has no visible session, use detached checks.
- Holds and ordinary proxy leases are in memory, so controllers reconnect after daemon restart.
- Local human-control takeover remains deferred. A future host-global fence must coexist with local session claims.
- Limrun has not moved its lease ownership onto the shared provider lease table ([#4102](https://github.com/callstack/agent-device/issues/4102)).
- The existing journals record provider lease scopes. A crash can occur before there is durable evidence of the rental. [#4972](https://github.com/callstack/agent-device/issues/4972) tracks the durable rental journal.
- An older client or a direct RPC caller that sent no lease id on a leased session is refused. It must send the lease id that its allocation returned.
- `session_list` still shows session names to every holder of the proxy token ([#4908](https://github.com/callstack/agent-device/issues/4908)).
- A web open can be admitted under a non-`macos-app` lease for another backend; admission does not compare the request platform with the lease backend.
11 changes: 9 additions & 2 deletions docs/adr/0040-daemon-ownership-state-machines.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,14 @@ Each machine has one transition owner. Other modules send events. The coordinato
| Ending | Retirement and release confirmed | Ended. Permit reuse when the affected resources are safe. |
| Ending | Cleanup or release uncertain | Ending. Keep the reservation and retry eligible work. |
| Ended | Cleanup or receipt retention ends | Absent. Keep the old credential unusable for admission. |
| Startup | Recoverable journal entry | Ending. Restore its reservation before overlapping admission. |
| Startup | Inherited rental or legacy provider journal entry | Ending. Restore its reservation before overlapping admission. |

At the deadline, check wanted work, holds, and generation before marking `Ending` in the same decision. Schedule the deadline and use the sweep as a backstop. One lease end record covers all sessions, any retained host, and provider release. Keep the `retainOnClose` idle-daemon rule. Once a reservation fences reuse, release the exact provider instance outside execution locks in backend order. An overlapping allocation waits outside locks or returns typed contention. The outermost response reports each lease end once, including on failure. Reserve the lease ID while it can authenticate retained output.

Before a billable create, durably record its contention scope and a fingerprint of the lease ID. When the provider supports reconciliation, record its allocation key before submission. Record the exact instance when the provider identifies it. The rental entry authorizes release after restart and remains until release or absence is confirmed. After registration, reconstruct the reservation in `LeaseRegistry`. Recover by exact identity when known, or use the provider's reconciliation key to find the instance. For either recovery hook, require a matching non-secret principal recorded for the effective provider account and API origin. A module owner label can stay the same when the account or origin changes. A provider can report absence only when it can rule out a late create. An empty lookup alone cannot do so. Keep an unresolved reservation as `release unknown` for the operator.

Once the provider confirms release, retry a failed journal retirement while the daemon owns registration. Include this retry in shutdown. Journal retirement proceeds independently of session and claim cleanup. The contention reservation stays until all cleanup is confirmed.

Register pending holds and admit mutations through one synchronous decision, including on first open. A pending hold fences mutations and becomes active after admitted mutations drain. Cancellation removes only that pending generation. When the last hold ends, restart inactivity timing at release or expiry. Active leases still accept heartbeats. Holds coexist with claims and vanish on restart. Keep host hold and `macos-app` admission rules.

### Session lifetime — `SessionCoordinator`
Expand Down Expand Up @@ -153,14 +157,17 @@ Use generated lifetime IDs for journals. Pass committed output IDs and typed rec
- A command that lacks an admitted capability cannot use a session port. A stale capability cannot act on a replacement. A stale cleanup cannot release its claim. A finalizer cannot register a response path or infer a producer.
- An RPC or SDK caller that used to attach a first lease to an open session must close it and open again. Active recording, trace, and profile work cannot span that ownership change. Same-owner reopen, same-owner capture then open, and retained close then fresh open remain available.
- Remote RPC callers that supplied host destinations must download by output ID. Clients keep local placement, script revision delivery, and recording sidecars. Remote reads of owner-unknown legacy diagnostic logs and recording exports are refused. Keep local recovery and exact-owner recorder cleanup. A committed recording can be served again if the producer proves ownership and the bytes survive. Restore output eligibility after restart only when retention was already durable and the record is verified.
- Restart begins with an empty live session store. The recoverable provider live and pending journals and host-global device claim records are durable. The runtime-only release retry map is lost on crash. An allocation can crash before a recoverable provider identity exists. If release cannot be proved, keep the affected scope fenced as `release unknown` for operator reconciliation. The durable rental journal is a separate issue. Client saved-connection records ([#4925](https://github.com/callstack/agent-device/pull/4925)) follow separately.
- Restart begins with an empty live session store. The rental journal covers new provider allocations from reservation through confirmed release. Legacy live and pending journals still recover through the same lease end owner. Restart retains host-global device claim records. Provider runtimes without restart reconciliation leave a fenced rental for the operator. Client saved-connection records ([#4925](https://github.com/callstack/agent-device/pull/4925)) follow separately.
- Before you roll back to a daemon that predates the rental journal, settle all journaled rentals and verify that the journal is empty. Older daemons read the legacy files and cannot reconstruct these reservations.

### Wire compatibility

For the path cutover, cover 0.22.x and the first release series with the new output contract in both client/daemon directions. Within this window, accept the supported legacy request shape without trusting its paths. Keep trace and perf destinations on the client across start and stop. Give new clients a safe mixed-version path to download. Retire peer-echoed paths and the remote placeholder exchange only after those combinations pass and the release notes state the supported window. Under [ADR 0006](0006-daemon-rpc-protocol-version.md), add `compatibleChanges` acknowledgments for compatible declaration changes. If a declaration is removed or a supported pairing cannot communicate safely, apply the protocol increment rule.

## Rejected alternatives

- Journal only live leases or release retries. A daemon can exit after a billable request and before the provider identifies its instance. The contention reservation must already be durable at that point.

- Add authorization at each store lookup. A late lookup can still choose a different lifetime.
- Let the request or sweep tear down expiry independently. They can duplicate cleanup or race the next allocation.
- Infer an output owner from the reply. Teardown and restart can outlive the request that caused publication.
Expand Down
16 changes: 16 additions & 0 deletions packages/contracts/src/device-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,17 @@ export type DeviceLease = {
expiresAt: number;
};

export type ProviderRentalIdentity = Readonly<{
reconciliationKey?: string;
instanceId?: string;
}>;

export type LeaseLifecycleContext = {
/** Record non-secret provider identifiers before create and when an instance is named. */
rental?: {
beforeCreate: (reconciliationKey: string) => void;
rented: (instanceId: string) => void;
};
flags?: Readonly<Record<string, unknown>>;
initialApp?: string;
cwd?: string;
Expand All @@ -45,6 +55,12 @@ export type ProviderLeaseRelease = {
};

export type LeaseLifecycleProvider = {
/** Return true only when release or absence of this inherited rental is confirmed. */
recoverRental?: (
lease: DeviceLease,
identity: ProviderRentalIdentity,
recordInstance: (instanceId: string) => void,
) => Promise<boolean>;
allocate?: (
lease: DeviceLease,
context?: LeaseLifecycleContext,
Expand Down
1 change: 1 addition & 0 deletions packages/contracts/src/facades/device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export type {
DeviceInventoryProvider,
DeviceLease,
LeaseLifecycleContext,
ProviderRentalIdentity,
LeaseLifecycleProvider,
ProviderLeaseRelease,
ProviderAppCatalog,
Expand Down
2 changes: 2 additions & 0 deletions packages/contracts/src/provider-device-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ export type ProviderExpiredLeaseRecovery = (lease: DeviceLease) => Promise<void>
/** Provider adapter contract; root owns active-runtime and request composition. */
export type ProviderDeviceRuntime = {
provider: string;
/** Non-secret identity of the effective account and API origin that can recover this runtime's rentals. */
readonly rentalRecoveryPrincipal?: string;
leaseLifecycle: LeaseLifecycleProvider;
recoverExpiredLease?: ProviderExpiredLeaseRecovery;
cloudArtifacts?: CloudArtifactProvider;
Expand Down
29 changes: 18 additions & 11 deletions packages/daemon/docs/remote-device-lease-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,26 @@ In-flight work and human-control holds still keep a lease from expiring.
After daemon shutdown begins, no new lease-end teardown starts.
Shutdown waits for any lease-end teardown that already started before it tears sessions down itself.

A daemon that dies while it holds a provider lease leaves the rented device running on the provider side, and that device stays billed.
The daemon journals live provider leases in `live-provider-leases.json` in its state directory.
At startup, allocation and session commands wait until the daemon adopts both journals, checks durable device claims, and gives providers time to recover each rental. Host lease PUT also waits. A recovered scope stays fenced when its provider cannot identify the rental or confirm its release.
It reads both lease records only after it holds the daemon registration for the state directory, because until then they can belong to a daemon that is still running.
The lease itself is not restored, and its controller connects again.
A lease that leaves the registry for expiry stays in the journal until its expired-lease record is durable, and a journal write that fails is retried until this daemon shuts down.
If a journal retry is pending, daemon shutdown makes one final journal write. It does not schedule another journal retry.
A daemon that has shut down writes lease records only synchronously. It arms no timer for them, because a timer could fire after that daemon released its registration, when the records belong to the next daemon.
After the daemon shuts its lease releaser down, that releaser refuses every further provider-backed release. It still writes the expired-lease record of a recoverable lease, so the next daemon inherits it. If no record names the lease, the daemon logs the refusal with its lease provider, because no daemon will end that device.
A provider rental can keep billing after the daemon exits.
Before provider allocation, the daemon writes the contention scope to `provider-rentals.json` in the daemon state directory.
The journal keeps a lease fingerprint, any provider reconciliation key, and the exact instance ID when the provider supplies it.
The daemon reads the rental journal and the legacy live and pending journals after it holds daemon registration.
Allocation, session commands, and host lease PUT wait for startup recovery to restore the reservations.
For an inherited rental, the daemon requires a matching recovery principal for the effective provider account and API origin.
With that proof, the provider can settle the rental by confirming release or proving absence.
If the principal is missing or different, the daemon keeps the rental fenced as `releaseStatus: unknown`.
The legacy live and pending files use their historical adoption path.
Revyl uses a fresh session ID for each journaled create, even if a later lease reuses the public lease ID.
Revyl keeps the lease fenced if a stop reports absence before the provider confirms the instance.
If journal retirement fails after confirmed release, the daemon retries the write, including during shutdown.
The retry can proceed while session or claim cleanup is pending.
The daemon keeps the contention reservation until journal retirement and local cleanup both succeed.
An empty lookup can race a create and leave the reservation as `releaseStatus: unknown`.
Use the journal and daemon diagnostics to identify a rental for provider-side reconciliation.
Before you run a daemon version that predates the rental journal against the same state directory, confirm that all journaled rentals have been released and the journal's `rentals` list is empty.
The live session store starts empty. The controller must connect again.
A failed or canceled first allocation keeps its reservation while the provider can still be creating or releasing the device.
If creation succeeds after cancellation, the adapter releases the exact instance.
If the provider cannot prove release, the reservation remains.
Rentals without durable evidence require operator reconciliation. [#4972](https://github.com/callstack/agent-device/issues/4972) tracks the durable rental journal.

When a request closes a session, the daemon ends the lease of that session, unless the lease was allocated with `retainOnClose`.
The reply to that request reports each lease that it ended once, at response level, as `endedLeases: [{ leaseId, outcome: 'released' }]`.
Expand Down
16 changes: 15 additions & 1 deletion packages/daemon/src/resources/lease-registry-scope.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import crypto from 'node:crypto';
import { providerInstanceUnallocatedError, type DeviceLease } from '@agent-device/contracts/device';
import {
providerInstanceUnallocatedError,
type DeviceLease,
type LeaseLifecycleContext,
} from '@agent-device/contracts/device';
import {
LEASE_REASONS,
MIN_LEASE_WINDOW_MS,
Expand All @@ -22,9 +26,18 @@ export const DEVICE_LEASE_REASONS = {
busy: { reason: 'DEVICE_LEASE_BUSY' },
// The lease is ending and its local session cleanup is still pending.
sessionCleanupPending: { reason: 'session-cleanup-pending' },
// The provider confirmed release. Retry allocation after the daemon records that result.
rentalRetirementPending: { reason: 'provider-rental-retirement-pending' },
} as const satisfies ReasonTable<'leases'>;

export type LeaseRegistryOptions = {
providerRentals?: {
assertLeaseIdAvailable: (leaseId: string) => void;
reserve: (lease: DeviceLease) => void;
context: (lease: DeviceLease) => LeaseLifecycleContext['rental'];
persistPendingInstance: (lease: DeviceLease) => void;
confirmReleased: (lease: DeviceLease) => boolean;
};
maxActiveSimulatorLeases?: number;
defaultLeaseTtlMs?: number;
minLeaseTtlMs?: number;
Expand All @@ -35,6 +48,7 @@ export type LeaseRegistryOptions = {
lease: DeviceLease,
reason?: 'PROVIDER_INSTANCE_ENDED' | 'LEASE_RELEASED',
) => void;
onProviderReleaseConfirmed?: (lease: DeviceLease) => void;
/**
* Called with every live provider lease after a provider lease is issued or leaves the registry, so
* the daemon can journal what a crash would otherwise forget. An expired lease leaves only after
Expand Down
Loading
Loading