diff --git a/docs/adr/0007-remote-device-leases.md b/docs/adr/0007-remote-device-leases.md index dc30b65689..2615c3925e 100644 --- a/docs/adr/0007-remote-device-leases.md +++ b/docs/adr/0007-remote-device-leases.md @@ -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. @@ -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. diff --git a/docs/adr/0040-daemon-ownership-state-machines.md b/docs/adr/0040-daemon-ownership-state-machines.md index c19f2ee441..c6bba7ec8b 100644 --- a/docs/adr/0040-daemon-ownership-state-machines.md +++ b/docs/adr/0040-daemon-ownership-state-machines.md @@ -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` @@ -153,7 +157,8 @@ 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 @@ -161,6 +166,8 @@ For the path cutover, cover 0.22.x and the first release series with the new out ## 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. diff --git a/packages/contracts/src/device-provider.ts b/packages/contracts/src/device-provider.ts index b9ad147309..720098ba80 100644 --- a/packages/contracts/src/device-provider.ts +++ b/packages/contracts/src/device-provider.ts @@ -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>; initialApp?: string; cwd?: string; @@ -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; allocate?: ( lease: DeviceLease, context?: LeaseLifecycleContext, diff --git a/packages/contracts/src/facades/device.ts b/packages/contracts/src/facades/device.ts index beb85376c4..6f2b7fdf30 100644 --- a/packages/contracts/src/facades/device.ts +++ b/packages/contracts/src/facades/device.ts @@ -26,6 +26,7 @@ export type { DeviceInventoryProvider, DeviceLease, LeaseLifecycleContext, + ProviderRentalIdentity, LeaseLifecycleProvider, ProviderLeaseRelease, ProviderAppCatalog, diff --git a/packages/contracts/src/provider-device-runtime.ts b/packages/contracts/src/provider-device-runtime.ts index c96f4230a3..0e13bb097e 100644 --- a/packages/contracts/src/provider-device-runtime.ts +++ b/packages/contracts/src/provider-device-runtime.ts @@ -34,6 +34,8 @@ export type ProviderExpiredLeaseRecovery = (lease: DeviceLease) => Promise /** 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; diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index 7bfd362d3e..cc3134a1ee 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -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' }]`. diff --git a/packages/daemon/src/resources/lease-registry-scope.ts b/packages/daemon/src/resources/lease-registry-scope.ts index 2eb1c18345..e231a1878b 100644 --- a/packages/daemon/src/resources/lease-registry-scope.ts +++ b/packages/daemon/src/resources/lease-registry-scope.ts @@ -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, @@ -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; @@ -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 diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index 507d627f87..1d84b5ef57 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -59,7 +59,7 @@ const LEASE_REGISTRY_REASONS = { type LeaseEnd = { lease: DeviceLease; sessionsSettled: boolean; - providerRelease: 'pending' | 'confirmed'; + providerRelease: 'pending' | 'retiring' | 'confirmed'; claimReleaseUnknown?: true; providerReleaseUnknown?: ReleaseUnknownReason; providerEnded?: true; @@ -78,7 +78,13 @@ function leaseEndBusyError(end: LeaseEnd, lease?: DeviceLease): AppError { const reason = releaseReason(end); return reason ? deviceLeaseBusyError(lease, reason) - : deviceLeaseBusyError(lease, undefined, DEVICE_LEASE_REASONS.sessionCleanupPending.reason); + : deviceLeaseBusyError( + lease, + undefined, + end.providerRelease === 'retiring' + ? DEVICE_LEASE_REASONS.rentalRetirementPending.reason + : DEVICE_LEASE_REASONS.sessionCleanupPending.reason, + ); } type OwnedHumanControlHold = { hold: HumanControlHold; ownerLeaseId?: string }; @@ -114,7 +120,9 @@ export class LeaseRegistry { lease: DeviceLease, reason?: 'PROVIDER_INSTANCE_ENDED' | 'LEASE_RELEASED', ) => void; + private readonly onProviderReleaseConfirmed: LeaseRegistryOptions['onProviderReleaseConfirmed']; private readonly onProviderLeasesChanged?: (leases: readonly DeviceLease[]) => void; + private readonly providerRentals: LeaseRegistryOptions['providerRentals']; private readonly providerSessionOwnership: ProviderSessionOwnershipRegistry; constructor(options: LeaseRegistryOptions = {}) { @@ -125,6 +133,8 @@ export class LeaseRegistry { this.now = options.now ?? (() => Date.now()); this.onLeaseExpired = options.onLeaseExpired; this.onProviderLeasesChanged = options.onProviderLeasesChanged; + this.onProviderReleaseConfirmed = options.onProviderReleaseConfirmed; + this.providerRentals = options.providerRentals; this.providerSessionOwnership = new ProviderSessionOwnershipRegistry({ now: this.now, retentionMs: options.providerSessionRetentionMs, @@ -141,12 +151,16 @@ export class LeaseRegistry { reason: LEASE_REGISTRY_REASONS.idInUse.reason, }); } + if (chosenLeaseId) this.providerRentals?.assertLeaseIdAvailable(chosenLeaseId); this.assertHumanControlAdmission(normalized); this.assertDeviceAvailable(normalized); this.assertNoRunBindingLease(normalized); this.enforceCapacity(normalized.backend); const lease = createDeviceLease(normalized, leaseTtlMs, this.now(), chosenLeaseId); - if (providerAllocating) this.allocating.add(lease.leaseId); + if (providerAllocating) { + this.providerRentals?.reserve(lease); + this.allocating.add(lease.leaseId); + } this.issueLease(lease); return { ...lease }; } @@ -339,13 +353,21 @@ export class LeaseRegistry { return true; } + providerRentalContext(lease: DeviceLease) { + return this.providerRentals?.context(lease); + } + + persistProviderRentalInstance(lease: DeviceLease): void { + this.providerRentals?.persistPendingInstance(lease); + } + finishProviderAllocation(leaseId: string): void { this.allocating.delete(leaseId); } joinProviderRelease(leaseId: string, release: () => Promise) { const end = this.ending.get(leaseId); - if (!end || end.providerRelease === 'confirmed') + if (!end || end.providerRelease !== 'pending') return Promise.resolve({ release: 'confirmed' }); return (end.releaseAttempt ??= Promise.resolve() .then(release) @@ -364,7 +386,7 @@ export class LeaseRegistry { pendingRequestedLeaseEnds(): DeviceLease[] { return [...this.ending.values()] - .filter((end) => end.requestRelease && end.providerRelease === 'pending') + .filter((end) => end.requestRelease && end.providerRelease !== 'confirmed') .map(({ lease }) => lease); } @@ -874,6 +896,16 @@ export class LeaseRegistry { return this.ending.get(leaseId)?.providerRelease === 'pending'; } + isProviderRentalRetirementPending(leaseId: string): boolean { + return this.ending.get(leaseId)?.providerRelease === 'retiring'; + } + + confirmRequestProviderRelease(lease: DeviceLease): void { + if (leaseProviderRequiringRuntime(lease) && this.onProviderReleaseConfirmed) + this.onProviderReleaseConfirmed(lease); + else this.confirmLeaseEnd(lease.leaseId, 'providerReleased'); + } + leaseEndRefusal(leaseId: string): AppError | undefined { const end = this.ending.get(leaseId); return end && leaseEndBusyError(end); @@ -883,6 +915,10 @@ export class LeaseRegistry { const end = this.ending.get(leaseId); if (!end) return true; if (part === 'providerReleased') { + if (this.providerRentals?.confirmReleased(end.lease) === false) { + end.providerRelease = 'retiring'; + return false; + } end.providerRelease = 'confirmed'; this.reportProviderLeases(end.lease); } else { diff --git a/packages/daemon/src/resources/lease-release.ts b/packages/daemon/src/resources/lease-release.ts index 10eb0cfb92..9ebb1914eb 100644 --- a/packages/daemon/src/resources/lease-release.ts +++ b/packages/daemon/src/resources/lease-release.ts @@ -25,7 +25,7 @@ export async function releaseLease( .catch((error: unknown): ProviderLeaseRelease => ({ release: 'unknown', error })); if (outcome?.release === 'confirmed' || (!outcome && !leaseProviderRequiringRuntime(lease))) { recordProviderSession(registry, lease, outcome?.provider); - registry.confirmLeaseEnd(lease.leaseId, 'providerReleased'); + registry.confirmRequestProviderRelease(lease); return outcome ?? { release: 'confirmed' }; } registry.markLeaseReleaseUnknown(lease.leaseId, 'provider-release-unconfirmed'); diff --git a/packages/daemon/src/resources/provider-rental-journal.test.ts b/packages/daemon/src/resources/provider-rental-journal.test.ts new file mode 100644 index 0000000000..b2670cb392 --- /dev/null +++ b/packages/daemon/src/resources/provider-rental-journal.test.ts @@ -0,0 +1,24 @@ +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { expect, test } from 'vitest'; +import { createProviderRentalJournal } from './provider-rental-journal.ts'; + +test('an allocation holding an old journal callback cannot submit a create after shutdown', () => { + const journal = createProviderRentalJournal(mkdtempForTestSync('provider-rental-')); + const lease = { + leaseId: '1234567890abcdef1234567890abcdef', + tenantId: 'tenant', + runId: 'run', + backend: 'ios-simulator' as const, + leaseProvider: 'limrun', + createdAt: 0, + heartbeatAt: 0, + expiresAt: 60_000, + }; + journal.reserve(lease); + const context = journal.context(lease)!; + journal.close(); + expect(() => context.beforeCreate('late-create')).toThrow( + 'Provider rental reservation is unavailable', + ); + expect(journal.identity(lease)).toEqual({}); +}); diff --git a/packages/daemon/src/resources/provider-rental-journal.ts b/packages/daemon/src/resources/provider-rental-journal.ts new file mode 100644 index 0000000000..e3ef7c4d51 --- /dev/null +++ b/packages/daemon/src/resources/provider-rental-journal.ts @@ -0,0 +1,220 @@ +import { createHash } from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import type { + DeviceLease, + LeaseLifecycleContext, + ProviderRentalIdentity, +} from '@agent-device/contracts/device'; +import { normalizeLeaseId } from '@agent-device/contracts/lease-scope'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { publishDurableFileSync } from '@agent-device/host-kit/file'; +import { readLeaseBackend } from '@agent-device/kernel/contracts'; +import { deviceLeaseBusyError } from './lease-registry-scope.ts'; + +type Rental = { + lease: DeviceLease; + rentalRecoveryPrincipal?: string; + legacyLeaseId?: string; + releaseOnRestart: ProviderRentalIdentity; +}; + +export type ProviderRentalPolicy = (provider: string) => { + rentalRecoveryPrincipal?: string; + legacyRecovery: boolean; +}; + +export type ProviderRentalJournal = ReturnType; + +export function createProviderRentalJournal(stateDir: string, policy?: ProviderRentalPolicy) { + const destination = path.join(stateDir, 'provider-rentals.json'); + let entries = new Map(); + const unrecordedInstances = new Map(); + let closed = false; + + const write = (updated: Map): void => { + publishDurableFileSync({ + destination, + contents: `${JSON.stringify({ version: 1, rentals: [...updated.values()] })}\n`, + mode: 0o600, + }); + entries = updated; + }; + + const policyFor = (lease: DeviceLease) => + lease.leaseProvider ? policy?.(lease.leaseProvider) : undefined; + const idFor = (lease: DeviceLease): string => + entries.has(lease.leaseId) ? lease.leaseId : rentalId(lease.leaseId); + + const update = ( + lease: DeviceLease, + change: (entries: Map, id: string) => void, + ): void => { + if (closed) return; + const updated = new Map(entries); + change(updated, idFor(lease)); + write(updated); + }; + + const record = (lease: DeviceLease, identity: ProviderRentalIdentity): void => { + const entry = entries.get(idFor(lease)); + if (closed || !entry) throw new Error('Provider rental reservation is unavailable.'); + update(lease, (updated, id) => { + updated.set(id, { ...entry, releaseOnRestart: { ...entry.releaseOnRestart, ...identity } }); + }); + }; + const recordInstance = (lease: DeviceLease, instanceId: string): void => + record(lease, { instanceId }); + + const reportFailure = (lease: DeviceLease, error: unknown): void => { + emitDiagnostic({ + level: 'error', + phase: 'provider_rental_journal_write_failed', + data: { resourcePath: destination, rentalId: idFor(lease), error: String(error) }, + }); + }; + + const persistPendingInstance = (lease: DeviceLease): void => { + const id = idFor(lease); + const instanceId = unrecordedInstances.get(id); + if (instanceId === undefined) return; + recordInstance(lease, instanceId); + unrecordedInstances.delete(id); + }; + const retryPendingInstance = (lease: DeviceLease): void => { + if (closed) return; + try { + persistPendingInstance(lease); + } catch (error) { + reportFailure(lease, error); + } + }; + + return { + restore: () => { + let contents: string; + try { + contents = fs.readFileSync(destination, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; + throw error; + } + const parsed = JSON.parse(contents) as { version?: unknown; rentals?: unknown }; + if ( + parsed?.version !== 1 || + !Array.isArray(parsed.rentals) || + !parsed.rentals.every(isRental) + ) { + throw new Error(`Invalid provider rental journal: ${destination}`); + } + entries = new Map(parsed.rentals.map((entry) => [entry.lease.leaseId, entry])); + }, + path: destination, + inheritedLeases: () => [...entries.values()].map(({ lease }) => lease), + identity: (lease: DeviceLease) => entries.get(idFor(lease))?.releaseOnRestart, + legacyLeaseId: (lease: DeviceLease) => entries.get(idFor(lease))?.legacyLeaseId, + hasMatchingRecoveryPrincipal: (lease: DeviceLease) => { + const recorded = entries.get(idFor(lease))?.rentalRecoveryPrincipal; + return recorded !== undefined && recorded === policyFor(lease)?.rentalRecoveryPrincipal; + }, + assertLeaseIdAvailable: (leaseId: string) => { + if (entries.has(rentalId(leaseId))) { + throw deviceLeaseBusyError(undefined, 'provider-release-unconfirmed'); + } + }, + reserve: (lease: DeviceLease) => { + if (closed) throw new Error('Provider rental journal is closed.'); + const id = rentalId(lease.leaseId); + const recovery = policyFor(lease); + const { clientId, retainOnClose, ...scope } = lease; + update(lease, (updated) => + updated.set(id, { + lease: { + ...scope, + leaseId: id, + ...(recovery?.legacyRecovery ? { clientId, retainOnClose } : {}), + }, + rentalRecoveryPrincipal: recovery?.rentalRecoveryPrincipal, + legacyLeaseId: recovery?.legacyRecovery ? lease.leaseId : undefined, + releaseOnRestart: {}, + }), + ); + }, + recordInstance, + persistPendingInstance, + retryPendingInstance, + context: (lease: DeviceLease): LeaseLifecycleContext['rental'] => { + if (!entries.has(idFor(lease))) return undefined; + return { + beforeCreate: (reconciliationKey) => record(lease, { reconciliationKey }), + rented: (instanceId) => { + const id = idFor(lease); + if (closed || !entries.has(id)) return; + unrecordedInstances.set(id, instanceId); + retryPendingInstance(lease); + }, + }; + }, + confirmReleased: (lease: DeviceLease): boolean => { + if (!entries.has(idFor(lease))) return true; + if (closed) return false; + const id = idFor(lease); + try { + update(lease, (updated, id) => updated.delete(id)); + unrecordedInstances.delete(id); + return true; + } catch (error) { + reportFailure(lease, error); + return false; + } + }, + close: () => { + closed = true; + }, + }; +} + +function rentalId(leaseId: string): string { + return `rental-${createHash('sha256').update(leaseId).digest('hex')}`; +} + +function isRental(value: unknown): value is Rental { + const entry = value as Partial | null; + return ( + !!entry && + isRentalScope(entry.lease) && + (entry.rentalRecoveryPrincipal === undefined || + (typeof entry.rentalRecoveryPrincipal === 'string' && + entry.rentalRecoveryPrincipal.trim().length > 0)) && + (entry.legacyLeaseId === undefined || + (typeof entry.legacyLeaseId === 'string' && + normalizeLeaseId(entry.legacyLeaseId) === entry.legacyLeaseId && + rentalId(entry.legacyLeaseId) === entry.lease?.leaseId)) && + isRentalIdentity(entry.releaseOnRestart) + ); +} + +function isRentalScope(lease: DeviceLease | undefined): boolean { + return ( + !!lease && + typeof lease.leaseId === 'string' && + /^rental-[a-f0-9]{64}$/.test(lease.leaseId) && + [lease.tenantId, lease.runId, lease.leaseProvider].every( + (field) => typeof field === 'string', + ) && + typeof lease.backend === 'string' && + readLeaseBackend(lease.backend) === lease.backend && + (lease.deviceKey === undefined || typeof lease.deviceKey === 'string') && + [lease.createdAt, lease.heartbeatAt, lease.expiresAt].every(Number.isFinite) + ); +} + +function isRentalIdentity(identity: ProviderRentalIdentity | undefined): boolean { + return ( + !!identity && + typeof identity === 'object' && + [identity.reconciliationKey, identity.instanceId].every( + (field) => field === undefined || typeof field === 'string', + ) + ); +} diff --git a/packages/daemon/src/server/__tests__/provider-lease-expiry.test.ts b/packages/daemon/src/server/__tests__/provider-lease-expiry.test.ts index 9dc69ea73b..44057d8dc6 100644 --- a/packages/daemon/src/server/__tests__/provider-lease-expiry.test.ts +++ b/packages/daemon/src/server/__tests__/provider-lease-expiry.test.ts @@ -260,6 +260,38 @@ test('shutdown drain reports releases completed before and during its final retr } }); +test('shutdown drain retries retirement when a provider stop confirms during its wait', async () => { + const lease = new LeaseRegistry().allocateLease({ + tenantId: 'tenant-a', + runId: 'run-1', + leaseProvider: 'browserstack', + }); + const release = vi + .fn() + .mockRejectedValueOnce(new Error('temporary outage')) + .mockResolvedValueOnce({ release: 'confirmed' }); + const onReleased = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true); + const releaser = createExpiredProviderLeaseReleaser({ + leaseLifecycleProvider: { release }, + providerRuntimeIds: ['browserstack'], + onReleased, + }); + + try { + await expect(releaser.release(lease)).resolves.toEqual({ status: 'retrying' }); + releaser.beginShutdown(); + await expect(releaser.drain(2_000)).resolves.toEqual({ + pending: [], + unknown: [], + released: [lease], + }); + expect(release).toHaveBeenCalledTimes(2); + expect(onReleased).toHaveBeenCalledTimes(2); + } finally { + releaser.shutdown(); + } +}); + test('a shutdown drain that settles inside its budget leaves no deadline timer behind', async () => { vi.useFakeTimers(); const releaser = createExpiredProviderLeaseReleaser({ @@ -536,58 +568,69 @@ test('daemon startup recovers inherited lease records only after it holds the re expect(source.indexOf('expiredProviderLeaseReleaser.retryPending()')).toBe(-1); }); -test('a release that fails after shutdown is not retried and stays durable', async () => { - vi.useFakeTimers(); - const stateDir = mkdtempForTestSync('agent-device-expired-provider-lease-'); - const lease = new LeaseRegistry().allocateLease({ - tenantId: 'tenant-a', - runId: 'run-1', - leaseProvider: 'limrun', - }); - let rejectHeldRelease: ((error: Error) => void) | undefined; - const recoverExpiredLease = vi.fn( - () => - new Promise((_resolve, reject) => { - rejectHeldRelease = reject; - }), - ); - const releaser = createExpiredProviderLeaseReleaser({ - recoverExpiredLease, - stateDir, - recoverableProviderIds: ['limrun'], - retryDelayMs: 1_000, - }); - - try { - releaser.beginShutdown(); - // The provider call is still in flight when the drain budget runs out, so its outcome is unknown. - const admitted = releaser.release(lease); - const drained = releaser.drain(10); - await vi.advanceTimersByTimeAsync(10); - expect(await drained).toEqual({ pending: [lease], unknown: [lease], released: [] }); - expect(recoverExpiredLease).toHaveBeenCalledTimes(1); - - // Plugins are disposed here. The provider call this daemon is waiting on then fails. - releaser.shutdown(); - rejectHeldRelease!(new Error('provider plugin disposed')); - await vi.advanceTimersByTimeAsync(60_000); +test.each(['success', 'failure'])( + 'a release that reports %s after shutdown stays durable without callbacks', + async (result) => { + vi.useFakeTimers(); + const stateDir = mkdtempForTestSync('agent-device-expired-provider-lease-'); + const lease = new LeaseRegistry().allocateLease({ + tenantId: 'tenant-a', + runId: 'run-1', + leaseProvider: 'limrun', + }); + let finishHeldRelease!: () => void; + const recoverExpiredLease = vi.fn( + () => + new Promise((resolve, reject) => { + finishHeldRelease = () => + result === 'success' ? resolve() : reject(new Error('provider plugin disposed')); + }), + ); + const onReleased = vi.fn(); + const onReleaseUnknown = vi.fn(); + const releaser = createExpiredProviderLeaseReleaser({ + recoverExpiredLease, + stateDir, + recoverableProviderIds: ['limrun'], + retryDelayMs: 1_000, + onReleased, + onReleaseUnknown, + }); - expect(recoverExpiredLease).toHaveBeenCalledTimes(1); - // Nothing is armed to call the provider again, and nothing is armed to write a lease record. - expect(vi.getTimerCount()).toBe(0); - const record = JSON.parse( - fs.readFileSync(`${stateDir}/expired-provider-leases.json`, 'utf8'), - ) as { leases: DeviceLease[] }; - expect(record.leases.map((entry) => entry.leaseId)).toEqual([lease.leaseId]); - // The provider call this daemon was waiting on failed once the releaser had closed, so the lease - // stayed pending, and nothing here will attempt it again. The record is what carries it forward. - await expect(admitted).resolves.toEqual({ status: 'refused', reason: 'closed', durable: true }); - } finally { - releaser.shutdown(); - vi.useRealTimers(); - fs.rmSync(stateDir, { recursive: true, force: true }); - } -}); + try { + releaser.beginShutdown(); + // The provider call is still in flight when the drain budget runs out, so its outcome is unknown. + const admitted = releaser.release(lease); + const drained = releaser.drain(10); + await vi.advanceTimersByTimeAsync(10); + expect(await drained).toEqual({ pending: [lease], unknown: [lease], released: [] }); + expect(recoverExpiredLease).toHaveBeenCalledTimes(1); + + releaser.shutdown(); + finishHeldRelease(); + await vi.advanceTimersByTimeAsync(60_000); + + expect(recoverExpiredLease).toHaveBeenCalledTimes(1); + expect(onReleased).not.toHaveBeenCalled(); + expect(onReleaseUnknown).not.toHaveBeenCalled(); + // Nothing is armed to call the provider again, and nothing is armed to write a lease record. + expect(vi.getTimerCount()).toBe(0); + const record = JSON.parse( + fs.readFileSync(`${stateDir}/expired-provider-leases.json`, 'utf8'), + ) as { leases: DeviceLease[] }; + expect(record.leases.map((entry) => entry.leaseId)).toEqual([lease.leaseId]); + await expect(admitted).resolves.toEqual({ + status: 'refused', + reason: 'closed', + durable: true, + }); + } finally { + releaser.shutdown(); + vi.useRealTimers(); + fs.rmSync(stateDir, { recursive: true, force: true }); + } + }, +); test('release after shutdown starts no provider call and retries nothing', async () => { vi.useFakeTimers(); @@ -623,17 +666,13 @@ test('release after shutdown starts no provider call and retries nothing', async await expect(releaser.release(recoverableLease)).resolves.toEqual({ status: 'refused', reason: 'closed', - durable: true, + durable: false, }); await vi.advanceTimersByTimeAsync(60_000); expect(release).not.toHaveBeenCalled(); expect(recoverExpiredLease).not.toHaveBeenCalled(); - // What a closed daemon cannot release, it leaves durable for the next one. - const record = JSON.parse( - fs.readFileSync(`${stateDir}/expired-provider-leases.json`, 'utf8'), - ) as { leases: DeviceLease[] }; - expect(record.leases.map((entry) => entry.leaseId)).toEqual([recoverableLease.leaseId]); + expect(fs.existsSync(`${stateDir}/expired-provider-leases.json`)).toBe(false); } finally { releaser.shutdown(); vi.useRealTimers(); diff --git a/packages/daemon/src/server/http/daemon-runtime-deps.ts b/packages/daemon/src/server/http/daemon-runtime-deps.ts index 4ec0615867..3cb5ea4abc 100644 --- a/packages/daemon/src/server/http/daemon-runtime-deps.ts +++ b/packages/daemon/src/server/http/daemon-runtime-deps.ts @@ -15,6 +15,7 @@ import type { InteractorResolution } from '../../core/interactor-resolution.ts'; import type { PlatformOwnerLifecycle } from '../../core/platform-owner-lifecycle.ts'; import type { ProviderDeviceAdmission } from '../../core/provider-device-admission.ts'; import type { RequestRouterDeps } from '../request-router.ts'; +import type { ProviderRentalPolicy } from '../../resources/provider-rental-journal.ts'; /** * Every capability the daemon runtime cannot construct for itself: the platform and provider @@ -54,6 +55,7 @@ export type DaemonRuntimeDeps = Readonly<{ providerRuntimeIds: readonly string[]; recoverExpiredLease?: ProviderExpiredLeaseRecovery; recoverableProviderIds: readonly string[]; + providerRentalPolicy?: ProviderRentalPolicy; /** The runtime gateway every lifecycle and recovery step in this server runs through. */ deviceRuntimeGateway: RequestRouterDeps['deviceRuntimeGateway']; /** The resource-cleanup surface the session teardowns run through. */ diff --git a/packages/daemon/src/server/http/daemon-runtime-lease-expiry.test.ts b/packages/daemon/src/server/http/daemon-runtime-lease-expiry.test.ts index 3377600776..1cb3227ab9 100644 --- a/packages/daemon/src/server/http/daemon-runtime-lease-expiry.test.ts +++ b/packages/daemon/src/server/http/daemon-runtime-lease-expiry.test.ts @@ -130,7 +130,8 @@ async function startProviderDaemon(deps: Partial, inheritedLe composeDeps: daemonRuntimeDepsFixture({ providerRuntimeIds: ['limrun'], ...deps }), host: createTestHostEnvironment({ env: { - ...process.env, + PATH: process.env.PATH, + TMPDIR: process.env.TMPDIR, AGENT_DEVICE_STATE_DIR: stateDir, AGENT_DEVICE_CLAIMS_DIR: `${stateDir}/claims`, AGENT_DEVICE_DAEMON_SERVER_MODE: 'http', @@ -299,6 +300,71 @@ test('same-ID allocation cannot renew while an explicit release is awaiting its } }); +test.each(['timer', 'shutdown'] as const)( + 'retries rental retirement during %s after close overlaps lease_release', + async (retry) => { + const entered = barrier(); + const answer = barrier(); + const release = vi.fn(async () => { + entered.open(); + await answer.reached; + return { release: 'confirmed' as const }; + }); + const { runtime, store, stateDir } = await startProviderDaemon({ + leaseLifecycleProvider: { + allocate: async (_lease, context) => { + context?.rental?.beforeCreate('fixture-key'); + context?.rental?.rented('fixture-instance'); + return {}; + }, + release, + }, + }); + const allocated = await leaseRpc(runtime, 'allocate', { ttlMs: 60_000 }); + const lease = allocated.result?.data?.lease as DeviceLease; + assert.ok(lease); + store.publish('leased', makeIosSession('leased', { lease })); + const journal = `${stateDir}/provider-rentals.json`; + const rentals = () => JSON.parse(fs.readFileSync(journal, 'utf8')).rentals; + const rename = fs.renameSync; + const failRetirement = vi.spyOn(fs, 'renameSync').mockImplementation((source, target) => { + if (target === journal) throw new Error('Rental retirement write failed'); + rename(source, target); + }); + const close = leaseRpc(runtime, 'close', { leaseId: lease.leaseId }); + let concurrentRelease: ReturnType | undefined; + try { + await entered.reached; + concurrentRelease = leaseRpc(runtime, 'release', { leaseId: lease.leaseId }); + await vi.waitFor(() => { + expect(leaseProbe.ended).toContainEqual([lease.leaseId, 'LEASE_RELEASED']); + }); + answer.open(); + expect(await close).toMatchObject({ result: { ok: true } }); + expect(await concurrentRelease).toMatchObject({ result: { data: { released: false } } }); + expect(rentals()).toHaveLength(1); + expect(await leaseRpc(runtime, 'allocate', { runId: 'successor' })).toMatchObject({ + error: { data: { code: 'DEVICE_IN_USE' } }, + }); + + failRetirement.mockRestore(); + if (retry === 'timer') await vi.advanceTimersByTimeAsync(1_000); + else await closeProviderDaemon(runtime); + expect(rentals()).toHaveLength(0); + expect(release).toHaveBeenCalledOnce(); + if (retry === 'timer') + expect(await leaseRpc(runtime, 'allocate', { runId: 'successor' })).toMatchObject({ + result: { ok: true }, + }); + } finally { + failRetirement.mockRestore(); + answer.open(); + await Promise.allSettled([close, concurrentRelease]); + await closeProviderDaemon(runtime); + } + }, +); + test('a close retry admits the ending lease owner through the device mutation pass', async () => { const dispatched = barrier(); const answer = barrier(); @@ -383,10 +449,15 @@ test('an inherited scope is refused as release unknown when its runtime is missi test.each(['confirmed', 'unknown'] as const)( 'explicit release reports an unattributable claim with provider release %s', async (providerRelease) => { - const { runtime, registry, store, stateDir } = await startProviderDaemon({ - leaseLifecycleProvider: { release: async () => ({ release: providerRelease }) }, + const { runtime, store, stateDir } = await startProviderDaemon({ + leaseLifecycleProvider: { + allocate: async () => ({}), + release: async () => ({ release: providerRelease }), + }, }); - const lease = registry.allocateLease(providerLease); + const allocated = await leaseRpc(runtime, 'allocate', { ttlMs: 60_000 }); + const lease = allocated.result?.data?.lease as DeviceLease; + assert.ok(lease); const session = makeIosSession('leased', { lease }); const env = { ...process.env, AGENT_DEVICE_CLAIMS_DIR: `${stateDir}/claims` }; vi.stubEnv('AGENT_DEVICE_CLAIMS_DIR', env.AGENT_DEVICE_CLAIMS_DIR); @@ -410,6 +481,8 @@ test.each(['confirmed', 'unknown'] as const)( releaseStatus: 'unknown', releaseReason: 'device-claim-release-unconfirmed', }); + const journal = JSON.parse(fs.readFileSync(`${stateDir}/provider-rentals.json`, 'utf8')); + expect(journal.rentals).toHaveLength(providerRelease === 'confirmed' ? 0 : 1); expect((await leaseRpc(runtime, 'allocate')).error?.data?.details).toMatchObject({ releaseStatus: 'unknown', releaseReason: 'device-claim-release-unconfirmed', diff --git a/packages/daemon/src/server/http/daemon-runtime.ts b/packages/daemon/src/server/http/daemon-runtime.ts index 2b1ee8fef1..b0069295bf 100644 --- a/packages/daemon/src/server/http/daemon-runtime.ts +++ b/packages/daemon/src/server/http/daemon-runtime.ts @@ -299,11 +299,15 @@ async function startDaemonRuntimeOnHost( installProviderDeviceAdmission(deps.providerDeviceAdmission); installInteractorResolution(deps.interactorResolution); const { createLeaseSessionEnd } = await import('../lease-session-end.ts'); + const { createProviderRentalJournal } = + await import('../../resources/provider-rental-journal.ts'); + const providerRentals = createProviderRentalJournal(baseDir, deps.providerRentalPolicy); const expiredProviderLeaseReleaser = createExpiredProviderLeaseReleaser({ leaseLifecycleProvider: deps.leaseLifecycleProvider, providerRuntimeIds: deps.providerRuntimeIds, recoverExpiredLease: deps.recoverExpiredLease, stateDir: baseDir, + providerRentals, recoverableProviderIds: deps.recoverableProviderIds, onRecovered: (lease) => leaseRegistry.beginLeaseEnd(lease, { sessionsSettled: true, providerRelease: 'pending' }), @@ -313,11 +317,13 @@ async function startDaemonRuntimeOnHost( onReleased: (lease) => { if (leaseRegistry.confirmLeaseEnd(lease.leaseId, 'providerReleased')) leaseSessionEnd.forgetClosing(lease.leaseId); + return !leaseRegistry.isProviderRentalRetirementPending(lease.leaseId); }, withinDiagnosticsScope: async (run) => await withDaemonDiagnosticsScope({ logPath }, run), }); rollback.onRollback(() => expiredProviderLeaseReleaser.shutdown()); const leaseRegistry = new LeaseRegistry({ + providerRentals, maxActiveSimulatorLeases: parseIntegerEnv(env.AGENT_DEVICE_MAX_SIMULATOR_LEASES), defaultLeaseTtlMs: parseIntegerEnv(env.AGENT_DEVICE_LEASE_TTL_MS), minLeaseTtlMs: parseIntegerEnv(env.AGENT_DEVICE_LEASE_MIN_TTL_MS), @@ -361,12 +367,10 @@ async function startDaemonRuntimeOnHost( ) .finally(finishProvider); }, + onProviderReleaseConfirmed: expiredProviderLeaseReleaser.confirmRelease, onProviderLeasesChanged: (leases) => expiredProviderLeaseReleaser.recordLiveLeases(leases), }); - // The registry only notices an expired lease when something calls it; this sweep ends an - // abandoned lease (and, through `onLeaseExpired`, its session and claim) without a later request. const leaseExpirySweep = setInterval(() => { - // The sweep runs outside any request, so the releases it starts report into a daemon scope. void withDaemonDiagnosticsScope({ logPath }, () => { try { leaseRegistry.consumeExpiredLeases(); @@ -547,8 +551,6 @@ async function startDaemonRuntimeOnHost( // Reaps this daemon process when it sits fully idle (no open sessions, no // in-flight requests, no active recording) past AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS. - // `close` is defined below but only invoked asynchronously by the timer, - // well after this closure captures it. const inFlightRequests = new Set>(); // Who owns this process decides what it publishes and which lifecycle request it answers. A host // that starts the runtime passes `embedded`; the daemon executable leaves it detached. @@ -676,12 +678,12 @@ async function startDaemonRuntimeOnHost( scope: createRecoveryPlatformScope(), onDiagnostic: (diagnostic) => startupDiagnostics.push(diagnostic), }); + providerRentals.restore(); const providerRecovery = withDaemonDiagnosticsScope({ logPath }, async () => { await expiredProviderLeaseReleaser.recoverInherited((diagnostic) => startupDiagnostics.push(diagnostic), ); }).catch((error) => { - // Startup has no request scope, so the failure goes to the daemon log directly. void emitDaemonDiagnostic(logPath, 'provider_lease_startup_recovery_failed', { error: error instanceof Error ? error.message : String(error), }).catch(() => undefined); @@ -696,8 +698,6 @@ async function startDaemonRuntimeOnHost( openWebSessionNames: openWebSessionNames(sessionStore), ownedProcessRecords: deps.ownedProcessRecords, }); - // Marker-gated lifecycle recovery owns test-IME orphan repair. Its implementation remains - // lazy until the marker exists, so a normal daemon startup does not load or probe adb. void applicationLifecycle.recoverStartupResources({ stateDir: baseDir }).catch((error) => { void emitDaemonDiagnostic(logPath, 'daemon_lifecycle_startup_recovery_failed', { error: error instanceof Error ? error.message : String(error), @@ -796,8 +796,7 @@ async function startDaemonRuntimeOnHost( leaseSessionEnd.cancel(); clearInterval(leaseExpirySweep); stopMetadataLossWatch(); - // Cancellation and the listener close run together: a connection held by a request that ignores - // cancellation is force-closed at the same budget the drain gives it. + // Close uncooperative connections within the request drain budget. const serversClosed = closeDaemonServers(servers, requestDrainTimeoutMs); if (closeOptions.cause) await emitFatalDiagnostic(closeOptions.cause); const requests = await drainInFlightRequests(); @@ -928,6 +927,7 @@ async function startDaemonRuntimeOnHost( report = await closeSteps(closeOptions); return report; } finally { + expiredProviderLeaseReleaser.shutdown(); await Promise.allSettled([ settleWithin(async () => await releasePngWorker(), DAEMON_PNG_WORKER_TERMINATE_TIMEOUT_MS), Promise.resolve().then(() => pluginClose.close()), @@ -952,8 +952,6 @@ async function startDaemonRuntimeOnHost( } }; - // Idle reap, external callers and the executable's signal handlers all close through here, and - // none of them runs inside the startup scope, so the close re-enters it. let closing: Promise | undefined; let settleClosed: { resolve(report: ShutdownReport): void; reject(error: unknown): void }; const closed = new Promise((resolve, reject) => { @@ -975,7 +973,6 @@ async function startDaemonRuntimeOnHost( return closing; }; - // A detached daemon leaves when it loses its registration. stopMetadataLossWatch = armDaemonMetadataLossWatch( baseDir, infoPath, diff --git a/packages/daemon/src/server/provider-lease-expiry.ts b/packages/daemon/src/server/provider-lease-expiry.ts index 67c186687b..3488debac3 100644 --- a/packages/daemon/src/server/provider-lease-expiry.ts +++ b/packages/daemon/src/server/provider-lease-expiry.ts @@ -7,6 +7,7 @@ import type { ProviderExpiredLeaseRecovery, } from '@agent-device/contracts/device'; import { publishFileSync } from '@agent-device/host-kit/file'; +import type { ProviderRentalJournal } from '../resources/provider-rental-journal.ts'; import type { ReleaseUnknownReason } from '../resources/lease-registry-scope.ts'; import { releaseExpiredProviderLease } from '../sessions/lease-lifecycle.ts'; import { emitDiagnostic, type ResourceDiagnostic } from '@agent-device/host-kit/diagnostics'; @@ -35,10 +36,8 @@ type Timer = ReturnType; /** * The lifecycle of one releaser. `running` admits releases and re-arms retries. `draining` is the - * bounded shutdown window in which the final release attempts run. `closed` starts no provider attempt - * and arms no timer: its providers may already be disposed, and a timer could fire after this daemon - * released its registration and rewrite records the next daemon owns. It still writes lease records - * synchronously, because they are how the next daemon learns what to recover. + * bounded shutdown window in which the final release attempts run. `closed` prevents new attempts, + * release callbacks, and journal writes so the next daemon can take ownership of the records. */ type ReleaserPhase = 'running' | 'draining' | 'closed'; @@ -51,10 +50,8 @@ type ReleaseRefusalReason = 'closed' | 'provider-runtime-unavailable'; * What one `release` call did with the lease it was given. * * `released` means this daemon ended the lease with its provider. `retrying` means this daemon still - * owns the lease and will attempt it again. `not-required` means no provider ever held it. `refused` - * means this daemon will not end this lease: `reason` says why, and `durable` says whether a lease - * record now names it for the next daemon. A refused lease whose `durable` is false is a device no - * daemon will end, so every caller reports it. + * owns the lease and will retry release or journal retirement. `not-required` means no provider ever + * held it. `refused` gives the reason and whether a durable record preserves the scope for restart. */ export type ProviderLeaseReleaseOutcome = | { status: 'released' } @@ -73,13 +70,14 @@ export type ExpiredProviderLeaseReleaser = { /** * Ends one lease. Admits it while this releaser runs or is draining, and answers with what it did. * Once closed it refuses: no provider attempt starts and no pending work is admitted, because the - * providers may already be disposed. A recoverable lease is still made durable for the next daemon, - * which is what the outcome's `durable` answers. + * providers may already be disposed. The outcome's `durable` reports whether a record already exists. */ release: ( lease: DeviceLease, afterSessionCleanup?: Promise, ) => Promise; + /** Records a request-owned stop and retries journal retirement while registration is held. */ + confirmRelease: (lease: DeviceLease) => void; /** Journals the registry's live provider leases, so a daemon killed while holding them recovers them. */ recordLiveLeases: (leases: readonly DeviceLease[]) => void; /** @@ -108,19 +106,25 @@ export function createExpiredProviderLeaseReleaser(options: { providerRuntimeIds?: readonly string[]; recoverExpiredLease?: ProviderExpiredLeaseRecovery; stateDir?: string; + providerRentals?: ProviderRentalJournal; recoverableProviderIds?: readonly string[]; retryDelayMs?: number; onRecovered?: (lease: DeviceLease) => void; needsProviderRelease?: (lease: DeviceLease) => boolean; - /** The provider half is confirmed, including leases that had no provider to release. */ - onReleased?: (lease: DeviceLease) => void; + /** Returns false if the confirmed release still needs journal retirement. */ + onReleased?: (lease: DeviceLease) => boolean | void; onReleaseUnknown?: (lease: DeviceLease, reason: ReleaseUnknownReason) => void; /** Gives a timer-driven retry, which runs outside any request, a diagnostics scope. */ withinDiagnosticsScope?: (run: () => Promise) => Promise; }): ExpiredProviderLeaseReleaser { const pendingLiveLeases = new Map(); const pendingRecoveryLeases = new Map(); + const pendingRetirements = new Map(); + const inheritedRentalIds = new Set(); const persistedRecoveryLeaseIds = new Set(); + let persistedLiveLeaseIds = new Set(); + const hasRentalRecord = (lease: DeviceLease) => + options.providerRentals?.identity(lease) !== undefined; let inherited = false; const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS; let retryTimer: Timer | undefined; @@ -129,6 +133,7 @@ export function createExpiredProviderLeaseReleaser(options: { const releaseContext = new AsyncResource('ProviderLeaseExpiry'); const sessionCleanup = new Map>(); let phase: ReleaserPhase = 'running'; + const isClosed = () => phase === 'closed'; /** The releases this drain window observed; replaced at each window so one window's set is never another's. */ let drainReleasedLeases = new Map(); const runScoped = (run: () => Promise): void => { @@ -158,16 +163,18 @@ export function createExpiredProviderLeaseReleaser(options: { const confirmProviderRelease = ( lease: DeviceLease, status: 'released' | 'not-required' = 'released', - ): void => { - options.onReleased?.(lease); - if (status === 'not-required') return; + ): boolean => { + if (options.onReleased?.(lease) === false) return false; + if (status === 'not-required') return true; // The drain window is the only period that reports releases, so the phase is the tracker and the // set cannot grow outside it. nextRetryDelayMs = retryDelayMs; if (phase === 'draining') drainReleasedLeases.set(lease.leaseId, lease); + return true; }; const persistPendingLeases = (): boolean => { + if (isClosed()) return false; if (!options.stateDir) { emitPersistenceFailure( pendingRecoveryLeases.size, @@ -176,9 +183,11 @@ export function createExpiredProviderLeaseReleaser(options: { return false; } try { - writeLeaseRecord(options.stateDir, PENDING_RELEASES_FILE, [ - ...pendingRecoveryLeases.values(), - ]); + writeLeaseRecord( + options.stateDir, + PENDING_RELEASES_FILE, + [...pendingRecoveryLeases.values()].filter((lease) => !hasRentalRecord(lease)), + ); persistedRecoveryLeaseIds.clear(); for (const leaseId of pendingRecoveryLeases.keys()) { persistedRecoveryLeaseIds.add(leaseId); @@ -197,7 +206,8 @@ export function createExpiredProviderLeaseReleaser(options: { const orphaned = loadLeaseRecord(options.stateDir, LIVE_LEASES_FILE, onDiagnostic); if (orphaned.size === 0) return; for (const [leaseId, lease] of orphaned) { - if (!pendingRecoveryLeases.has(leaseId)) pendingRecoveryLeases.set(leaseId, lease); + if (!pendingRecoveryLeases.has(leaseId) && !hasRentalRecord(lease)) + pendingRecoveryLeases.set(leaseId, lease); } // The journal is dropped only once its leases are in the pending record, so a crash in between // leaves them in one file or the other. @@ -225,7 +235,7 @@ export function createExpiredProviderLeaseReleaser(options: { * that fails is retried with the latest leases until one lands. */ const writeJournal = (): void => { - if (!options.stateDir) return; + if (isClosed() || !options.stateDir) return; const unpersisted = [...pendingRecoveryLeases.values()].filter( (lease) => !persistedRecoveryLeaseIds.has(lease.leaseId), ); @@ -239,13 +249,11 @@ export function createExpiredProviderLeaseReleaser(options: { ); try { writeLeaseRecord(options.stateDir, LIVE_LEASES_FILE, [...journal.values()]); + persistedLiveLeaseIds = new Set(journal.keys()); if (journalRetryTimer) clearTimeout(journalRetryTimer); journalRetryTimer = undefined; } catch (error) { emitJournalFailure('provider_lease_journal_write_failed', journal.size, error); - // The retry timer is not armed once closed: it could fire after this daemon released its - // registration, and writes made then belong to the daemon that holds it. - if (phase === 'closed') return; journalRetryTimer ??= setTimeout(() => { journalRetryTimer = undefined; runScoped(async () => writeJournal()); @@ -253,10 +261,63 @@ export function createExpiredProviderLeaseReleaser(options: { journalRetryTimer.unref?.(); } }; + const inheritedRental = (lease: DeviceLease) => + inheritedRentalIds.has(lease.leaseId) ? options.providerRentals : undefined; + + const canRecover = (lease: DeviceLease): boolean => { + if (options.needsProviderRelease?.(lease) === false) return true; + const rental = inheritedRental(lease); + if (!rental) return isRecoverableProviderAvailable(lease, options.recoverableProviderIds); + if ( + !rental.hasMatchingRecoveryPrincipal(lease) || + !isProviderRuntimeAvailable(lease, options.providerRuntimeIds) + ) + return false; + if (rental.legacyLeaseId(lease)) + return ( + !!options.recoverExpiredLease && + isRecoverableProviderAvailable(lease, options.recoverableProviderIds) + ); + const identity = rental.identity(lease); + return ( + !!(identity?.instanceId || identity?.reconciliationKey) && + !!options.leaseLifecycleProvider?.recoverRental + ); + }; + + const reportUnavailableRecovery = ( + lease: DeviceLease, + onDiagnostic: ((diagnostic: ResourceDiagnostic) => void) | undefined, + ): void => { + const rental = inheritedRental(lease); + const reason = + rental && isProviderRuntimeAvailable(lease, options.providerRuntimeIds) + ? 'provider-release-unconfirmed' + : 'provider-runtime-unavailable'; + options.onReleaseUnknown?.(lease, reason); + onDiagnostic?.({ + phase: 'provider_lease_release_refused', + resourcePath: + rental?.path ?? + (options.stateDir + ? leaseRecordPath(options.stateDir, PENDING_RELEASES_FILE) + : PENDING_RELEASES_FILE), + data: { + leaseId: lease.leaseId, + provider: lease.leaseProvider, + releaseStatus: 'unknown', + reason, + ...(rental?.hasMatchingRecoveryPrincipal(lease) === false + ? { recoveryPrincipalUnverified: true } + : {}), + }, + }); + }; + const recoverInherited = async ( onDiagnostic?: (diagnostic: ResourceDiagnostic) => void, ): Promise => { - if (inherited) return; + if (isClosed() || inherited) return; inherited = true; // Everything in the expired record is durable by definition, which is what the persisted ids track. for (const [leaseId, lease] of loadLeaseRecord( @@ -264,36 +325,29 @@ export function createExpiredProviderLeaseReleaser(options: { PENDING_RELEASES_FILE, onDiagnostic, )) { - pendingRecoveryLeases.set(leaseId, lease); + if (!hasRentalRecord(lease)) pendingRecoveryLeases.set(leaseId, lease); + } + for (const lease of options.providerRentals?.inheritedLeases() ?? []) { + pendingRecoveryLeases.set(lease.leaseId, lease); + inheritedRentalIds.add(lease.leaseId); } for (const leaseId of pendingRecoveryLeases.keys()) persistedRecoveryLeaseIds.add(leaseId); adoptOrphanedLeases(onDiagnostic); for (const lease of pendingRecoveryLeases.values()) { options.onRecovered?.(lease); if ( - !isRecoverableProviderAvailable(lease, options.recoverableProviderIds) || - !options.recoverExpiredLease + !canRecover(lease) || + (!inheritedRentalIds.has(lease.leaseId) && !options.recoverExpiredLease) ) { - const reason = 'provider-runtime-unavailable'; - options.onReleaseUnknown?.(lease, reason); - onDiagnostic?.({ - phase: 'provider_lease_release_refused', - resourcePath: options.stateDir - ? leaseRecordPath(options.stateDir, PENDING_RELEASES_FILE) - : PENDING_RELEASES_FILE, - data: { - leaseId: lease.leaseId, - provider: lease.leaseProvider, - releaseStatus: 'unknown', - reason, - }, - }); + reportUnavailableRecovery(lease, onDiagnostic); } } await retryPending(); }; const recordLiveLeases = (leases: readonly DeviceLease[]): void => { - liveLeases = leases.filter((lease) => leaseProviderRequiringRuntime(lease) !== undefined); + liveLeases = leases.filter( + (lease) => leaseProviderRequiringRuntime(lease) !== undefined && !hasRentalRecord(lease), + ); writeJournal(); }; @@ -303,8 +357,9 @@ export function createExpiredProviderLeaseReleaser(options: { // inherits whatever these lease records still hold. phase === 'closed' || retryTimer || - (!hasRetryableLiveLease(pendingLiveLeases, options.providerRuntimeIds) && - !hasRetryableRecoveryLease(pendingRecoveryLeases, options.recoverableProviderIds)) + (pendingRetirements.size === 0 && + ![...pendingLiveLeases.values()].some(canAttemptLiveRelease) && + ![...pendingRecoveryLeases.values()].some(canRecover)) ) { return; } @@ -318,6 +373,7 @@ export function createExpiredProviderLeaseReleaser(options: { level: 'warn', phase: 'provider_lease_expiry_retry_scheduled', data: { + pendingRetirementCount: pendingRetirements.size, pendingLiveLeaseCount: pendingLiveLeases.size, pendingRecoveryLeaseCount: pendingRecoveryLeases.size, retryDelayMs: nextRetryDelayMs, @@ -325,11 +381,31 @@ export function createExpiredProviderLeaseReleaser(options: { }); }; + const retireConfirmedRelease = (lease: DeviceLease): void => { + if (isClosed()) return; + if (!confirmProviderRelease(lease)) { + pendingRetirements.set(lease.leaseId, lease); + scheduleRetry(); + return; + } + pendingRetirements.delete(lease.leaseId); + pendingLiveLeases.delete(lease.leaseId); + if (pendingRecoveryLeases.delete(lease.leaseId)) { + inheritedRentalIds.delete(lease.leaseId); + persistPendingLeases(); + } + }; + const trackReleaseAttempt = (key: string, attempt: Promise): Promise => { activeReleaseAttempts.set(key, attempt); const finish = (): void => { if (activeReleaseAttempts.get(key) === attempt) activeReleaseAttempts.delete(key); - if (pendingLiveLeases.size === 0 && pendingRecoveryLeases.size === 0 && retryTimer) { + if ( + pendingRetirements.size === 0 && + pendingLiveLeases.size === 0 && + pendingRecoveryLeases.size === 0 && + retryTimer + ) { clearTimeout(retryTimer); retryTimer = undefined; } else { @@ -342,52 +418,88 @@ export function createExpiredProviderLeaseReleaser(options: { const startReleaseAttempt = (leaseId: string, key: string, run: () => Promise) => { const after = sessionCleanup.get(leaseId); + const runIfOpen = async () => { + if (!isClosed()) await run(); + }; const attempt = after ? releaseContext.runInAsyncScope(async () => { await after; - if (phase !== 'closed') await (options.withinDiagnosticsScope?.(run) ?? run()); + if (!isClosed()) await (options.withinDiagnosticsScope?.(runIfOpen) ?? runIfOpen()); }) - : run(); + : runIfOpen(); return trackReleaseAttempt(key, attempt); }; + const canAttemptLiveRelease = (lease: DeviceLease): boolean => + options.needsProviderRelease?.(lease) === false || + (!!options.leaseLifecycleProvider?.release && + isProviderRuntimeAvailable(lease, options.providerRuntimeIds)); + + const usesLegacyRelease = (lease: DeviceLease): boolean => + isRecoverableProviderAvailable(lease, options.recoverableProviderIds) && + (!hasRentalRecord(lease) || options.providerRentals?.legacyLeaseId(lease) !== undefined); + const ensureLiveReleaseAttempt = (lease: DeviceLease): Promise | undefined => { - if (phase === 'closed') return undefined; - if (!isProviderRuntimeAvailable(lease, options.providerRuntimeIds)) return undefined; + if (isClosed() || pendingRetirements.has(lease.leaseId) || !canAttemptLiveRelease(lease)) + return undefined; const key = `live:${lease.leaseId}`; const activeAttempt = activeReleaseAttempts.get(key); if (activeAttempt) return activeAttempt; return startReleaseAttempt(lease.leaseId, key, async () => { - if ( - options.needsProviderRelease?.(lease) === false || - (await releaseLiveProviderLease(options.leaseLifecycleProvider, lease)) - ) { - pendingLiveLeases.delete(lease.leaseId); - confirmProviderRelease(lease); - } else options.onReleaseUnknown?.(lease, 'provider-release-unconfirmed'); + let released = options.needsProviderRelease?.(lease) === false; + if (!released) { + options.providerRentals?.retryPendingInstance(lease); + released = await releaseLiveProviderLease(options.leaseLifecycleProvider, lease); + } + if (isClosed()) return; + if (released) retireConfirmedRelease(lease); + else options.onReleaseUnknown?.(lease, 'provider-release-unconfirmed'); }); }; const ensureRecoveryReleaseAttempt = (lease: DeviceLease): Promise | undefined => { - if (phase === 'closed') return undefined; - if (!isRecoverableProviderAvailable(lease, options.recoverableProviderIds)) return undefined; + if (isClosed() || pendingRetirements.has(lease.leaseId) || !canRecover(lease)) return undefined; if (!persistedRecoveryLeaseIds.has(lease.leaseId) && !persistPendingLeases()) return undefined; const key = `recovery:${lease.leaseId}`; const activeAttempt = activeReleaseAttempts.get(key); if (activeAttempt) return activeAttempt; + const recoverRental = options.leaseLifecycleProvider?.recoverRental; + const rental = inheritedRental(lease); + const identity = rental?.identity(lease); + const legacyLeaseId = rental?.legacyLeaseId(lease); + const recoverLegacy = options.recoverExpiredLease; + const recordInstance = (instanceId: string) => rental?.recordInstance(lease, instanceId); + const recover = + rental && !legacyLeaseId + ? identity && recoverRental && (() => recoverRental(lease, identity, recordInstance)) + : recoverLegacy && + (() => recoverLegacy(legacyLeaseId ? { ...lease, leaseId: legacyLeaseId } : lease)); return startReleaseAttempt(lease.leaseId, key, async () => { - if ( + options.providerRentals?.retryPendingInstance(lease); + const released = options.needsProviderRelease?.(lease) === false || - (await releaseExpiredProviderLease(options.recoverExpiredLease, lease)) - ) { - pendingRecoveryLeases.delete(lease.leaseId); - confirmProviderRelease(lease); - persistPendingLeases(); - } else options.onReleaseUnknown?.(lease, 'provider-release-unconfirmed'); + (await releaseExpiredProviderLease(recover, lease)); + if (isClosed()) return; + if (released) { + retireConfirmedRelease(lease); + } else { + options.onReleaseUnknown?.(lease, 'provider-release-unconfirmed'); + if (identity) + emitDiagnostic({ + level: 'warn', + phase: 'provider_rental_release_unknown', + data: { rentalId: lease.leaseId, provider: lease.leaseProvider, ...identity }, + }); + } }); }; + const retryRetirements = (): void => { + for (const lease of pendingRetirements.values()) retireConfirmedRelease(lease); + }; + const retryPending = async (): Promise => { + retryRetirements(); const attempts = [ ...[...pendingLiveLeases.values()].map(ensureLiveReleaseAttempt), ...[...pendingRecoveryLeases.values()].map(ensureRecoveryReleaseAttempt), @@ -399,34 +511,23 @@ export function createExpiredProviderLeaseReleaser(options: { await Promise.all(attempts); }; - /** - * Refuses a lease that arrives once this releaser is closed. Nothing is awaited and no attempt is - * tracked, because that work belongs to the daemon that now owns the state directory. A recoverable - * lease is still written out: `pendingRecoveryLeases` is the content of its lease record, so writing - * through the map is what makes the handoff durable, and the outcome says so. - */ - const refuseClosedRelease = (lease: DeviceLease): ProviderLeaseReleaseOutcome => { - if (!isRecoverableProviderAvailable(lease, options.recoverableProviderIds)) { - return { status: 'refused', reason: 'closed', durable: false }; - } - pendingRecoveryLeases.set(lease.leaseId, lease); - return { status: 'refused', reason: 'closed', durable: persistPendingLeases() }; - }; + const refuseClosedRelease = (lease: DeviceLease): ProviderLeaseReleaseOutcome => ({ + status: 'refused', + reason: 'closed', + durable: + hasRentalRecord(lease) || + persistedLiveLeaseIds.has(lease.leaseId) || + persistedRecoveryLeaseIds.has(lease.leaseId), + }); - /** What the attempt this release started came to. The pending entry is the provider's answer: it is removed only when the provider confirmed the end. */ + /** A lease stays pending until provider release and rental retirement are complete. */ const releaseOutcomeFor = ( lease: DeviceLease, pendingLeases: ReadonlyMap, ): ProviderLeaseReleaseOutcome => { if (!pendingLeases.has(lease.leaseId)) return { status: 'released' }; // The releaser closed while the provider call was in flight, so nothing here will attempt it again. - if (phase === 'closed') { - return { - status: 'refused', - reason: 'closed', - durable: persistedRecoveryLeaseIds.has(lease.leaseId), - }; - } + if (isClosed()) return refuseClosedRelease(lease); return { status: 'retrying' }; }; @@ -437,13 +538,11 @@ export function createExpiredProviderLeaseReleaser(options: { }, release: async (lease, afterSessionCleanup) => { if (!leaseProviderRequiringRuntime(lease)) { - confirmProviderRelease(lease, 'not-required'); + if (!isClosed()) confirmProviderRelease(lease, 'not-required'); return { status: 'not-required' }; } - if (phase === 'closed') { - options.onReleaseUnknown?.(lease, 'provider-release-unconfirmed'); - return refuseClosedRelease(lease); - } + if (isClosed()) return refuseClosedRelease(lease); + if (pendingRetirements.has(lease.leaseId)) return { status: 'retrying' }; if (afterSessionCleanup) { sessionCleanup.set(lease.leaseId, afterSessionCleanup); const forget = () => { @@ -451,23 +550,23 @@ export function createExpiredProviderLeaseReleaser(options: { }; void afterSessionCleanup.then(forget, forget); } - if (isRecoverableProviderAvailable(lease, options.recoverableProviderIds)) { + if (usesLegacyRelease(lease)) { // Set before the first await: the registry journals right after `onLeaseExpired` returns, and the // journal keeps this lease only while it is pending here and not yet durable. pendingRecoveryLeases.set(lease.leaseId, lease); - if (persistPendingLeases()) { - await ensureRecoveryReleaseAttempt(lease); - } else { - scheduleRetry(); - } + if (hasRentalRecord(lease)) persistedRecoveryLeaseIds.add(lease.leaseId); + const attempt = ensureRecoveryReleaseAttempt(lease); + if (attempt) await attempt; + else scheduleRetry(); return releaseOutcomeFor(lease, pendingRecoveryLeases); } - if ( - !isProviderRuntimeAvailable(lease, options.providerRuntimeIds) || - !options.leaseLifecycleProvider?.release - ) { + if (!canAttemptLiveRelease(lease)) { options.onReleaseUnknown?.(lease, 'provider-runtime-unavailable'); - return { status: 'refused', reason: 'provider-runtime-unavailable', durable: false }; + return { + status: 'refused', + reason: 'provider-runtime-unavailable', + durable: hasRentalRecord(lease), + }; } pendingLiveLeases.set(lease.leaseId, lease); await ensureLiveReleaseAttempt(lease); @@ -475,6 +574,7 @@ export function createExpiredProviderLeaseReleaser(options: { if (outcome.status === 'retrying') scheduleRetry(); return outcome; }, + confirmRelease: retireConfirmedRelease, recordLiveLeases, recoverInherited, retryPending, @@ -484,8 +584,15 @@ export function createExpiredProviderLeaseReleaser(options: { // A release that fails inside the budget is still a pending release: the // drain reports it, it never throws past the bounded window. await settleWithin(() => retryPending(), Math.max(0, timeoutMs)).catch(() => undefined); + retryRetirements(); const result = { - pending: [...pendingLiveLeases.values(), ...pendingRecoveryLeases.values()], + pending: [ + ...new Map([ + ...pendingLiveLeases, + ...pendingRecoveryLeases, + ...pendingRetirements, + ]).values(), + ], unknown: [ ...[...pendingLiveLeases.values()].filter((lease) => activeReleaseAttempts.has(`live:${lease.leaseId}`), @@ -493,23 +600,21 @@ export function createExpiredProviderLeaseReleaser(options: { ...[...pendingRecoveryLeases.values()].filter((lease) => activeReleaseAttempts.has(`recovery:${lease.leaseId}`), ), - ], + ].filter((lease) => !pendingRetirements.has(lease.leaseId)), released: [...drainReleasedLeases.values()], }; drainReleasedLeases = new Map(); return result; }, shutdown: () => { + if (isClosed()) return; + if (journalRetryTimer) writeJournal(); advancePhase('closed'); + options.providerRentals?.close(); if (retryTimer) clearTimeout(retryTimer); retryTimer = undefined; - if (journalRetryTimer) { - // One last attempt, so a journal that a retry was still owed does not outlive this daemon stale. - // The closed phase keeps this the last lease record write that is owed a retry. - clearTimeout(journalRetryTimer); - journalRetryTimer = undefined; - writeJournal(); - } + if (journalRetryTimer) clearTimeout(journalRetryTimer); + journalRetryTimer = undefined; }, }; } @@ -561,24 +666,6 @@ async function releaseLiveProviderLease( ); } -function hasRetryableLiveLease( - pendingLeases: ReadonlyMap, - providerRuntimeIds: readonly string[] | undefined, -): boolean { - return [...pendingLeases.values()].some((lease) => - isProviderRuntimeAvailable(lease, providerRuntimeIds), - ); -} - -function hasRetryableRecoveryLease( - pendingLeases: ReadonlyMap, - recoverableProviderIds: readonly string[] | undefined, -): boolean { - return [...pendingLeases.values()].some((lease) => - isRecoverableProviderAvailable(lease, recoverableProviderIds), - ); -} - function isProviderRuntimeAvailable( lease: DeviceLease, providerRuntimeIds: readonly string[] | undefined, diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index e879ff8ef9..614c78517c 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -164,9 +164,11 @@ export async function handleLeaseCommands(args: LeaseHandlerArgs): Promise { if (error instanceof AppError && error.details?.releaseStatus === 'confirmed') { registry.beginLeaseEnd(lease, { sessionsSettled: true, providerRelease: 'confirmed' }); - registry.confirmLeaseEnd(lease.leaseId, 'providerReleased'); + registry.confirmRequestProviderRelease(lease); return { release: 'confirmed' }; } return await settleAllocationRelease(lease, provider, registry, undefined).catch( diff --git a/packages/plugins/src/contract.ts b/packages/plugins/src/contract.ts index a7482ab134..f3e950e068 100644 --- a/packages/plugins/src/contract.ts +++ b/packages/plugins/src/contract.ts @@ -94,12 +94,13 @@ export type PluginConnection = Readonly<{ }>; /** - * The provider runtime a plugin builds. This type names only `provider` and `shutdown`; the host - * also requires `leaseLifecycle`, `ownsDevice`, `getInteractor` and `deviceInventoryProvider` from + * The provider runtime a plugin builds. The host also requires `leaseLifecycle`, `ownsDevice`, `getInteractor` and `deviceInventoryProvider` from * the provider runtime contract before it registers the runtime. */ export type PluginProviderRuntime = Readonly<{ provider: string; + /** Non-secret identity of the effective account and API origin that can recover this runtime's rentals. */ + rentalRecoveryPrincipal?: string; shutdown(): Promise; }>; diff --git a/packages/plugins/src/validate.ts b/packages/plugins/src/validate.ts index 7ee8d368c2..e8a3ce1308 100644 --- a/packages/plugins/src/validate.ts +++ b/packages/plugins/src/validate.ts @@ -659,6 +659,11 @@ export function assertProviderRuntime( ) { throw invalidPlugin(`Plugin runtime owner does not match its provider: ${provider}`); } + const principal = runtime.rentalRecoveryPrincipal; + if (principal !== undefined && (typeof principal !== 'string' || principal.trim().length === 0)) + throw invalidPlugin( + `Provider rental recovery principal must be a nonempty string: ${provider}`, + ); } function hasProviderFacets(runtime: ProviderDeviceRuntime): boolean { diff --git a/packages/provider-aws-device-farm/src/aws-device-farm.ts b/packages/provider-aws-device-farm/src/aws-device-farm.ts index c0a9df8774..063a7a46c1 100644 --- a/packages/provider-aws-device-farm/src/aws-device-farm.ts +++ b/packages/provider-aws-device-farm/src/aws-device-farm.ts @@ -182,6 +182,7 @@ export function createAwsDeviceFarmPrepareSession( }); // The ARN is a billed session from here on; any failure short of RUNNING // must stop it before surfacing, or it bills until AWS reaps it. + req?.rental?.rented(remoteAccess.arn); let running: AwsDeviceFarmRemoteAccessSession; let endpoint: string | undefined; try { diff --git a/packages/provider-limrun/src/client-options.ts b/packages/provider-limrun/src/client-options.ts index 8a3aaf9a46..81a50ac1d0 100644 --- a/packages/provider-limrun/src/client-options.ts +++ b/packages/provider-limrun/src/client-options.ts @@ -6,7 +6,7 @@ import { type AppErrorCode, type ReasonTable, } from '@agent-device/kernel/errors'; -import type { LimrunDeleteResult } from './lease-ownership.ts'; +import type { LimrunDeleteResult, LimrunRuntimeSession } from './lease-ownership.ts'; export const LIMRUN_CLIENT_ID = 'agent-device-cli'; @@ -168,3 +168,41 @@ function limrunOrgApiError(error: unknown): unknown { }, ); } + +const HEARTBEAT_PROBE_BUDGET_MS = 2_000; + +/** + * The termination reason of a created instance whose connection dropped, or `undefined` when the + * instance is not terminated or the probe cannot tell. The budget only stops waiting, so the probe + * aborts its own GET when the budget expires. + */ +export async function readLimrunTerminationReason( + limrun: Limrun, + session: Pick, + requestSignal: AbortSignal | undefined, +): Promise { + const expiry = new AbortController(); + const signal = requestSignal ? AbortSignal.any([requestSignal, expiry.signal]) : expiry.signal; + try { + const { awaitLimrunWithinBudget } = await import('./lifecycle-budget.ts'); + const request = + session.platform === 'ios' + ? limrun.iosInstances.get(session.instanceId, { signal }) + : limrun.androidInstances.get(session.instanceId, { signal }); + const answer = await awaitLimrunWithinBudget(request, HEARTBEAT_PROBE_BUDGET_MS); + if (!answer.ok) { + if ('expired' in answer) expiry.abort(); + return undefined; + } + if (answer.value.status.state !== 'terminated') return undefined; + // The termination reason is the account API's own text, and this request carries the account key in + // its header, so it goes through the same reader as an instance's error body before it is published. + const { safeTerminationReason } = await import('./error-text.ts'); + return safeTerminationReason(answer.value.status.terminationReason, [ + limrun.apiKey ?? undefined, + session.token, + ]); + } catch { + return undefined; + } +} diff --git a/packages/provider-limrun/src/lease-ownership.ts b/packages/provider-limrun/src/lease-ownership.ts index 569a1d6e44..60888683ae 100644 --- a/packages/provider-limrun/src/lease-ownership.ts +++ b/packages/provider-limrun/src/lease-ownership.ts @@ -38,6 +38,10 @@ export type LimrunLeaseOwner = { */ rentedInstanceId: string | undefined; createSubmitted?: true; + rental?: Readonly<{ + reconciliationKey: string; + recordInstance: (instanceId: string) => void; + }>; /** * The session this lease's create built, recorded the moment it existed. It is the handle that holds the * instance connection and the host ADB endpoint open, so it stays on the owner even when a later step of diff --git a/packages/provider-limrun/src/lease-release-observation.test.ts b/packages/provider-limrun/src/lease-release-observation.test.ts index ed9399638b..8c94f6a15d 100644 --- a/packages/provider-limrun/src/lease-release-observation.test.ts +++ b/packages/provider-limrun/src/lease-release-observation.test.ts @@ -18,7 +18,11 @@ const state = vi.hoisted(() => ({ /** Instance deletes this runtime asked Limrun for; each waits for its case to answer it. */ deletes: [] as Array<{ instanceId: string; report: () => void }>, creates: 0, + createLabels: undefined as Readonly> | undefined, + createError: undefined as Error | undefined, listedInstance: undefined as string | undefined, + listInstances: undefined as ((labelSelector: string) => string[]) | undefined, + deleteInstance: vi.fn<(instanceId: string) => void>(), deleteDispatched: undefined as (() => void) | undefined, clientStarts: 0, clientGate: undefined as Promise | undefined, @@ -36,9 +40,11 @@ vi.mock('@limrun/api', () => ({ default: class MockLimrun { readonly iosInstances = { create: vi.fn(), list: vi.fn(), delete: vi.fn() }; readonly androidInstances = { - create: async () => { + create: async ({ metadata }: { metadata: { labels: Readonly> } }) => { state.creates += 1; + state.createLabels = metadata.labels; await state.createGate; + if (state.createError) throw state.createError; return { metadata: { id: 'android-instance-1' }, status: { @@ -48,13 +54,16 @@ vi.mock('@limrun/api', () => ({ }, }; }, - list: vi.fn(async () => ({ - getPaginatedItems: () => - state.listedInstance ? [{ metadata: { id: state.listedInstance } }] : [], - })), + list: vi.fn(async ({ labelSelector }: { labelSelector: string }) => { + const ids = + state.listInstances?.(labelSelector) ?? + (state.listedInstance ? [state.listedInstance] : []); + return { getPaginatedItems: () => ids.map((id) => ({ metadata: { id } })) }; + }), // Every delete waits for its case to answer it, so a release can be held at its delete while the // local teardown it started beside has long since refused. delete: vi.fn(async (instanceId: string) => { + state.deleteInstance(instanceId); if (state.autoDelete) return; let report!: () => void; const answered = new Promise((answeredNow) => { @@ -408,3 +417,118 @@ test('Limrun recovery carries a late labeled delete into the release result', as vi.useRealTimers(); } }); + +test('Limrun rental recovery records a matched instance before deleting it', async () => { + const runtime = createLimrunRuntime({ apiKey: 'lim_test_key' }, testDependencies()); + const lease = androidLease('rental-inherited'); + const recover = runtime.leaseLifecycle.recoverRental!; + const journaled = vi.fn(); + try { + const identity = { reconciliationKey: 'request-key' }; + await expect(recover(lease, identity, journaled)).resolves.toBe(false); + expect(state.deletes).toHaveLength(0); + state.listedInstance = 'exact-instance'; + const release = recover(lease, identity, journaled); + await vi.waitFor(() => expect(state.deletes).toHaveLength(1)); + expect(journaled).toHaveBeenCalledExactlyOnceWith('exact-instance'); + expect(state.deletes[0]?.instanceId).toBe('exact-instance'); + state.deletes[0]?.report(); + await expect(release).resolves.toBe(true); + + state.deletes.length = 0; + state.listedInstance = 'different-instance'; + const exact = recover(lease, { ...identity, instanceId: 'exact-instance' }, journaled); + await vi.waitFor(() => expect(state.deletes).toHaveLength(1)); + expect(state.deletes[0]?.instanceId).toBe('exact-instance'); + state.deletes[0]?.report(); + await expect(exact).resolves.toBe(true); + } finally { + state.deletes.forEach(({ report }) => report()); + state.deletes.length = 0; + state.listedInstance = undefined; + await runtime.shutdown(); + } +}); + +test.each([ + { result: 'empty', ids: [] }, + { result: 'ambiguous', ids: ['candidate-a', 'candidate-b'] }, +])('a journaled lost create stays unknown on $result keyed lookup', async ({ ids }) => { + const runtime = createLimrunRuntime({ apiKey: 'lim_test_key' }, testDependencies()); + const lease = androidLease('shared-lease-label'); + const beforeCreate = vi.fn(); + const rented = vi.fn(); + const list = vi.fn((selector: string) => + selector === 'provider=limrun,leaseId=shared-lease-label' ? ['older-rental'] : ids, + ); + state.autoDelete = true; + state.createError = new Error('create response lost'); + state.listInstances = list; + state.deleteInstance.mockClear(); + try { + const failed = await runtime.leaseLifecycle.allocate!(lease, { + rental: { beforeCreate, rented }, + }).catch((error: unknown) => error); + const key = state.createLabels?.rentalKey; + expect(key).toEqual(expect.any(String)); + expect(beforeCreate).toHaveBeenCalledExactlyOnceWith(key); + expect(list).toHaveBeenCalledExactlyOnceWith(`provider=limrun,rentalKey=${key}`); + expect(failed).toMatchObject({ + details: { reason: 'limrun_instance_delete_unconfirmed' }, + }); + expect(rented).not.toHaveBeenCalled(); + expect(state.deleteInstance).not.toHaveBeenCalled(); + + list.mockReturnValueOnce(['current-rental']); + await expect(runtime.leaseLifecycle.release!(lease)).resolves.toMatchObject({ + release: 'confirmed', + provider: { limrunInstanceId: 'current-rental' }, + }); + expect(list).toHaveBeenLastCalledWith(`provider=limrun,rentalKey=${key}`); + expect(rented).toHaveBeenCalledExactlyOnceWith('current-rental'); + expect(rented).toHaveBeenCalledBefore(state.deleteInstance); + expect(state.deleteInstance).toHaveBeenCalledExactlyOnceWith('current-rental'); + } finally { + state.listInstances = () => ['current-rental']; + try { + await runtime.shutdown(); + } finally { + state.listInstances = undefined; + state.createError = undefined; + state.autoDelete = false; + } + } +}); + +test('Limrun recovery tracks concurrent rentals sharing one public lease label separately', async () => { + const runtime = createLimrunRuntime({ apiKey: 'lim_test_key' }, testDependencies()); + const lease = androidLease('shared-lease-label'); + const recover = runtime.leaseLifecycle.recoverRental!; + const journaledA = vi.fn(); + const journaledB = vi.fn(); + const instancesBySelector = new Map([ + ['provider=limrun,rentalKey=key-a', ['instance-a']], + ['provider=limrun,rentalKey=key-b', ['instance-b']], + ]); + state.listInstances = (selector) => instancesBySelector.get(selector) ?? []; + state.autoDelete = true; + state.deleteInstance.mockClear(); + try { + await expect( + Promise.all([ + recover(lease, { reconciliationKey: 'key-a' }, journaledA), + recover(lease, { reconciliationKey: 'key-b' }, journaledB), + ]), + ).resolves.toEqual([true, true]); + expect(journaledA).toHaveBeenCalledExactlyOnceWith('instance-a'); + expect(journaledB).toHaveBeenCalledExactlyOnceWith('instance-b'); + expect(state.deleteInstance.mock.calls.map(([id]) => id).sort()).toEqual([ + 'instance-a', + 'instance-b', + ]); + } finally { + state.listInstances = undefined; + state.autoDelete = false; + await runtime.shutdown(); + } +}); diff --git a/packages/provider-limrun/src/lease-release.test.ts b/packages/provider-limrun/src/lease-release.test.ts index f09244614e..1814c24637 100644 --- a/packages/provider-limrun/src/lease-release.test.ts +++ b/packages/provider-limrun/src/lease-release.test.ts @@ -38,6 +38,7 @@ test('a create that answers late joins the delete its disposal already started', return { failure: undefined, cause: undefined }; }); const host: LimrunDisposalHost = { + findRentalInstance: async () => undefined, deleteInstance: deleteHost, endCapture: async () => undefined, }; @@ -83,6 +84,7 @@ test("a refused delete reports its own error as the refusal's cause", async () = await import('./lifecycle-budget.ts'); const refusal = new Error('Limrun refused to delete the instance'); const host: LimrunDisposalHost = { + findRentalInstance: async () => undefined, deleteInstance: async () => ({ failure: 'Limrun refused to delete the instance', cause: refusal, @@ -269,6 +271,7 @@ test('a take-refusal for an unconfirmed delete does not call the instance ended' test('a late create whose delete Limrun refused keeps disposal uncertain', async () => { await import('./lifecycle-budget.ts'); const host: LimrunDisposalHost = { + findRentalInstance: async () => undefined, deleteInstance: async () => ({ failure: 'Limrun refused to delete the instance', cause: undefined, @@ -307,6 +310,7 @@ test('a late create whose delete Limrun refused keeps disposal uncertain', async test('a capture end that spends its tunnel budget is still joined in time', async () => { await import('./lifecycle-budget.ts'); const host: LimrunDisposalHost = { + findRentalInstance: async () => undefined, deleteInstance: async () => ({ failure: undefined, cause: undefined }), // The tunnel answers at the very end of its own 20 s budget, then the record is written. endCapture: async () => { @@ -345,6 +349,7 @@ test('a rejected capture report preserves its error without changing confirmed d Promise.resolve({ status: 'failed', error: new Error('boot failed') }), ); const host: LimrunDisposalHost = { + findRentalInstance: async () => undefined, deleteInstance: async () => ({ failure: undefined, cause: undefined }), endCapture: async () => { throw refusal; @@ -363,6 +368,7 @@ test('an unanswered create does not make a confirmed instance delete uncertain', }); const owner = ownerWithRentedInstance(creation); const host: LimrunDisposalHost = { + findRentalInstance: async () => undefined, deleteInstance: async () => ({ failure: undefined, cause: undefined }), endCapture: async () => undefined, }; diff --git a/packages/provider-limrun/src/lease-release.ts b/packages/provider-limrun/src/lease-release.ts index aab41e07c5..d167dc0160 100644 --- a/packages/provider-limrun/src/lease-release.ts +++ b/packages/provider-limrun/src/lease-release.ts @@ -1,5 +1,5 @@ import type Limrun from '@limrun/api'; -import type { DeviceLease } from '@agent-device/contracts/device'; +import type { DeviceLease, ProviderRentalIdentity } from '@agent-device/contracts/device'; import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors'; import { cleanupLimrunAndroidAdbTunnel } from './android.ts'; import { CAPTURE_OPEN_BUDGET_MS } from './capture-lifecycle.ts'; @@ -62,13 +62,15 @@ const LOCAL_TEARDOWN_BUDGET_MS = 45_000; const CAPTURE_RECORD_BUDGET_MS = CAPTURE_OPEN_BUDGET_MS + 10_000; /** - * What a disposal may ask of the runtime that owns the lease, and nothing else: the delete of one instance, and - * the end of one lease's capture. Keeping the disposal to these two is what lets it end an owner without - * reaching back into the routes that allocate and read one, and without deciding when a lease is free again. + * Provider lookup, instance deletion and capture cleanup for a lease disposal. */ export type LimrunDisposalHost = Readonly<{ /** One instance delete: whether Limrun has the instance gone, and what refused it otherwise. */ deleteInstance(platform: LimrunPlatform, instanceId: string): Promise; + findRentalInstance( + platform: LimrunPlatform, + reconciliationKey: string, + ): Promise; /** Ends one lease's capture and answers with its record, for a runtime that has captured something. */ endCapture(owner: LimrunLeaseOwner): Promise; }>; @@ -96,7 +98,8 @@ export async function disposeLimrunLeaseOwner( // moment it was built — so a create that failed or refused its caller is disposed from those, exactly like // one that answered. const session = owner.session; - const instanceId = session?.instanceId ?? owner.rentedInstanceId; + const instanceId = + session?.instanceId ?? owner.rentedInstanceId ?? (await reconcileRental(host, owner)); if (instanceId === undefined) return await disposeUnrented(host, owner); // The capture's record is optional reporting, and local teardown can outlive its own steps: neither is // allowed to stand between this disposal and the delete that stops the instance from being billed, so both @@ -122,6 +125,19 @@ export async function disposeLimrunLeaseOwner( }; } +async function reconcileRental( + host: LimrunDisposalHost, + owner: LimrunLeaseOwner, +): Promise { + if (!owner.createSubmitted || !owner.rental) return undefined; + const { reconciliationKey, recordInstance } = owner.rental; + const instanceId = await host.findRentalInstance(owner.platform, reconciliationKey); + if (instanceId === undefined) return undefined; + recordInstance(instanceId); + owner.rentedInstanceId = instanceId; + return instanceId; +} + /** * What the joined capture record leaves to report: nothing, a refusal of the record itself, or a wait * that ran out. A refusal is reported as what it is, because a record that will never be written is not @@ -187,17 +203,18 @@ async function disposeUnansweredCreate( } /** - * Ends what a disposal holds when its create answered and no instance is named for the lease: nothing this - * runtime rented is running, so the lease can be given back. + * Ends the capture when no instance is known. A submitted journaled create stays unresolved until its + * rental can be identified. */ async function disposeUnrented( host: LimrunDisposalHost, owner: LimrunLeaseOwner, ): Promise { + const unresolvedRental = owner.createSubmitted && owner.rental; return { - cleanup: 'none', + cleanup: unresolvedRental ? 'uncertain' : 'none', instanceId: undefined, - failure: undefined, + failure: unresolvedRental ? 'Rental lookup did not identify one instance' : undefined, cause: undefined, capture: await awaitEndedCapture(host, owner), }; @@ -412,12 +429,22 @@ export async function releaseLimrunLease( }; } +export async function recoverLimrunRental( + limrun: Limrun | undefined, + lease: DeviceLease, + identity: ProviderRentalIdentity, + recordInstance: (instanceId: string) => void, +): Promise { + if (!identity.instanceId && !identity.reconciliationKey) return false; + return (await releaseLabeledInstances(limrun, lease, { identity, recordInstance })) !== undefined; +} + type LabeledRecovery = { - instanceIds: string[]; + lookup?: Promise; deletes: Map>; }; -const labeledRecoveries = new WeakMap>>(); +const labeledRecoveries = new WeakMap>(); /** * Ends every instance a lease's own labels name, for a lease this runtime no longer holds an owner for. @@ -429,24 +456,66 @@ const labeledRecoveries = new WeakMap void }, ): Promise { const platform = platformForLimrunLeaseBackend(lease.backend); if (!platform || !limrun) return undefined; - const byLease = labeledRecoveries.get(limrun) ?? new Map>(); - labeledRecoveries.set(limrun, byLease); - const lookup = - byLease.get(lease.leaseId) ?? findLabeledInstances(limrun, platform, lease.leaseId); - byLease.set(lease.leaseId, lookup); - const { instanceIds, deletes } = await lookup.catch((error: unknown) => { - if (byLease.get(lease.leaseId) === lookup) byLease.delete(lease.leaseId); - throw error; - }); + const { instanceId: exactId, reconciliationKey } = rental?.identity ?? {}; + const key = labeledRecoveryKey(platform, lease.leaseId, rental?.identity); + const byIdentity = labeledRecoveries.get(limrun) ?? new Map(); + labeledRecoveries.set(limrun, byIdentity); + const recovery: LabeledRecovery = byIdentity.get(key) ?? { deletes: new Map() }; + byIdentity.set(key, recovery); + let instanceIds: string[]; + if (exactId) { + instanceIds = [exactId]; + } else { + const lookup = (recovery.lookup ??= findReleaseInstances( + limrun, + platform, + lease, + reconciliationKey, + )); + instanceIds = await lookup.catch((error: unknown) => { + if (byIdentity.get(key) === recovery && recovery.deletes.size === 0) byIdentity.delete(key); + throw error; + }); + if (rental && instanceIds[0] !== undefined) rental.recordInstance(instanceIds[0]); + } + await deleteLabeledInstances(recovery.deletes, limrun, platform, lease.leaseId, instanceIds); + if (byIdentity.get(key) === recovery && (instanceIds.length > 0 || recovery.deletes.size === 0)) + byIdentity.delete(key); + if (instanceIds.length === 0) return undefined; + return { + limrunInstanceId: instanceIds[0], + limrunInstanceIds: instanceIds, + limrunInstanceCount: instanceIds.length, + }; +} + +function labeledRecoveryKey( + platform: LimrunPlatform, + leaseId: string, + identity?: ProviderRentalIdentity, +): string { + if (identity?.reconciliationKey) return `${platform}:rental:${identity.reconciliationKey}`; + if (identity?.instanceId) return `${platform}:instance:${identity.instanceId}`; + return `${platform}:lease:${leaseId}`; +} + +async function deleteLabeledInstances( + deletes: LabeledRecovery['deletes'], + limrun: Limrun, + platform: LimrunPlatform, + leaseId: string, + instanceIds: string[], +): Promise { const confirmed: string[] = []; for (const instanceId of instanceIds) { const deleted = await awaitLabeledDelete(deletes, limrun, platform, instanceId); if (deleted.failure !== undefined) { throwUnconfirmedDelete( - `Recovery could not confirm instance '${instanceId}' of lease '${lease.leaseId}' deleted`, + `Recovery could not confirm instance '${instanceId}' of lease '${leaseId}' deleted`, { limrunInstanceId: instanceId, limrunInstanceIds: instanceIds }, deleted.failure, recoveryHint(instanceIds, confirmed), @@ -455,13 +524,33 @@ async function releaseLabeledInstances( } confirmed.push(instanceId); } - if (byLease.get(lease.leaseId) === lookup) byLease.delete(lease.leaseId); - if (instanceIds.length === 0) return undefined; - return { - limrunInstanceId: instanceIds[0], - limrunInstanceIds: instanceIds, - limrunInstanceCount: instanceIds.length, - }; +} + +async function findReleaseInstances( + limrun: Limrun, + platform: LimrunPlatform, + lease: DeviceLease, + reconciliationKey: string | undefined, +): Promise { + if (!reconciliationKey) + return await findLabeledInstances(limrun, platform, `leaseId=${lease.leaseId}`); + const instanceId = await findLimrunRentalInstance(limrun, platform, reconciliationKey); + return instanceId === undefined ? [] : [instanceId]; +} + +export async function findLimrunRentalInstance( + limrun: Limrun | undefined, + platform: LimrunPlatform, + reconciliationKey: string, +): Promise { + if (!limrun) return undefined; + const instanceIds = await findLabeledInstances( + limrun, + platform, + `rentalKey=${reconciliationKey}`, + ); + // A one-attempt create can account for one instance. An empty list can race create. + return instanceIds.length === 1 ? instanceIds[0] : undefined; } async function awaitLabeledDelete( @@ -490,18 +579,15 @@ async function awaitLabeledDelete( async function findLabeledInstances( limrun: Limrun, platform: LimrunPlatform, - leaseId: string, -): Promise { - const labelSelector = `provider=${LIMRUN_PROVIDER},leaseId=${leaseId}`; + label: string, +): Promise { + const labelSelector = `provider=${LIMRUN_PROVIDER},${label}`; const instances = await fromLimrunOrgApi( platform === 'ios' ? limrun.iosInstances.list({ labelSelector }) : limrun.androidInstances.list({ labelSelector }), ); - return { - instanceIds: instances.getPaginatedItems().map((instance) => instance.metadata.id), - deletes: new Map(), - }; + return instances.getPaginatedItems().map((instance) => instance.metadata.id); } /** What the recovery refusal tells the operator to name to Limrun: the instance left, and those gone. */ diff --git a/packages/provider-limrun/src/plugin.test.ts b/packages/provider-limrun/src/plugin.test.ts index f9cfdcbfc0..f1a36b131c 100644 --- a/packages/provider-limrun/src/plugin.test.ts +++ b/packages/provider-limrun/src/plugin.test.ts @@ -32,6 +32,7 @@ vi.mock('./runtime.ts', () => ({ return { runtime: { provider: 'limrun', + prepareRentalRecovery: async () => {}, shutdown: async () => undefined, leaseLifecycle: {}, ownsDevice: () => false, diff --git a/packages/provider-limrun/src/plugin.ts b/packages/provider-limrun/src/plugin.ts index 50b64bdfb7..fae494c849 100644 --- a/packages/provider-limrun/src/plugin.ts +++ b/packages/provider-limrun/src/plugin.ts @@ -58,7 +58,7 @@ export function limrunPlugin(options: LimrunPluginOptions = {}): ProviderAgentDe module.createLimrunRuntimeDependencies(host), ), ]); - return register.createLimrunRuntime( + const registration = register.createLimrunRuntime( { ...credentials, ...(host.stateDir === undefined @@ -71,6 +71,8 @@ export function limrunPlugin(options: LimrunPluginOptions = {}): ProviderAgentDe dependencies, { includePlatformModule: true }, ); + await registration.runtime.prepareRentalRecovery(); + return registration; }, }, ], diff --git a/packages/provider-limrun/src/runtime-instance.test.ts b/packages/provider-limrun/src/runtime-instance.test.ts index 96e0aedd37..b65ee193c4 100644 --- a/packages/provider-limrun/src/runtime-instance.test.ts +++ b/packages/provider-limrun/src/runtime-instance.test.ts @@ -1,4 +1,7 @@ -import { expect, test } from 'vitest'; +import Limrun from '@limrun/api'; +import { expect, test, vi } from 'vitest'; +import { limrunPlugin } from './plugin.ts'; +import { stubLimrunRuntimeDependencies } from './runtime-dependencies.fixtures.ts'; import { resolveLimrunRuntimeInstance } from './runtime-instance.ts'; test('derives a stable opaque identity without exposing the API key', () => { @@ -46,3 +49,120 @@ test('keeps the durable digest of an account and of an attached instance', () => }), ).toBe('principal-5e4bdc0668a05c1c16f984e4655fc1d1a3bcd25b5965e3b9f3a40838121d5110'); }); + +test('rental recovery binds routing but ignores generated client and SDK telemetry', async () => { + const [provider] = limrunPlugin({ + createDependencies: (host) => ({ + ...stubLimrunRuntimeDependencies(), + clientVersion: host.clientVersion, + }), + }).contributes; + if (provider.kind !== 'provider') throw new Error('Expected the Limrun provider'); + const principal = async (env: Record, clientVersion = '1.0.0') => { + const setup = await provider.setup({ + env, + options: {}, + clientVersion, + diagnostics: { emit: () => {} }, + createError: (_code, message) => { + throw new Error(message); + }, + runHostCommand: async () => { + throw new Error('Expected no host command'); + }, + }); + if (!('runtime' in setup)) throw new Error('Expected a configured Limrun runtime'); + return setup.runtime.rentalRecoveryPrincipal; + }; + const buildRequest = Limrun.prototype.buildRequest; + let sdkVersion = 'sdk-1'; + const builtRequest = vi + .spyOn(Limrun.prototype, 'buildRequest') + .mockImplementation(async function (this: Limrun, ...args: Parameters) { + const built = await buildRequest.call(this, ...args); + built.req.headers.set('x-stainless-package-version', sdkVersion); + return built; + }); + vi.stubEnv('LIMRUN_BASE_URL', 'https://a.example.test'); + vi.stubEnv('LIMRUN_CUSTOM_HEADERS', undefined); + try { + const first = await principal({ LIMRUN_API_KEY: 'fixture-key', LIMRUN_IOS_MODEL: 'iphone' }); + expect(first).toMatch(/^principal-[a-f0-9]{64}$/); + expect( + (await principal({ + LIMRUN_API_KEY: 'fixture-key', + LIMRUN_CUSTOM_HEADERS: 'X-Host-Only: ignored', + })) === first, + ).toBe(true); + sdkVersion = 'sdk-2'; + expect((await principal({ LIMRUN_API_KEY: 'fixture-key' }, '2.0.0')) === first).toBe(true); + expect( + await principal({ + LIMRUN_API_KEY: 'fixture-key', + LIMRUN_IOS_MODEL: 'ipad', + LIMRUN_KEEP_ALIVE: '1', + }), + ).toBe(first); + expect(await principal({ LIMRUN_API_KEY: 'other-key' })).not.toBe(first); + + vi.stubEnv('LIMRUN_BASE_URL', 'https://b.example.test'); + expect(await principal({ LIMRUN_API_KEY: 'fixture-key' })).not.toBe(first); + vi.stubEnv('LIMRUN_BASE_URL', 'https://a.example.test'); + vi.stubEnv('LIMRUN_CUSTOM_HEADERS', 'Authorization: Bearer alternate-fixture-credential'); + expect(await principal({ LIMRUN_API_KEY: 'fixture-key' })).not.toBe(first); + vi.stubEnv('LIMRUN_CUSTOM_HEADERS', 'X-Account: account-a\nX-Route: region-a'); + const routed = await principal({ LIMRUN_API_KEY: 'fixture-key' }); + expect(routed).not.toBe(first); + vi.stubEnv('LIMRUN_CUSTOM_HEADERS', 'X-Route: region-a\nX-Account: account-a'); + expect(await principal({ LIMRUN_API_KEY: 'fixture-key' })).toBe(routed); + vi.stubEnv('LIMRUN_CUSTOM_HEADERS', 'X-Account: account-b\nX-Route: region-a'); + expect(await principal({ LIMRUN_API_KEY: 'fixture-key' })).not.toBe(routed); + vi.stubEnv('LIMRUN_CUSTOM_HEADERS', 'User-Agent: operator-route-a'); + const customAgent = await principal({ LIMRUN_API_KEY: 'fixture-key' }); + vi.stubEnv('LIMRUN_CUSTOM_HEADERS', 'User-Agent: operator-route-b'); + expect(await principal({ LIMRUN_API_KEY: 'fixture-key' })).not.toBe(customAgent); + expect( + await principal({ + LIM_IOS_INSTANCE_URL: 'https://attached.example.test', + LIM_IOS_INSTANCE_TOKEN: 'fixture-token', + }), + ).toBeUndefined(); + } finally { + builtRequest.mockRestore(); + vi.unstubAllEnvs(); + } +}); + +test.each(['SDK', 'host'] as const)( + 'keeps Limrun registered with a malformed %s header setting', + async (source) => { + const [provider] = limrunPlugin({ + createDependencies: stubLimrunRuntimeDependencies, + }).contributes; + if (provider.kind !== 'provider') throw new Error('Expected the Limrun provider'); + const customHeaders = 'Invalid Header Name: fixture'; + vi.stubEnv('LIMRUN_CUSTOM_HEADERS', source === 'SDK' ? customHeaders : undefined); + try { + const setup = await provider.setup({ + env: { + LIMRUN_API_KEY: 'fixture-key', + ...(source === 'host' ? { LIMRUN_CUSTOM_HEADERS: customHeaders } : {}), + }, + options: {}, + clientVersion: 'test-version', + diagnostics: { emit: () => {} }, + createError: (_code, message) => { + throw new Error(message); + }, + runHostCommand: async () => { + throw new Error('Expected no host command'); + }, + }); + if (!('runtime' in setup)) throw new Error('Expected a configured Limrun runtime'); + expect(setup.runtime.provider).toBe('limrun'); + expect(setup.runtime.rentalRecoveryPrincipal !== undefined).toBe(source === 'host'); + } finally { + vi.unstubAllEnvs(); + } + }, +); diff --git a/packages/provider-limrun/src/runtime-instance.ts b/packages/provider-limrun/src/runtime-instance.ts index f7292a681f..2e38a44c46 100644 --- a/packages/provider-limrun/src/runtime-instance.ts +++ b/packages/provider-limrun/src/runtime-instance.ts @@ -1,4 +1,5 @@ import { providerRuntimeInstance } from '@agent-device/contracts/platform-runtime'; +import type Limrun from '@limrun/api'; import type { LimrunIosModel } from './device.ts'; import type { LimrunInstanceAccess } from './instance-access.ts'; @@ -26,3 +27,35 @@ export function resolveLimrunRuntimeInstance(options: { ['attachedAndroid', options.instances?.android?.apiUrl], ]); } + +export async function resolveLimrunRentalRecoveryPrincipal( + client: Limrun, +): Promise { + // The SDK retains its constructor-resolved overrides here, including those from its environment. + // If a future SDK no longer exposes this shape, the runtime cannot prove its recovery scope. + const { isRecord } = await import('@agent-device/kernel/record'); + const options: unknown = Reflect.get(client, '_options'); + if (!isRecord(options)) return undefined; + const defaults = options.defaultHeaders; + if (defaults !== undefined && !isRecord(defaults)) return undefined; + const customHeaderNames = [ + ...new Set(Object.keys(defaults ?? {}).map((name) => name.toLowerCase())), + ] + .filter((name) => name !== 'authorization') + .sort(); + const { + req: { headers }, + } = await client.buildRequest({ method: 'get', path: '/' }); + const authorization = headers.get('authorization'); + if (!authorization) return undefined; + return providerRuntimeInstance('limrun', [ + ['authorization', authorization], + ['baseUrl', client.baseURL], + [ + 'customHeaders', + customHeaderNames.length === 0 + ? undefined + : JSON.stringify(customHeaderNames.map((name) => [name, headers.get(name)])), + ], + ]); +} diff --git a/packages/provider-limrun/src/runtime.ts b/packages/provider-limrun/src/runtime.ts index 1f40f53d8c..4d33293c86 100644 --- a/packages/provider-limrun/src/runtime.ts +++ b/packages/provider-limrun/src/runtime.ts @@ -1,5 +1,6 @@ import type { RuntimeOwnerRef } from '@agent-device/contracts/platform-runtime'; import Limrun from '@limrun/api'; +import { randomUUID } from 'node:crypto'; import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types'; import type { DeviceInventoryProvider, @@ -44,14 +45,16 @@ import type { LimrunAppLogDescriptor } from './app-log-descriptor.ts'; import type { LimrunAppLogReader } from './app-log-runtime.ts'; import { deleteLimrunInstance, - LIMRUN_CLIENT_ID, LIMRUN_ORG_CLIENT_LOGGING, limrunUserAgent, + readLimrunTerminationReason, requireLimrunOrgClient, } from './client-options.ts'; -import { resolveLimrunRuntimeInstance } from './runtime-instance.ts'; +import { + resolveLimrunRentalRecoveryPrincipal, + resolveLimrunRuntimeInstance, +} from './runtime-instance.ts'; import type { LimrunRequestOperationDrain } from './request-cancellation.ts'; -import type { LimrunAppAsset } from './app-catalog.ts'; import type { LimrunInstanceAccess } from './instance-access.ts'; import type { CloudArtifactProvider, @@ -77,7 +80,6 @@ const LIMRUN_RUNTIME_REASONS = { runtimeShutDown: { reason: 'limrun_runtime_shut_down' }, } as const satisfies ReasonTable<'limrun provider'>; -const HEARTBEAT_PROBE_BUDGET_MS = 2_000; const KEEP_ALIVE_INTERVAL_MS = 30_000; export type LimrunRuntimeOptions = { @@ -105,7 +107,9 @@ export type LimrunRuntime = ProviderDeviceRuntime & { }; export type LimrunRuntimeRegistration = Readonly<{ - runtime: LimrunRuntime; + runtime: LimrunRuntime & { + prepareRentalRecovery(): Promise; + }; platformModule: PlatformRuntimeProviderModule; }>; @@ -157,9 +161,15 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { private readonly options: LimrunRuntimeOptions; private readonly dependencies: LimrunRuntimeDependencies; readonly provider = LIMRUN_PROVIDER; + rentalRecoveryPrincipal?: string; readonly leaseLifecycle: LeaseLifecycleProvider = { allocate: async (lease, context) => await this.allocate(lease, context), + recoverRental: async (lease, identity, recordInstance) => { + if (lease.leaseProvider !== this.provider) return false; + const { recoverLimrunRental } = await import('./lease-release.ts'); + return await recoverLimrunRental(this.limrun, lease, identity, recordInstance); + }, heartbeat: async (lease, context) => await this.heartbeat(lease, context), release: async (lease) => { if (lease.leaseProvider !== this.provider) return undefined; @@ -217,6 +227,13 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { : undefined; } + async prepareRentalRecovery(): Promise { + if (!this.limrun) return; + this.rentalRecoveryPrincipal = await resolveLimrunRentalRecoveryPrincipal(this.limrun).catch( + () => undefined, + ); + } + /** * The capture lifecycle, made the first time a lease asks for a capture. The records a release settled live * there, so an artifacts read for a lease this runtime no longer holds goes through the same instance that @@ -547,6 +564,7 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { allocateLimrunAndroidSession, allocateLimrunIosSession, rejectRefusedLimrunProfileFields, + limrunRentalMetadata, resolvePreinstalledAppId, resolveRequestedLimrunAppAsset, } = await import('./session-allocation.ts'); @@ -569,10 +587,28 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { } const limrun = this.orgClient('Creating an instance'); const requestedAsset = await resolveRequestedLimrunAppAsset(limrun, platform, context); - const params = this.sessionAllocationParams(limrun, owner.lease, requestedAsset); + const rental = context?.rental; + const rentalKey = rental && randomUUID(); + const params = { + limrun, + lease: owner.lease, + metadata: limrunRentalMetadata(owner.lease, rentalKey), + region: this.options.region, + iosModel: this.options.iosModel, + app: requestedAsset, + dependencies: this.dependencies, + }; const rent = (instanceId: string): void => { owner.rentedInstanceId = instanceId; + rental?.rented(instanceId); }; + if (rental && rentalKey) { + rental.beforeCreate(rentalKey); + owner.rental = { + reconciliationKey: rentalKey, + recordInstance: (instanceId) => rental.rented(instanceId), + }; + } owner.createSubmitted = true; const session = platform === 'ios' @@ -680,6 +716,10 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { private readonly disposalHost: LimrunDisposalHost = { deleteInstance: async (platform, instanceId) => await this.deleteCreatedInstance(platform, instanceId), + findRentalInstance: async (platform, reconciliationKey) => { + const { findLimrunRentalInstance } = await import('./lease-release.ts'); + return await findLimrunRentalInstance(this.limrun, platform, reconciliationKey); + }, endCapture: async (owner) => await this.capturesInstance?.end(owner), }; @@ -756,27 +796,6 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { ); } - private sessionAllocationParams(limrun: Limrun, lease: DeviceLease, app?: LimrunAppAsset) { - return { - limrun, - lease, - metadata: { - displayName: `agent-device-${lease.tenantId}-${lease.runId}`, - labels: { - tenantId: lease.tenantId, - runId: lease.runId, - leaseId: lease.leaseId, - provider: lease.leaseProvider ?? LIMRUN_PROVIDER, - source: LIMRUN_CLIENT_ID, - }, - }, - region: this.options.region, - iosModel: this.options.iosModel, - app, - dependencies: this.dependencies, - }; - } - private async heartbeat( lease: DeviceLease, context?: LeaseLifecycleContext, @@ -961,40 +980,4 @@ function allocationRefusedAfterShutdown(lease: DeviceLease): never { ); } -/** - * The termination reason of a created instance whose connection dropped, or `undefined` when the - * instance is not terminated or the probe cannot tell. The budget only stops waiting, so the probe - * aborts its own GET when the budget expires. - */ -async function readLimrunTerminationReason( - limrun: Limrun, - session: Pick, - requestSignal: AbortSignal | undefined, -): Promise { - const expiry = new AbortController(); - const signal = requestSignal ? AbortSignal.any([requestSignal, expiry.signal]) : expiry.signal; - try { - const { awaitLimrunWithinBudget } = await import('./lifecycle-budget.ts'); - const request = - session.platform === 'ios' - ? limrun.iosInstances.get(session.instanceId, { signal }) - : limrun.androidInstances.get(session.instanceId, { signal }); - const answer = await awaitLimrunWithinBudget(request, HEARTBEAT_PROBE_BUDGET_MS); - if (!answer.ok) { - if ('expired' in answer) expiry.abort(); - return undefined; - } - if (answer.value.status.state !== 'terminated') return undefined; - // The termination reason is the account API's own text, and this request carries the account key in - // its header, so it goes through the same reader as an instance's error body before it is published. - const { safeTerminationReason } = await import('./error-text.ts'); - return safeTerminationReason(answer.value.status.terminationReason, [ - limrun.apiKey ?? undefined, - session.token, - ]); - } catch { - return undefined; - } -} - export type { LimrunRuntimeDependencies } from './runtime-dependencies.ts'; diff --git a/packages/provider-limrun/src/session-allocation.ts b/packages/provider-limrun/src/session-allocation.ts index 6bfae4a797..e7aec4f163 100644 --- a/packages/provider-limrun/src/session-allocation.ts +++ b/packages/provider-limrun/src/session-allocation.ts @@ -4,8 +4,13 @@ import { REMOTE_LEASE_IDLE_TTL_MS } from '@agent-device/contracts/lease-scope'; import { AppError } from '@agent-device/kernel/errors'; import { rejectRefusedProviderProfileFields } from '@agent-device/contracts/provider-profile-fields'; import { createLimrunAndroidSession, type LimrunAndroidSession } from './android.ts'; -import { fromLimrunOrgApi, LIMRUN_SINGLE_ATTEMPT } from './client-options.ts'; -import { buildLimrunDevice, LIMRUN_PROFILE_FIELDS, type LimrunIosModel } from './device.ts'; +import { fromLimrunOrgApi, LIMRUN_CLIENT_ID, LIMRUN_SINGLE_ATTEMPT } from './client-options.ts'; +import { + buildLimrunDevice, + LIMRUN_PROFILE_FIELDS, + LIMRUN_PROVIDER, + type LimrunIosModel, +} from './device.ts'; import { createLimrunIosSession, type LimrunIosSession } from './ios.ts'; import { assertLimrunUploadedAppAccess, @@ -41,6 +46,20 @@ type SessionAllocationParams = Readonly<{ dependencies: LimrunRuntimeDependencies; }>; +export function limrunRentalMetadata(lease: DeviceLease, rentalKey?: string) { + return { + displayName: `agent-device-${lease.tenantId}-${lease.runId}`, + labels: { + tenantId: lease.tenantId, + runId: lease.runId, + leaseId: lease.leaseId, + ...(rentalKey ? { rentalKey } : {}), + provider: lease.leaseProvider ?? LIMRUN_PROVIDER, + source: LIMRUN_CLIENT_ID, + }, + }; +} + export function rejectRefusedLimrunProfileFields(context?: LeaseLifecycleContext): void { rejectRefusedProviderProfileFields(context?.flags, LIMRUN_PROFILE_FIELDS); } diff --git a/packages/provider-revyl/src/device.ts b/packages/provider-revyl/src/device.ts index 1fbf851793..4112c8c921 100644 --- a/packages/provider-revyl/src/device.ts +++ b/packages/provider-revyl/src/device.ts @@ -75,17 +75,7 @@ export function isSupportedRevylRuntimeDevice(device: DeviceInfo): boolean { const REVYL_SESSION_ID_NAMESPACE = 'agent-device:revyl:session:v1'; /** - * The session id one lease's device is started and stopped under. - * - * Revyl's `start_device` takes a caller-generated `session_id` and uses it as the session's canonical - * identity, which is what Revyl's own clients do for a hosted session. Deriving it from the lease id - * therefore gives the runtime a durable identity for one lease: an expired-lease recovery in a process - * that never started the device can name the session it has to stop. - * - * It is a UUID because that is the field's declared format, and it is a hash rather than the lease id - * itself because two daemons that rent for the same account must derive the same id for the same lease - * and never collide across providers. Revyl's UUID regex accepts lowercase hex with the version and - * variant bits set. + * Derives the UUID for an unjournaled Revyl session or its legacy recovery record. */ export function revylSessionIdForLease(leaseId: string): string { const digest = createHash('sha256') diff --git a/packages/provider-revyl/src/index.test.ts b/packages/provider-revyl/src/index.test.ts index b16ef22b0b..c3eb3659a5 100644 --- a/packages/provider-revyl/src/index.test.ts +++ b/packages/provider-revyl/src/index.test.ts @@ -130,6 +130,7 @@ test('setup builds the runtime and owner from the credential options, not the en resolveRevylRuntimeInstance({ apiKey: 'option-key', backendUrl: fixture.backendUrl }), ); assert.equal(setup.runtime.provider, 'revyl'); + assert.equal(setup.runtime.rentalRecoveryPrincipal, setup.platformModule.owner.instance); await setup.runtime.shutdown(); }); diff --git a/packages/provider-revyl/src/revyl-backend.fixtures.ts b/packages/provider-revyl/src/revyl-backend.fixtures.ts index 8253eea449..b53e14f3f8 100644 --- a/packages/provider-revyl/src/revyl-backend.fixtures.ts +++ b/packages/provider-revyl/src/revyl-backend.fixtures.ts @@ -59,6 +59,7 @@ export type RevylFixtureBackend = Readonly<{ requests: RevylFixtureRequest[]; /** Paths in arrival order, each spelled `METHOD /path`, which is what the assertions read. */ paths(): string[]; + hasOpenSession(id: string): boolean; /** * Paths whose answer has been written back, in completion order. Receipt is the wrong moment for a * caller-side assertion: the client has not seen the action succeed yet, so a cancellation that lands @@ -267,6 +268,7 @@ export async function startRevylFixtureBackend( backendUrl, requests, paths: () => requests.map((request) => `${request.method} ${request.path}`), + hasOpenSession: (id) => openSessions.has(id), answeredPaths: () => [...answered], bodyFor: (action) => { const found = [...requests] diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index fb4b720a18..fb7a9c84df 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -672,9 +672,7 @@ export function revylFailureRefusedTheRequest(error: unknown): boolean { } /** - * Whether a failure is Revyl's "no such session" (a session route's 404 or 410). A stop that meets - * it has already been answered: the session is gone, which is released. Every cleanup path reads it - * the same way. + * Whether Revyl reported that a session is absent (a session route's 404 or 410). */ export function isRevylSessionGone(error: unknown): boolean { return ( diff --git a/packages/provider-revyl/src/revyl-session.ts b/packages/provider-revyl/src/revyl-session.ts index a0e127eb3c..c0e885f67c 100644 --- a/packages/provider-revyl/src/revyl-session.ts +++ b/packages/provider-revyl/src/revyl-session.ts @@ -2,7 +2,7 @@ import { AppError, REQUEST_CANCELED_REASONS, type ReasonTable } from '@agent-dev import { setTimeout as sleep } from 'node:timers/promises'; import type { DeviceLease } from '@agent-device/contracts/device'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { buildRevylDevice, revylSessionIdForLease, type RevylPlatform } from './device.ts'; +import { buildRevylDevice, type RevylPlatform } from './device.ts'; import { REVYL_START_DEVICE_TIMEOUT_MS, isRevylSessionGone, @@ -83,6 +83,7 @@ export type RevylSession = Readonly<{ }>; export type RevylStartRequestInput = Readonly<{ + sessionId: string; platform: RevylPlatform; appUrl: string | undefined; deviceModel: string | undefined; @@ -90,6 +91,7 @@ export type RevylStartRequestInput = Readonly<{ signal?: AbortSignal; /** Epoch-ms deadline the caller has for the whole allocation; it outranks the runtime's own. */ deadline?: number; + beforeCreate?: (sessionId: string) => void; /** Told the session once `start_device` answered with it, the first moment Revyl holds it. */ onRented?: (rented: RevylRentedSession) => void; }>; @@ -105,7 +107,11 @@ export type RevylCallerBudget = Readonly<{ signal?: AbortSignal; deadline?: numb * it. `sessionId` is always the id the backend was told, or the one it answered with, so the end always * addresses what Revyl actually holds. */ -export type RevylRentedSession = Readonly<{ runId?: string; sessionId: string }>; +export type RevylRentedSession = Readonly<{ + runId?: string; + sessionId: string; + state: 'submitted' | 'confirmed' | 'legacy'; +}>; /** * What one start amounted to. A start either hands over a ready device, or fails and says whether it left @@ -130,12 +136,15 @@ export async function startRevylSession( lease: DeviceLease, input: RevylStartRequestInput, ): Promise { - // The runtime issues the session id rather than reading it back, so a session this lease started - // can be ended from the lease alone — including from a process that never started it. - const sessionId = revylSessionIdForLease(lease.leaseId); + const { sessionId } = input; // Nothing has been sent yet, so nothing is rented: this caller is answered with its own cancellation and // the entry closes without asking Revyl for a session it never made. if (input.signal?.aborted) return { status: 'failed', error: startCanceled(input) }; + try { + input.beforeCreate?.(sessionId); + } catch (error) { + return { status: 'failed', error }; + } let started: RevylStartDeviceResponse; try { started = await submitRevylStart(client, input, sessionId); @@ -145,19 +154,59 @@ export async function startRevylSession( return { status: 'failed', error, - ...(startMayHaveRented(error) ? { rented: { sessionId } } : {}), + ...(startMayHaveRented(error) ? { rented: { sessionId, state: 'submitted' } } : {}), + }; + } + const accepted = readRevylStartResponse(started, sessionId, input); + if (accepted.status === 'failed') return accepted; + const { runId } = accepted; + // Revyl may have answered a run for a start whose caller has already hung up. The device is rented + // either way, so the answer still reports it as what is owed an end. + if (input.signal?.aborted) { + return { + status: 'failed', + rented: { runId, sessionId, state: 'confirmed' }, + error: startCanceled(input), }; } + const deadline = readinessDeadline(input); + try { + const health = await awaitRevylDeviceReady(client, runId, deadline, input); + return { + status: 'ready', + session: { + platform: input.platform, + runId, + sessionId, + screen: readRevylScreenSize(health), + dragDuration: health.supports_explicit_drag_duration === true, + preciseOrientation: health.supports_precise_orientation === true, + device: buildRevylDevice(input.platform, lease, runId), + client, + lease, + launchedApp: {}, + }, + }; + } catch (error) { + return { status: 'failed', error, rented: { runId, sessionId, state: 'confirmed' } }; + } +} + +function readRevylStartResponse( + started: RevylStartDeviceResponse, + sessionId: string, + input: RevylStartRequestInput, +): Extract | { status: 'accepted'; runId: string } { const runId = typeof started.workflow_run_id === 'string' ? started.workflow_run_id : undefined; - const echoed = typeof started.session_id === 'string' ? started.session_id : undefined; + const echoed = + typeof started.session_id === 'string' && started.session_id ? started.session_id : undefined; + if (runId || echoed) + input.onRented?.({ runId, sessionId: echoed ?? sessionId, state: 'confirmed' }); if (runId && echoed && echoed !== sessionId) { - // Every later stop addresses the session by the id the runtime issued, and an expired-lease - // recovery in another process derives that same id from the lease. A backend that kept its own - // identity therefore has to be refused, and the id it named is the only handle that still names - // the device: that is what `rented` reports, and what the failure names. + // If Revyl kept a different identity, its answer is the release target. return { status: 'failed', - rented: { runId, sessionId: echoed }, + rented: { runId, sessionId: echoed, state: 'confirmed' }, error: new AppError( 'COMMAND_FAILED', `Revyl started the device as session ${echoed} instead of ${sessionId}.`, @@ -175,7 +224,7 @@ export async function startRevylSession( // when it kept its own, so the end addresses the session the backend actually holds. return { status: 'failed', - rented: { sessionId: echoed ?? sessionId }, + rented: { sessionId: echoed ?? sessionId, state: echoed ? 'confirmed' : 'submitted' }, error: new AppError( 'COMMAND_FAILED', `Revyl did not start a ${input.platform} device: ${started.error ?? started.message ?? 'no workflow run was returned'}`, @@ -187,37 +236,7 @@ export async function startRevylSession( ), }; } - input.onRented?.({ runId, sessionId }); - // Revyl may have answered a run for a start whose caller has already hung up. The device is rented - // either way, so the answer still reports it as what is owed an end. - if (input.signal?.aborted) { - return { - status: 'failed', - rented: { runId, sessionId }, - error: startCanceled(input), - }; - } - const deadline = readinessDeadline(input); - try { - const health = await awaitRevylDeviceReady(client, runId, deadline, { ...input, sessionId }); - return { - status: 'ready', - session: { - platform: input.platform, - runId, - sessionId, - screen: readRevylScreenSize(health), - dragDuration: health.supports_explicit_drag_duration === true, - preciseOrientation: health.supports_precise_orientation === true, - device: buildRevylDevice(input.platform, lease, runId), - client, - lease, - launchedApp: {}, - }, - }; - } catch (error) { - return { status: 'failed', error, rented: { runId, sessionId } }; - } + return { status: 'accepted', runId }; } /** @@ -306,7 +325,8 @@ function startMayHaveRented(error: unknown): boolean { } /** A rented session whose `/stop` Revyl did not confirm, and why. */ -export type RevylUnconfirmedStop = RevylRentedSession & Readonly<{ failure: string }>; +export type RevylUnconfirmedStop = Pick & + Readonly<{ failure: string }>; /** * The one report for Revyl sessions that are still rented because their stop was not confirmed. The ids @@ -342,7 +362,6 @@ export function revylCleanupPending( } /** The start request once its session id is issued, which every readiness failure names. */ -type RevylReadyInput = RevylStartRequestInput & Readonly<{ sessionId: string }>; /** The readiness budget: the instant it runs out, and how much of it the caller was given. */ type RevylDeadline = Readonly<{ at: number; budgetMs: number }>; @@ -360,7 +379,7 @@ async function awaitRevylDeviceReady( client: RevylClient, runId: string, deadline: RevylDeadline, - input: RevylReadyInput, + input: RevylStartRequestInput, ): Promise { await untilRevylWorkerReady(client, runId, deadline, input); for (;;) { @@ -381,7 +400,7 @@ async function readWorkerHealth( client: RevylClient, runId: string, deadline: RevylDeadline, - input: RevylReadyInput, + input: RevylStartRequestInput, ): Promise { try { return await runWithinDeadline( @@ -403,7 +422,7 @@ async function readWorkerHealth( async function runWithinDeadline( poll: () => Promise, deadline: RevylDeadline, - input: RevylReadyInput, + input: RevylStartRequestInput, ): Promise { try { return await poll(); @@ -427,7 +446,7 @@ async function untilRevylWorkerReady( client: RevylClient, runId: string, deadline: RevylDeadline, - input: RevylReadyInput, + input: RevylStartRequestInput, ): Promise { for (;;) { requireTime(deadline, input); @@ -469,7 +488,7 @@ async function readWorkerConnection( client: RevylClient, runId: string, deadline: RevylDeadline, - input: RevylReadyInput, + input: RevylStartRequestInput, ): Promise { try { return await runWithinDeadline( @@ -485,7 +504,7 @@ async function readWorkerConnection( } /** Fails the moment the readiness budget is spent, whatever a poll that was already sent answers. */ -function requireTime(deadline: RevylDeadline, input: RevylReadyInput): void { +function requireTime(deadline: RevylDeadline, input: RevylStartRequestInput): void { if (Date.now() < deadline.at) return; // The budget is the caller's deadline when it is shorter, so the number named has to be the one that // actually ran out. @@ -493,7 +512,7 @@ function requireTime(deadline: RevylDeadline, input: RevylReadyInput): void { } /** The remaining readiness budget, so a poll that outlives it is canceled rather than awaited. */ -function pollSignal(deadline: RevylDeadline, input: RevylReadyInput): AbortSignal { +function pollSignal(deadline: RevylDeadline, input: RevylStartRequestInput): AbortSignal { const remaining = AbortSignal.timeout(Math.max(0, deadline.at - Date.now())); return input.signal === undefined ? remaining : AbortSignal.any([input.signal, remaining]); } diff --git a/packages/provider-revyl/src/runtime-rental-recovery.test.ts b/packages/provider-revyl/src/runtime-rental-recovery.test.ts new file mode 100644 index 0000000000..a69d330d34 --- /dev/null +++ b/packages/provider-revyl/src/runtime-rental-recovery.test.ts @@ -0,0 +1,126 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { revylSessionIdForLease } from './device.ts'; +import { revylLease, startRevylFixtureBackend } from './revyl-backend.fixtures.ts'; + +test('rental recovery accepts a gone session only after Revyl named it', async () => { + const requested = revylSessionIdForLease('lease-9'); + const exact = revylSessionIdForLease('different-lease'); + const requestedPath = `POST /api/v1/execution/device/sessions/${requested}/stop`; + const exactPath = `POST /api/v1/execution/device/sessions/${exact}/stop`; + const absent = { status: 404, body: { detail: 'no such session' } }; + const fixture = await startRevylFixtureBackend({ + respond: { [requestedPath]: absent, [exactPath]: absent }, + }); + try { + const runtime = fixture.createRuntime(); + const lease = revylLease('ios', 'rental-inherited'); + const recover = runtime.leaseLifecycle.recoverRental!; + assert.equal(await recover(lease, { reconciliationKey: requested }, () => {}), false); + assert.equal( + await recover(lease, { reconciliationKey: requested, instanceId: exact }, () => {}), + true, + ); + assert.deepEqual(fixture.paths(), [requestedPath, exactPath]); + } finally { + await fixture.close(); + } +}); + +test('Revyl renews a live rental with callbacks from a new allocation request', async () => { + const fixture = await startRevylFixtureBackend(); + const runtime = fixture.createRuntime(); + const lease = revylLease('ios'); + const submitted: string[] = []; + const rented: string[] = []; + const allocate = () => + runtime.leaseLifecycle.allocate?.(lease, { + rental: { + beforeCreate: (key) => submitted.push(key), + rented: (id) => rented.push(id), + }, + }); + try { + const first = await allocate(); + assert.ok(first); + assert.deepEqual(await allocate(), first); + assert.equal(submitted.length, 1); + assert.deepEqual(rented, submitted); + } finally { + await runtime.shutdown(); + await fixture.close(); + } +}); + +test('a stop for an earlier journaled create cannot end a replacement with the same lease ID', async () => { + const fixture = await startRevylFixtureBackend({ + sessionExistsOnceStarted: true, + startResponse: { success: true }, + }); + const runtime = fixture.createRuntime(); + const lease = revylLease('ios'); + const submitted: string[] = []; + const allocate = () => + runtime.leaseLifecycle.allocate!(lease, { + rental: { + beforeCreate: (key) => submitted.push(key), + rented: () => {}, + }, + }); + try { + const first = await allocate(); + assert.equal(first?.providerSessionId, submitted[0]); + assert.equal((await runtime.leaseLifecycle.release!(lease))?.release, 'confirmed'); + const second = await allocate(); + assert.equal(second?.providerSessionId, submitted[1]); + assert.notEqual(submitted[0], submitted[1]); + assert.equal(fixture.hasOpenSession(submitted[1]!), true); + assert.equal( + await runtime.leaseLifecycle.recoverRental!(lease, { instanceId: submitted[0] }, () => {}), + true, + ); + assert.equal(fixture.hasOpenSession(submitted[1]!), true); + assert.equal((await runtime.leaseLifecycle.release!(lease))?.release, 'confirmed'); + assert.equal(fixture.hasOpenSession(submitted[1]!), false); + assert.deepEqual( + fixture.paths().filter((route) => route.endsWith('/stop')), + [submitted[0], submitted[0], submitted[1]].map( + (key) => `POST /api/v1/execution/device/sessions/${key}/stop`, + ), + ); + } finally { + await runtime.shutdown(); + await fixture.close(); + } +}); + +test('live release stays unknown while an unacknowledged create is absent', async () => { + const fixture = await startRevylFixtureBackend({ + sessionExistsOnceStarted: true, + respond: { 'POST /api/v1/execution/start_device': { status: 503 } }, + }); + const runtime = fixture.createRuntime(); + const lease = revylLease('ios'); + const submitted: string[] = []; + const rented: string[] = []; + try { + await assert.rejects( + runtime.leaseLifecycle.allocate!(lease, { + rental: { + beforeCreate: (key) => submitted.push(key), + rented: (id) => rented.push(id), + }, + }), + ); + assert.equal(submitted.length, 1); + assert.deepEqual(rented, []); + assert.equal((await runtime.leaseLifecycle.release!(lease))?.release, 'unknown'); + const stopPath = `POST /api/v1/execution/device/sessions/${submitted[0]}/stop`; + assert.deepEqual( + fixture.paths().filter((route) => route.endsWith('/stop')), + [stopPath, stopPath], + ); + } finally { + await fixture.close(); + } +}); diff --git a/packages/provider-revyl/src/runtime.ts b/packages/provider-revyl/src/runtime.ts index 02fea3280a..fae9695482 100644 --- a/packages/provider-revyl/src/runtime.ts +++ b/packages/provider-revyl/src/runtime.ts @@ -1,3 +1,4 @@ +import { randomUUID } from 'node:crypto'; import type { DeviceInventoryProvider, DeviceLease, @@ -55,7 +56,10 @@ const REVYL_RUNTIME_REASONS = { } as const satisfies ReasonTable<'revyl provider'>; /** What one lease's start asks Revyl for, with the platform the lease was admitted for. */ -type RevylLeaseRequest = RevylStartRequest & Readonly<{ platform: RevylPlatform }>; +type RevylLeaseRequest = Readonly<{ + selection: RevylStartRequest & { platform: RevylPlatform }; + rental?: LeaseLifecycleContext['rental']; +}>; export type RevylRuntimeOptions = Readonly<{ apiKey: string; @@ -89,13 +93,7 @@ export type RevylRuntime = ProviderDeviceRuntime & { */ export function createRevylRuntime(options: RevylRuntimeOptions): RevylRuntimeRegistration { const runtime = new RevylRuntimeImplementation(options); - const owner = providerRuntimeOwner( - REVYL_PROVIDER, - resolveRevylRuntimeInstance({ - apiKey: options.apiKey, - ...(options.backendUrl === undefined ? {} : { backendUrl: options.backendUrl }), - }), - ); + const owner = providerRuntimeOwner(REVYL_PROVIDER, runtime.rentalRecoveryPrincipal); if (owner.kind !== 'provider-runtime') throw new TypeError('Invalid Revyl runtime owner'); return Object.freeze({ runtime, @@ -109,12 +107,27 @@ export function createRevylRuntime(options: RevylRuntimeOptions): RevylRuntimeRe class RevylRuntimeImplementation implements ProviderDeviceRuntime { private readonly options: RevylRuntimeOptions; + private readonly client: RevylClient; /** Every lease this runtime rents a device for, until Revyl confirms that device's `/stop`. */ private readonly leases: ProviderLeaseTable; readonly provider = REVYL_PROVIDER; + readonly rentalRecoveryPrincipal: string; readonly leaseLifecycle: LeaseLifecycleProvider = { allocate: (lease, context) => this.allocate(lease, context), + recoverRental: async (lease, { reconciliationKey, instanceId }) => { + requireRevylLease(lease, 'recover'); + const sessionId = instanceId ?? reconciliationKey; + if (!sessionId) return false; + try { + await stopRevylSession(this.client, sessionId); + return true; + } catch (error) { + if (!isRevylSessionGone(error)) throw error; + // A missing preassigned session may still be starting. + return instanceId !== undefined; + } + }, release: async (lease) => { if (lease.leaseProvider !== this.provider) return undefined; try { @@ -144,12 +157,13 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime { throw new TypeError('Revyl runtime requires an apiKey'); } this.options = options; - const client = createRevylClient({ + this.client = createRevylClient({ apiKey: options.apiKey, ...(options.backendUrl === undefined ? {} : { backendUrl: options.backendUrl }), clientVersion: options.clientVersion, }); - this.leases = createProviderLeaseTable(createRevylLeaseDriver(client)); + this.rentalRecoveryPrincipal = resolveRevylRuntimeInstance(options); + this.leases = createProviderLeaseTable(createRevylLeaseDriver(this.client)); } ownsDevice(device: DeviceInfo): boolean { @@ -200,7 +214,7 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime { // Before the join below: an allocation that reuses a live lease still carries flags of its own, // and Revyl reads none of them — whether it starts a device or joins one that is starting. rejectRefusedRevylProfileFields(context); - const request: RevylLeaseRequest = { + const selection = { ...resolveRevylStartRequest(context, { ...(this.options.deviceModel === undefined ? {} @@ -209,10 +223,15 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime { }), platform, }; - const session = await this.leases.allocate(lease, request, { - ...revylCallerBudget(context), - requireJoinable: (started) => requireSameRevylStartRequest(lease.leaseId, started, request), - }); + const session = await this.leases.allocate( + lease, + { selection, rental: context?.rental }, + { + ...revylCallerBudget(context), + requireJoinable: (started) => + requireSameRevylStartRequest(lease.leaseId, started.selection, selection), + }, + ); return allocationResult(session); } @@ -248,25 +267,40 @@ function createRevylLeaseDriver( ): ProviderLeaseDriver { /** The idle-clock refresh of each ready session, by session id, ended before its `/stop`. */ const keepAlives = new Map void>(); + const submittedKeys = new WeakMap(); return { startTimeoutMs: REVYL_ALLOCATION_TIMEOUT_MS, - // A session is created when `start_device` answers, not when it is sent, so the issued id is never - // published before that answer: a stop sent earlier reads as "already gone" and leaves the device. - start: async (lease, request, control) => { + // Wait for `start_device` to name its session before attempting live release. An earlier stop can + // report "already gone" while the start is still in progress. + start: async (lease, { selection, rental }, control) => { const started = await startRevylSession(client, lease, { - platform: request.platform, - appUrl: request.appUrl, - deviceModel: request.deviceModel, - osVersion: request.osVersion, + sessionId: rental ? randomUUID() : revylSessionIdForLease(lease.leaseId), + platform: selection.platform, + appUrl: selection.appUrl, + deviceModel: selection.deviceModel, + osVersion: selection.osVersion, // The table aborts this once no caller waits or the lease is ending; Revyl bounds `start_device` // and readiness with its own budgets, which `REVYL_ALLOCATION_TIMEOUT_MS` covers. signal: control.signal, - onRented: control.rented, + beforeCreate: + rental && + ((sessionId) => { + rental.beforeCreate(sessionId); + submittedKeys.set(lease, sessionId); + }), + onRented: (rented) => { + control.rented(rented); + rental?.rented(rented.sessionId); + }, }); if (started.status === 'failed') return started; const { runId, sessionId } = started.session; keepAlives.set(sessionId, keepRevylSessionAlive(client, runId)); - return { status: 'ready', session: started.session, handle: { runId, sessionId } }; + return { + status: 'ready', + session: started.session, + handle: { runId, sessionId, state: 'confirmed' }, + }; }, stop: async (handle) => { keepAlives.get(handle.sessionId)?.(); @@ -274,12 +308,14 @@ function createRevylLeaseDriver( try { await stopRevylSession(client, handle.sessionId); } catch (error) { - // Revyl answers a session it no longer has as gone: that device is not rented. - if (!isRevylSessionGone(error)) throw error; + if (handle.state === 'submitted' || !isRevylSessionGone(error)) throw error; } }, handleKey: (handle) => handle.sessionId, - findByLease: async (lease) => ({ sessionId: revylSessionIdForLease(lease.leaseId) }), + findByLease: async (lease) => ({ + sessionId: revylSessionIdForLease(lease.leaseId), + state: 'legacy', + }), shuttingDown: (lease) => shuttingDownDuring(lease.leaseId, 'allocate'), releasing: (lease) => new AppError('COMMAND_FAILED', `Revyl lease ${lease.leaseId} is being released.`, { @@ -292,7 +328,7 @@ function createRevylLeaseDriver( revylLeasePlatform(lease), caller, budgetMs, - rented?.sessionId ?? revylSessionIdForLease(lease.leaseId), + rented?.sessionId ?? submittedKeys.get(lease) ?? revylSessionIdForLease(lease.leaseId), ), cleanupPending: (unconfirmed, scope, cause) => revylCleanupPending( diff --git a/packages/provider-webdriver/src/runtime-session.ts b/packages/provider-webdriver/src/runtime-session.ts index deaa1c01cb..b211acb434 100644 --- a/packages/provider-webdriver/src/runtime-session.ts +++ b/packages/provider-webdriver/src/runtime-session.ts @@ -329,6 +329,7 @@ export class WebDriverSessionManager { requestPolicy: this.options.requestPolicy, }); const session = await this.createSessionWithPreparedCleanup(client, prepared, lease, req); + req?.rental?.rented(prepared.providerSessionId ?? session.sessionId); const device = this.deviceForLease(lease, prepared, session.capabilities); const capabilities = createCloudWebDriverCapabilities({ provider: this.options.provider, diff --git a/src/__tests__/lease-provider-profile-fields.test.ts b/src/__tests__/lease-provider-profile-fields.test.ts index b953bb25a0..81431fcaaa 100644 --- a/src/__tests__/lease-provider-profile-fields.test.ts +++ b/src/__tests__/lease-provider-profile-fields.test.ts @@ -26,7 +26,13 @@ const limrunInstances = vi.hoisted(() => ({ vi.mock('@limrun/api', () => ({ default: class MockLimrun { + readonly baseURL = 'https://limrun.example.test'; + readonly _options = {}; readonly iosInstances = { create: limrunInstances.iosCreate }; + + async buildRequest() { + return { req: { headers: new Headers({ authorization: 'Bearer fixture-account' }) } }; + } }, })); diff --git a/src/daemon-composition.ts b/src/daemon-composition.ts index 85bef79f8d..efaca11753 100644 --- a/src/daemon-composition.ts +++ b/src/daemon-composition.ts @@ -194,6 +194,13 @@ export async function composeDaemonRuntimeDeps( providerRuntimeIds: providerRuntimeProviders.providerRuntimeIds, recoverExpiredLease: providerRuntimeProviders.recoverExpiredLease, recoverableProviderIds: providerRuntimeProviders.recoverableProviderIds, + providerRentalPolicy: (provider: string) => { + const runtime = providerDeviceRuntimes.find((runtime) => runtime.provider === provider); + return { + rentalRecoveryPrincipal: runtime?.rentalRecoveryPrincipal, + legacyRecovery: !!runtime?.recoverExpiredLease && !runtime.leaseLifecycle.recoverRental, + }; + }, deviceRuntimeGateway, platformResourceCleanup: createPlatformResourceCleanup(host, web), claimRecoveryGateway: createClaimRecoveryGatewayFor(host, platforms), diff --git a/src/daemon-provider-rental-restart.fixtures.ts b/src/daemon-provider-rental-restart.fixtures.ts new file mode 100644 index 0000000000..a44ba3ee56 --- /dev/null +++ b/src/daemon-provider-rental-restart.fixtures.ts @@ -0,0 +1,118 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { startDaemonRuntime } from '@agent-device/daemon'; +import { captureHostEnvironment } from '@agent-device/host-kit/process'; +import { createDaemonRuntimeDeps } from './daemon-composition.ts'; + +export const rentalRestartFixturePath = new URL(import.meta.url); +export const fakeRentalKey = 'fake-request-1'; +export const fakeInstanceId = 'fake-instance-1'; +export const interruptionExitCode = 71; + +export function rentalDaemonEnv(stateDir: string): NodeJS.ProcessEnv { + return { + PATH: process.env.PATH, + TMPDIR: process.env.TMPDIR, + AGENT_DEVICE_HOME: stateDir, + AGENT_DEVICE_STATE_DIR: stateDir, + AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0', + AGENT_DEVICE_DAEMON_SERVER_MODE: 'socket', + }; +} + +export async function startRentalDaemon( + stateDir: string, + phase: string, + reportRecovery: (result: unknown) => void, + overrides?: Pick< + Partial>>, + 'leaseLifecycleProvider' | 'recoverExpiredLease' | 'providerRentalPolicy' + >, +) { + const otherPrincipal = phase === 'recover-other-principal'; + const fakeProviderState = path.join( + stateDir, + otherPrincipal ? 'other-account-instance' : 'fake-provider-instance', + ); + const runtime = await startDaemonRuntime({ + host: captureHostEnvironment({ env: rentalDaemonEnv(stateDir), cwd: process.cwd }), + composeDeps: async (input) => { + const deps = await createDaemonRuntimeDeps(input); + return { + ...deps, + providerRentalPolicy: () => ({ + rentalRecoveryPrincipal: otherPrincipal ? 'other-account' : 'original-account', + legacyRecovery: false, + }), + providerRuntimeIds: ['limrun'], + recoverableProviderIds: ['limrun'], + recoverExpiredLease: async () => { + fs.rmSync(fakeProviderState, { force: true }); + }, + leaseLifecycleProvider: { + allocate: async (_lease, context) => { + if (phase === 'before-key') process.exit(interruptionExitCode); + context?.rental?.beforeCreate(fakeRentalKey); + if (phase === 'before-create' || phase === 'unknown') + process.exit(interruptionExitCode); + fs.writeFileSync(fakeProviderState, fakeInstanceId); + if (phase === 'after-create') process.exit(interruptionExitCode); + context?.rental?.rented(fakeInstanceId); + if (phase === 'after-identity') process.exit(interruptionExitCode); + return { providerSessionId: fakeInstanceId }; + }, + release: async () => { + if (phase === 'during-release') process.exit(interruptionExitCode); + fs.rmSync(fakeProviderState, { force: true }); + if (phase === 'after-delete') process.exit(interruptionExitCode); + return { release: 'confirmed' }; + }, + recoverRental: async (_lease, identity, recordInstance) => { + if (phase === 'recover-unknown') { + reportRecovery({ recovery: identity, outcome: 'unknown' }); + return false; + } + const found = fs.existsSync(fakeProviderState) + ? fs.readFileSync(fakeProviderState, 'utf8') + : undefined; + if (identity.instanceId === undefined && identity.reconciliationKey !== fakeRentalKey) + throw new Error('Recovery did not present the provider reconciliation key.'); + if (found !== undefined) { + const instanceId = identity.instanceId ?? found; + if (instanceId !== found) throw new Error('Recovery targeted a different rental.'); + recordInstance(instanceId); + // The fake refuses to execute a delete if the daemon has not recorded its exact target. + const journal = fs.readFileSync(path.join(stateDir, 'provider-rentals.json'), 'utf8'); + if (!journal.includes(instanceId)) + throw new Error('Exact release target is missing.'); + fs.rmSync(fakeProviderState); + } + reportRecovery({ recovery: identity, outcome: found ?? 'absent' }); + return true; + }, + }, + ...overrides, + }; + }, + stderr: { write: () => {} }, + stdout: { write: () => {} }, + }); + if (!runtime?.socketPort) throw new Error('Rental restart fixture did not open a socket.'); + return { runtime, port: runtime.socketPort, token: runtime.token }; +} + +if (process.send && process.argv[2] === 'run-rental-restart-fixture') { + const [, , , stateDir, phase] = process.argv; + if (!stateDir || !phase) + throw new Error('Rental restart fixture needs a state directory and phase.'); + const { runtime, port, token } = await startRentalDaemon(stateDir, phase, (result) => + process.send?.(result), + ); + process.on('disconnect', () => process.exit(0)); + process.on('message', async (message) => { + if (message !== 'close') return; + await runtime.close(); + process.disconnect?.(); + }); + process.send({ port, token }); +} diff --git a/src/daemon-provider-rental-restart.test.ts b/src/daemon-provider-rental-restart.test.ts new file mode 100644 index 0000000000..e1e2fa2fb7 --- /dev/null +++ b/src/daemon-provider-rental-restart.test.ts @@ -0,0 +1,471 @@ +import { fork } from 'node:child_process'; +import { once } from 'node:events'; +import fs from 'node:fs'; +import net from 'node:net'; +import path from 'node:path'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { startDaemonRuntime } from '@agent-device/daemon'; +import { captureHostEnvironment } from '@agent-device/host-kit/process'; +import { mkdtempForTestSync, selectPlugin } from '@agent-device/test-kit'; +import { createDaemonRuntimeDeps } from './daemon-composition.ts'; +import { expect, test, vi } from 'vitest'; +import { + fakeInstanceId, + fakeRentalKey, + interruptionExitCode, + rentalDaemonEnv, + rentalRestartFixturePath, + startRentalDaemon, +} from './daemon-provider-rental-restart.fixtures.ts'; + +const scope = { + leaseId: '1234567890abcdef1234567890abcdef', + tenantId: 'tenant-a', + runId: 'run-a', + leaseBackend: 'ios-simulator', + leaseProvider: 'limrun', + deviceKey: 'paid-device-a', +}; + +type Ready = { port: number; token: string }; + +async function send(ready: Ready, command: string, meta: object): Promise { + const { port, token } = ready; + return await new Promise((resolve, reject) => { + const socket = net.connect(port, '127.0.0.1', () => { + socket.write( + JSON.stringify({ token, command, session: 'test', positionals: [], meta }) + '\n', + ); + }); + let response = ''; + socket.setEncoding('utf8'); + socket.on('data', (chunk: string) => { + response += chunk; + if (!response.includes('\n')) return; + socket.destroy(); + resolve(JSON.parse(response) as DaemonResponse); + }); + socket.on('error', reject); + socket.on('close', () => reject(new Error('Daemon closed before replying.'))); + }); +} + +function startCrashingDaemon(stateDir: string, phase: string) { + const child = fork(rentalRestartFixturePath, ['run-rental-restart-fixture', stateDir, phase], { + execArgv: ['--experimental-strip-types'], + env: rentalDaemonEnv(stateDir), + stdio: ['ignore', 'ignore', 'inherit', 'ipc'], + }); + const exited = once(child, 'exit').then(([code]) => code); + const ready = new Promise((resolve, reject) => { + child.on('message', (message: Ready) => resolve(message)); + void exited.then( + (code) => reject(new Error(`Fixture exited before readiness (${code}).`)), + reject, + ); + }); + + return { + exited, + request: async (command: string) => await send(await ready, command, scope), + close: async () => { + if (child.connected) child.send('close'); + await exited; + }, + }; +} + +async function restartDaemon(stateDir: string, phase: string) { + const recovery: unknown[] = []; + const daemon = await startRentalDaemon(stateDir, phase, (result) => recovery.push(result)); + return { + recovery, + request: (command: string, meta: object) => send(daemon, command, meta), + close: () => daemon.runtime.close(), + }; +} + +test.each([ + ['before-create', undefined, 'absent'], + ['after-create', undefined, fakeInstanceId], + ['after-identity', fakeInstanceId, fakeInstanceId], + ['during-release', fakeInstanceId, fakeInstanceId], + ['after-delete', fakeInstanceId, 'absent'], +])('recovers a rental after daemon exit %s', async (phase, instanceId, outcome) => { + const stateDir = mkdtempForTestSync('agent-device-rental-restart-'); + const crashing = startCrashingDaemon(stateDir, phase); + try { + const crashOnRelease = phase === 'during-release' || phase === 'after-delete'; + if (crashOnRelease) expect((await crashing.request('lease_allocate')).ok).toBe(true); + const command = crashOnRelease ? 'lease_release' : 'lease_allocate'; + await expect(crashing.request(command)).rejects.toThrow('Daemon closed before replying'); + expect(await crashing.exited).toBe(interruptionExitCode); + } finally { + await crashing.close(); + } + const journal = fs.readFileSync(path.join(stateDir, 'provider-rentals.json'), 'utf8'); + expect(journal).not.toContain(scope.leaseId); + const recovery = { reconciliationKey: fakeRentalKey, ...(instanceId ? { instanceId } : {}) }; + expect(JSON.parse(journal).rentals).toMatchObject([ + { + lease: { deviceKey: scope.deviceKey, tenantId: scope.tenantId, runId: scope.runId }, + releaseOnRestart: recovery, + }, + ]); + + const restarted = await restartDaemon(stateDir, 'recover'); + try { + const successor = await restarted.request('lease_allocate', { ...scope, leaseId: undefined }); + expect(successor.ok).toBe(true); + expect(restarted.recovery).toEqual([{ recovery, outcome }]); + } finally { + await restarted.close(); + } +}); + +test.each([ + ['unknown', 'recover-unknown'], + ['before-key', 'recover-unknown'], + ['after-identity', 'recover-other-principal'], +])( + 'unconfirmed release stays fenced across daemon registrations (%s)', + async (phase, recoveryPhase) => { + const stateDir = mkdtempForTestSync('agent-device-rental-unknown-'); + const crashing = startCrashingDaemon(stateDir, phase); + try { + await expect(crashing.request('lease_allocate')).rejects.toThrow( + 'Daemon closed before replying', + ); + expect(await crashing.exited).toBe(interruptionExitCode); + } finally { + await crashing.close(); + } + + for (let restart = 0; restart < 2; restart++) { + const daemon = await restartDaemon(stateDir, recoveryPhase); + try { + const blocked = await daemon.request('lease_allocate', { + ...scope, + leaseId: undefined, + tenantId: 'tenant-b', + runId: 'different-run', + }); + expect(blocked).toMatchObject({ + ok: false, + error: { + code: 'DEVICE_IN_USE', + details: { reason: 'DEVICE_LEASE_BUSY', releaseStatus: 'unknown' }, + }, + }); + const unrelated = await daemon.request('lease_allocate', { + ...scope, + deviceKey: 'another-device', + leaseId: undefined, + }); + expect(unrelated).toMatchObject({ ok: true }); + expect(daemon.recovery[0]).toEqual( + phase === 'unknown' + ? { recovery: { reconciliationKey: fakeRentalKey }, outcome: 'unknown' } + : undefined, + ); + } finally { + await daemon.close(); + } + } + }, +); + +test('a legacy recovery completing after shutdown leaves the pending record for the next daemon', async () => { + const stateDir = mkdtempForTestSync('agent-device-rental-handoff-'); + const pendingPath = path.join(stateDir, 'expired-provider-leases.json'); + const now = Date.now(); + const lease = { + ...scope, + backend: scope.leaseBackend, + createdAt: now, + heartbeatAt: now, + expiresAt: now, + }; + const record = JSON.stringify({ version: 1, leases: [lease] }); + fs.writeFileSync(pendingPath, record); + let finishStop!: () => void; + const oldStop = new Promise((resolve) => { + finishStop = resolve; + }); + let attempts = 0; + const daemon = await startRentalDaemon(stateDir, 'recover', () => {}, { + recoverExpiredLease: async () => { + if (++attempts === 1) throw new Error('Release temporarily unavailable.'); + await oldStop; + }, + }); + try { + const report = await daemon.runtime.close(); + expect(report.providerReleases.unknown).toContain(scope.leaseId); + const successor = await startRentalDaemon(stateDir, 'recover', () => {}, { + recoverExpiredLease: async () => { + throw new Error('Release temporarily unavailable.'); + }, + }); + try { + finishStop(); + await new Promise((resolve) => setImmediate(resolve)); + expect(fs.existsSync(pendingPath)).toBe(true); + expect(fs.readFileSync(pendingPath, 'utf8')).toBe(record); + } finally { + await successor.runtime.close(); + } + } finally { + finishStop(); + await daemon.runtime.close(); + } +}); + +test('failed rental journal retirement fences overlapping allocations and retries without another stop', async () => { + const stateDir = mkdtempForTestSync('agent-device-rental-retirement-'); + const journalPath = path.join(stateDir, 'provider-rentals.json'); + const stop = vi.fn(async () => ({ release: 'confirmed' as const })); + const legacyStop = vi.fn(async () => {}); + const daemon = await startRentalDaemon(stateDir, 'recover', () => {}, { + recoverExpiredLease: legacyStop, + leaseLifecycleProvider: { + allocate: async (_lease, context) => { + context?.rental?.beforeCreate(fakeRentalKey); + context?.rental?.rented(fakeInstanceId); + return { providerSessionId: fakeInstanceId }; + }, + release: stop, + }, + }); + const next = { ...scope, leaseId: undefined, tenantId: 'tenant-b', runId: 'run-b' }; + const rename = fs.renameSync; + const failure = vi.spyOn(fs, 'renameSync'); + try { + expect(await send(daemon, 'lease_allocate', scope)).toMatchObject({ ok: true }); + failure.mockImplementation((from, to) => { + if (to === journalPath) throw new Error('Journal publication unavailable.'); + rename(from, to); + }); + expect(await send(daemon, 'lease_release', scope)).toMatchObject({ + ok: true, + data: { released: false }, + }); + expect(await send(daemon, 'lease_allocate', next)).toMatchObject({ + ok: false, + error: { + code: 'DEVICE_IN_USE', + details: { reason: 'provider-rental-retirement-pending' }, + }, + }); + expect(JSON.parse(fs.readFileSync(journalPath, 'utf8')).rentals).toHaveLength(1); + failure.mockRestore(); + await vi.waitFor( + () => { + expect(JSON.parse(fs.readFileSync(journalPath, 'utf8')).rentals).toEqual([]); + }, + { timeout: 4_000 }, + ); + expect(stop).toHaveBeenCalledTimes(1); + expect(legacyStop).not.toHaveBeenCalled(); + expect(await send(daemon, 'lease_allocate', next)).toMatchObject({ ok: true }); + } finally { + failure.mockRestore(); + await daemon.runtime.close(); + } +}); + +test('a live provider lease ID with a different scope is already in use', async () => { + const stateDir = mkdtempForTestSync('agent-device-rental-duplicate-'); + const daemon = await startRentalDaemon(stateDir, 'recover', () => {}); + try { + expect(await send(daemon, 'lease_allocate', scope)).toMatchObject({ ok: true }); + expect( + await send(daemon, 'lease_allocate', { ...scope, tenantId: 'tenant-b', deviceKey: 'other' }), + ).toMatchObject({ + ok: false, + error: { code: 'INVALID_ARGS', details: { reason: 'LEASE_ID_IN_USE' } }, + }); + } finally { + await daemon.runtime.close(); + } +}); + +test.each(['recoverRental', 'recoverExpiredLease'] as const)( + 'production composition requires the same configured account and origin for %s', + async (hook) => { + const stateDir = mkdtempForTestSync('agent-device-rental-plugin-principal-'); + const name = '@example/rental-recovery'; + const provider = 'rental-recovery'; + const journal = path.join(stateDir, 'provider-rentals.json'); + const calls = path.join(stateDir, 'recovery-calls'); + const configPath = path.join(stateDir, 'config.json'); + const options = { account: 'fixture-account', origin: 'https://a.example.test', calls }; + const principal = 'fixture-account@https://a.example.test'; + const legacy = hook === 'recoverExpiredLease'; + selectPlugin( + stateDir, + name, + String.raw`import fs from 'node:fs'; + export default ({ account, origin, calls, allowRecovery }) => ({ + apiVersion: 3, + contributes: [{ + kind: 'provider', provider: "${provider}", credentials: { variables: [] }, + setup: () => { + const recover = (lease) => { + if (!allowRecovery) throw new Error('Recovery is unavailable before restart'); + fs.appendFileSync(calls, JSON.stringify({ account, origin, leaseId: lease.leaseId }) + '\n'); + return true; + }; + return { + runtime: { + provider: "${provider}", + rentalRecoveryPrincipal: account ? account + '@' + origin : undefined, + leaseLifecycle: { + allocate: async (_lease, { rental }) => { + rental.beforeCreate('fixture-key'); + rental.rented('fixture-instance'); + return {}; + }, + release: async () => ({ release: 'unknown' }), + ${legacy ? '' : 'recoverRental: async (lease) => recover(lease),'} + }, + ${legacy ? 'recoverExpiredLease: async (lease) => { recover(lease); },' : ''} + ownsDevice: () => false, + getInteractor: () => undefined, + deviceInventoryProvider: async () => [], + shutdown: async () => {}, + }, + platformModule: { + owner: { kind: 'provider-runtime', provider: "${provider}", instance: 'android' }, + loadRuntime: async () => { throw new Error('No device access expected'); }, + }, + }; + }, + }], + });`, + { selectionOptions: options }, + ); + const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); + const start = async () => { + const runtime = await startDaemonRuntime({ + host: captureHostEnvironment({ env: rentalDaemonEnv(stateDir), cwd: process.cwd }), + composeDeps: createDaemonRuntimeDeps, + stderr: { write: () => {} }, + stdout: { write: () => {} }, + }); + if (!runtime?.socketPort) throw new Error('Rental plugin daemon did not open a socket.'); + return { runtime, port: runtime.socketPort, token: runtime.token }; + }; + const request = { ...scope, leaseProvider: provider }; + const original = await start(); + try { + expect(await send(original, 'lease_allocate', request)).toMatchObject({ ok: true }); + } finally { + await original.runtime.close(); + } + + const recorded = fs.readFileSync(journal, 'utf8'); + expect(fs.existsSync(calls)).toBe(false); + const withoutPrincipal = JSON.parse(recorded); + delete withoutPrincipal.rentals[0].rentalRecoveryPrincipal; + const unprovenRecord = JSON.stringify(withoutPrincipal); + for (const [changed, contents] of [ + [{ ...options, origin: 'https://b.example.test' }, recorded], + [{ ...options, account: 'other-fixture-account' }, recorded], + [{ ...options, account: undefined }, recorded], + [options, unprovenRecord], + [{ ...options, account: undefined }, unprovenRecord], + ] as const) { + config.plugins[name].options = { ...changed, allowRecovery: true }; + fs.writeFileSync(journal, contents); + fs.writeFileSync(configPath, JSON.stringify(config)); + const successor = await start(); + try { + expect(fs.existsSync(calls)).toBe(false); + expect( + await send(successor, 'lease_allocate', { ...request, leaseId: undefined }), + ).toMatchObject({ + ok: false, + error: { code: 'DEVICE_IN_USE', details: { releaseStatus: 'unknown' } }, + }); + expect(fs.readFileSync(journal, 'utf8')).toBe(contents); + } finally { + await successor.runtime.close(); + } + } + + const entry = JSON.parse(recorded).rentals[0]; + expect(entry.rentalRecoveryPrincipal).toBe(principal); + expect(entry.legacyLeaseId).toBe(legacy ? scope.leaseId : undefined); + config.plugins[name].options = { ...options, allowRecovery: true }; + fs.writeFileSync(journal, recorded); + fs.writeFileSync(configPath, JSON.stringify(config)); + const successor = await start(); + try { + const recovery = { + account: options.account, + origin: options.origin, + leaseId: legacy ? scope.leaseId : entry.lease.leaseId, + }; + expect(fs.readFileSync(calls, 'utf8')).toBe(`${JSON.stringify(recovery)}\n`); + expect(JSON.parse(fs.readFileSync(journal, 'utf8')).rentals).toHaveLength(0); + } finally { + await successor.runtime.close(); + } + }, +); + +test.each(['live', 'legacy'] as const)( + 'an exact ID write failure blocks allocation and retries through %s release', + async (releasePath) => { + const stateDir = mkdtempForTestSync('agent-device-rental-record-instance-'); + const journalPath = path.join(stateDir, 'provider-rentals.json'); + const stop = vi.fn(async () => ({ release: 'unknown' as const })); + const legacy = releasePath === 'legacy'; + const legacyStop = vi.fn(async () => { + throw new Error('Legacy release is unavailable.'); + }); + const daemon = await startRentalDaemon(stateDir, 'recover', () => {}, { + providerRentalPolicy: () => ({ legacyRecovery: legacy }), + ...(legacy ? { recoverExpiredLease: legacyStop } : {}), + leaseLifecycleProvider: { + allocate: async (_lease, context) => { + context?.rental?.beforeCreate(fakeRentalKey); + context?.rental?.rented(fakeInstanceId); + return { providerSessionId: fakeInstanceId }; + }, + release: stop, + }, + }); + const rename = fs.renameSync; + const failure = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { + if (to === journalPath && fs.readFileSync(from, 'utf8').includes(fakeInstanceId)) + throw new Error('Exact ID publication unavailable.'); + rename(from, to); + }); + try { + expect(await send(daemon, 'lease_allocate', scope)).toMatchObject({ + ok: false, + error: { message: expect.stringContaining('Exact ID publication unavailable') }, + }); + expect(legacy ? legacyStop : stop).toHaveBeenCalled(); + expect(await send(daemon, 'lease_allocate', { ...scope, leaseId: undefined })).toMatchObject({ + ok: false, + error: { code: 'DEVICE_IN_USE', details: { releaseStatus: 'unknown' } }, + }); + expect(fs.readFileSync(journalPath, 'utf8')).not.toContain(fakeInstanceId); + failure.mockRestore(); + await vi.waitFor( + () => { + expect(JSON.parse(fs.readFileSync(journalPath, 'utf8')).rentals).toMatchObject([ + { releaseOnRestart: { reconciliationKey: fakeRentalKey, instanceId: fakeInstanceId } }, + ]); + }, + { timeout: 4_000 }, + ); + } finally { + failure.mockRestore(); + await daemon.runtime.close(); + } + }, +); diff --git a/src/provider-device-runtime.ts b/src/provider-device-runtime.ts index 210faf44c1..b3dcd82f10 100644 --- a/src/provider-device-runtime.ts +++ b/src/provider-device-runtime.ts @@ -182,6 +182,10 @@ function composeLeaseProvider( ): LeaseLifecycleProvider | undefined { if (runtimes.length === 0) return undefined; return { + recoverRental: async (lease, identity, recordInstance) => + (await runtimes + .find((runtime) => runtimeMatchesProvider(runtime, lease.leaseProvider)) + ?.leaseLifecycle.recoverRental?.(lease, identity, recordInstance)) ?? false, allocate: async (lease, context) => await firstProviderResult(runtimes, 'allocate', lease, context), heartbeat: async (lease, context) => diff --git a/src/provider-device-runtimes.test.ts b/src/provider-device-runtimes.test.ts index bdc06d0bb0..c5a0d0901d 100644 --- a/src/provider-device-runtimes.test.ts +++ b/src/provider-device-runtimes.test.ts @@ -2,7 +2,6 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { test, vi } from 'vitest'; -import type { DeviceLease } from '@agent-device/contracts/device'; import { createAgentDeviceClient } from '@agent-device/client'; import { mkdtempForTestSync, skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; import { startPublicDaemonRuntime } from './__tests__/test-utils/public-daemon-runtime.ts'; @@ -25,11 +24,17 @@ vi.mock('@agent-device/plugins/store', async (importOriginal) => vi.mock('@limrun/api', () => ({ default: class MockLimrun { + readonly baseURL = 'https://limrun.example.test'; + readonly _options = {}; readonly iosInstances = { create: limrun.iosCreate, list: limrun.iosList, delete: limrun.iosDelete, }; + + async buildRequest() { + return { req: { headers: new Headers({ authorization: 'Bearer fixture-account' }) } }; + } }, })); @@ -40,7 +45,7 @@ vi.mock('@limrun/api/ios-client', () => ({ })), })); -test('Limrun retries an expired provider lease persisted by a daemon before restart', async (t) => { +test('Limrun retries an expired provider rental by exact identity after restart', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const stateDir = mkdtempForTestSync('agent-device-limrun-expired-lease-restart-'); const env = { LIMRUN_API_KEY: 'lim_test_key', AGENT_DEVICE_LEASE_MIN_TTL_MS: '1' }; @@ -89,28 +94,23 @@ test('Limrun retries an expired provider lease persisted by a daemon before rest await firstDaemon.runtime.close(); assert.ok(limrun.iosDisconnect.mock.calls.length > 0); - const pendingPath = path.join(stateDir, 'expired-provider-leases.json'); - const pending = JSON.parse(fs.readFileSync(pendingPath, 'utf8')) as { leases: DeviceLease[] }; - assert.deepEqual( - pending.leases.map(({ leaseId }) => leaseId), - [lease.leaseId], - ); + const rentalPath = path.join(stateDir, 'provider-rentals.json'); + const pending = JSON.parse(fs.readFileSync(rentalPath, 'utf8')); + assert.equal(pending.rentals.length, 1); + assert.equal(pending.rentals[0].releaseOnRestart.instanceId, 'ios-instance-1'); + const deletesBeforeRestart = limrun.iosDelete.mock.calls.length; + const listsBeforeRestart = limrun.iosList.mock.calls.length; limrun.iosDelete.mockResolvedValue(undefined); restartedDaemon = await startPublicDaemonRuntime({ stateDir, env }); - await vi.waitFor(() => assert.ok(limrun.iosDelete.mock.calls.length > 1), { + await vi.waitFor(() => assert.ok(limrun.iosDelete.mock.calls.length > deletesBeforeRestart), { interval: 10, timeout: 2_000, }); - assert.deepEqual(limrun.iosList.mock.calls.at(-1), [ - { labelSelector: `provider=limrun,leaseId=${lease.leaseId}` }, - ]); - assert.deepEqual(limrun.iosDelete.mock.calls.at(-1), [ - 'ios-instance-recovered', - { maxRetries: 0 }, - ]); - assert.equal(fs.existsSync(pendingPath), false); + assert.equal(limrun.iosList.mock.calls.length, listsBeforeRestart); + assert.deepEqual(limrun.iosDelete.mock.calls.at(-1), ['ios-instance-1', { maxRetries: 0 }]); + assert.deepEqual(JSON.parse(fs.readFileSync(rentalPath, 'utf8')).rentals, []); } finally { dateNow.mockRestore(); if (restartedDaemon) { diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 79274f07e1..516f281fbc 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -814,6 +814,7 @@ These reasons can come from more than one command. | `LEASE_OUTPUT_MISMATCH` | The request does not send the id of the lease that produced the artifact or diagnostics record. | | `DEVICE_LEASE_BUSY` | Another lease, or this tenant run, already holds the device; retry after that lease is released or expires. | | `session-cleanup-pending` | The lease is ending and its local session cleanup is still pending. | +| `provider-rental-retirement-pending` | The provider confirmed release. Retry allocation after the daemon records that result. | | `LEASE_ID_TOO_SHORT` | A lease id that the caller chose on allocate has fewer than 32 hex digits (128 bits). | | `LEASE_ID_IN_USE` | The requested lease id already names a lease that this daemon issued. | | `LEASE_CAPACITY_EXCEEDED` | Every iOS simulator lease slot is taken; retry after another lease is released. | diff --git a/website/docs/docs/plugins.md b/website/docs/docs/plugins.md index 93228e7ec0..c4f4e71f90 100644 --- a/website/docs/docs/plugins.md +++ b/website/docs/docs/plugins.md @@ -136,6 +136,14 @@ The host resolves the `./agent-device` export with import conditions. It falls b Provider runtimes must return a typed result from `leaseLifecycle.release`. Return `{ release: 'confirmed' }` when the rental is gone, or `{ release: 'unknown' }` when the provider cannot confirm it. Include optional artifact metadata in `provider`. Plugins built against the previous release hook must update their return value before upgrading the daemon. +Call `context.rental?.beforeCreate(key)` before sending a billable create. Send the create only after that call succeeds. Call `context.rental?.rented(instanceId)` as soon as the provider identifies the instance. Use non-secret values for both identifiers. + +Implement `leaseLifecycle.recoverRental` to release the recorded instance or find it by the reconciliation key. If lookup supplies the instance ID, call `recordInstance` before deleting it. Return `true` only when the provider confirms release or can rule out a late create. The daemon keeps unresolved rentals fenced across restarts. + +Set `runtime.rentalRecoveryPrincipal` to an opaque, non-secret string that identifies the effective provider account and API origin, including settings supplied through plugin options. If you derive it from credentials, persist only the digest. Keep the principal stable when allocation preferences such as device model change. If either the journaled or current principal is missing, or they differ, the daemon keeps the rental fenced. + +For new journaled rentals, the principal is required for both `recoverRental` and `recoverExpiredLease`. The daemon uses `recoverExpiredLease` for new rentals from providers that offer only that hook and to adopt historical live and pending lease files. + If your plugin uses Appium or WebDriver, bundle the engine with your plugin and build the runtime in `setup`. Use `host.diagnostics.emit(event)` to record a diagnostic in the active request log. If required credentials are absent, return `{ dormant: { reason, message, hint? } }` from `setup`. Use a stable reason code and a message describing the prerequisite. Use the hint to explain how to supply it. Omit the runtime, platform module, and disposer for this outcome. Throw when setup fails.