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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions docs/adr/0007-remote-device-leases.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,17 @@ An expired owner request returns `LEASE_NOT_FOUND`.
An owner `close` can report a confirmed end once in the outermost response.
When a provider reports an instance ended, the daemon ends the lease and its sessions regardless of provider cleanup outcome.
A cloud provider runtime refuses to allocate a lease that it is ending. It forgets a rented device only after the provider confirmed its stop.
Recoverable provider leases are journaled so a later daemon can end rentals left by a dead daemon.
Startup restores the reservation for an unresolved recoverable lease before it accepts overlapping allocations.
Live sessions start empty, and persistent device claims are checked under their host-global lock.
The daemon keeps the lease end reservation when provider creation fails or the caller cancels.
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.
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.
If the daemon cannot confirm provider release or clear the exact claim, keep the scope reserved and report `releaseStatus: unknown` with a typed `releaseReason`.
If claim clear fails or the claim has no attributable owner, stop automatic session cleanup retries.
The live session store starts empty.

The registry checks the lease issuance, effective deadline, wanted work, and pending or active holds in the same expiry decision.
Wanted admitted work and human-control holds defer expiry.
Expand Down Expand Up @@ -105,7 +113,7 @@ The detailed contracts are in the [daemon](../../packages/daemon/docs/remote-dev
- 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)).
- Provider allocation can still leave a rental outside registry recovery when a first allocation fails or a late allocation's release fails. Only the provider runtime that still holds the device can end that rental.
- 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.
8 changes: 7 additions & 1 deletion packages/contracts/src/device-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ export type LeaseLifecycleContext = {
deadline?: number;
};

export type ProviderLeaseRelease = {
release: 'confirmed' | 'unknown';
provider?: Record<string, unknown>;
error?: unknown;
};

export type LeaseLifecycleProvider = {
allocate?: (
lease: DeviceLease,
Expand All @@ -50,7 +56,7 @@ export type LeaseLifecycleProvider = {
release?: (
lease: DeviceLease,
context?: LeaseLifecycleContext,
) => Promise<Record<string, unknown> | undefined>;
) => Promise<ProviderLeaseRelease | undefined>;
};

export type DeviceInventoryProvider = (
Expand Down
1 change: 1 addition & 0 deletions packages/contracts/src/facades/device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export type {
DeviceLease,
LeaseLifecycleContext,
LeaseLifecycleProvider,
ProviderLeaseRelease,
ProviderAppCatalog,
ProviderAppCatalogHandler,
ProviderAppCatalogQuery,
Expand Down
2 changes: 2 additions & 0 deletions packages/daemon-contracts/src/daemon-resolution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,8 @@ export const DAEMON_LIFECYCLE_REASONS = {
ownerEmbedded: { reason: 'daemon-owner-embedded' },
// The daemon has begun to leave, so it refuses every new request; retry against a new daemon.
shuttingDown: { reason: 'daemon_shutting_down' },
// Startup failed while this request waited for recovery.
startupFailed: { reason: 'daemon-startup-failed' },
} as const satisfies ReasonTable<'daemon lifecycle'>;

/**
Expand Down
20 changes: 10 additions & 10 deletions packages/daemon/docs/remote-device-lease-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ The daemon sweeps for expired leases every second.
A request can also trigger expiry.
Both paths share one teardown for each expired session.
The daemon keeps the lease reservation until session cleanup and any provider release are confirmed.
If the provider refuses release and no recovery record exists, an overlapping allocation returns
`DEVICE_LEASE_BUSY` with `releaseStatus: "unknown"`.
If the daemon cannot confirm release, an overlapping allocation returns `DEVICE_LEASE_BUSY` with
`releaseStatus: "unknown"` and a typed `releaseReason`.
If the daemon cannot clear the exact device claim, it keeps the scope reserved and stops automatic session cleanup retries.
If expiry wins, the old owner's request returns `LEASE_NOT_FOUND`.
An owner `close` can report the confirmed lease end in `endedLeases` on that error.
Only `open` with a separate valid lease can replace an expired session.
Expand All @@ -39,18 +40,18 @@ 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.
Thus, the daemon journals the live leases of each provider that can recover an expired lease, in `live-provider-leases.json` in its state directory.
A daemon that starts and finds this journal hands each lease in it to the expired-lease recovery of its provider, which ends the rented device.
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.
Two routes still let the registry forget a provider lease while its device may be rented. The journal and expiry recovery both follow the registry, so neither covers it, and only the provider runtime still holding the device can end it:

- A failed first allocation releases the registry entry without a provider release, while its provider start may still run.
- An allocation that finishes after its requester left releases the registry entry even when the provider release throws.
A failed or canceled first allocation keeps its reservation while the provider can still be creating or releasing the device.
If creation succeeds after cancellation, the adapter releases the exact instance.
If the provider cannot prove release, the reservation remains.
Rentals without durable evidence require operator reconciliation. [#4972](https://github.com/callstack/agent-device/issues/4972) tracks the durable rental journal.

When a request closes a session, the daemon ends the lease of that session, unless the lease was allocated with `retainOnClose`.
The reply to that request reports each lease that it ended once, at response level, as `endedLeases: [{ leaseId, outcome: 'released' }]`.
Expand Down Expand Up @@ -164,9 +165,8 @@ Allocation is admitted work too.
The registry records a lease before a hosted provider creates the session behind it.
Creation of that session can take longer than the inactivity TTL of the lease.
The allocation holds a work pass while the provider allocates, so its lease does not expire before delivery.
The lease cannot expire during that allocation.
If a successful allocation is still wanted by its requester, the inactivity TTL starts from the moment allocation completed.
A requester that hung up preserves nothing, and its allocation is released as before.
Cancellation ends the allocation work pass. The lease reservation still protects the device until release is confirmed.

## Human control

Expand Down
12 changes: 12 additions & 0 deletions packages/daemon/src/__tests__/support/finish-test-lease.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { LeaseRegistry } from '../../resources/lease-registry.ts';

export function finishTestLease(
registry: LeaseRegistry,
request: Parameters<LeaseRegistry['getLease']>[0],
) {
const lease = registry.getLease(request);
if (!lease) return { released: false };
registry.beginLeaseEnd(lease, { sessionsSettled: true, providerRelease: 'confirmed' });
registry.confirmLeaseEnd(lease.leaseId, 'providerReleased');
return { released: true, lease };
}
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,14 @@ export async function resourceAdmissionWorld(
pluginInventory: registry.inventory,
shutdownProviderRuntimes: registry.close,
...((options.withLifecycleProvider ?? options.providerOwned)
? { leaseLifecycleProvider: { release: providerRelease } }
? {
leaseLifecycleProvider: {
release: async () => ({
release: 'confirmed' as const,
provider: await providerRelease(),
}),
},
}
: {}),
providerDeviceAdmission: Object.freeze({ isActive: () => options.providerOwned === true }),
deviceRuntimeGateway: {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { finishTestLease } from '../../__tests__/support/finish-test-lease.ts';
import { expect, test } from 'vitest';
import assert from 'node:assert/strict';
import { LeaseRegistry } from '../lease-registry.ts';
Expand Down Expand Up @@ -65,25 +66,25 @@ test.each(['sessionsSettled', 'providerReleased'] as const)(
let now = 1_000;
const registry = new LeaseRegistry({
now: () => now,
onLeaseExpired: (lease) => registry.reserveExpiredLease(lease),
onLeaseExpired: () => {},
});
const request = { ...HUMAN_CONTROL_LEASE_REQUEST, leaseProvider: 'fixture' };
const lease = registry.allocateLease(request);
now = lease.expiresAt;
expect(registry.consumeExpiredLeases()).toEqual([lease]);
const next = { ...request, runId: 'successor' };
const expectBusy = () =>
const expectBusy = (reason = 'DEVICE_LEASE_BUSY') =>
expect(() => registry.allocateLease(next)).toThrow(
expect.objectContaining({
details: expect.objectContaining({ reason: 'DEVICE_LEASE_BUSY' }),
details: expect.objectContaining({ reason }),
}),
);

expectBusy();
expect(registry.confirmExpiredLeaseEnd(lease.leaseId, first)).toBe(false);
expectBusy();
expect(registry.confirmLeaseEnd(lease.leaseId, first)).toBe(false);
expectBusy(first === 'providerReleased' ? 'session-cleanup-pending' : 'DEVICE_LEASE_BUSY');
const second = first === 'sessionsSettled' ? 'providerReleased' : 'sessionsSettled';
expect(registry.confirmExpiredLeaseEnd(lease.leaseId, second)).toBe(true);
expect(registry.confirmLeaseEnd(lease.leaseId, second)).toBe(true);
expect(registry.allocateLease(next).leaseId).not.toBe(lease.leaseId);
},
);
Expand All @@ -92,17 +93,17 @@ test('an ending lease without a device key keeps its run binding until confirmat
let now = 1_000;
const registry = new LeaseRegistry({
now: () => now,
onLeaseExpired: (lease) => registry.reserveExpiredLease(lease),
onLeaseExpired: () => {},
});
const request = { tenantId: 'tenant', runId: 'run', leaseProvider: 'fixture' };
const lease = registry.allocateLease(request);
now = lease.expiresAt;
registry.consumeExpiredLeases();
registry.confirmExpiredLeaseEnd(lease.leaseId, 'sessionsSettled');
registry.confirmLeaseEnd(lease.leaseId, 'sessionsSettled');
expect(() => registry.allocateLease(request)).toThrow(
expect.objectContaining({ details: expect.objectContaining({ reason: 'DEVICE_LEASE_BUSY' }) }),
);
expect(registry.confirmExpiredLeaseEnd(lease.leaseId, 'providerReleased')).toBe(true);
expect(registry.confirmLeaseEnd(lease.leaseId, 'providerReleased')).toBe(true);
expect(registry.allocateLease(request).leaseId).not.toBe(lease.leaseId);
});

Expand All @@ -118,7 +119,9 @@ test('a delayed expiry reservation cannot fence a renewed host lease with the sa
now = lease.expiresAt;
const expired = registry.consumeExpiredLease(leaseId);
assert.ok(expired);
const reservation = beforeReservation.then(() => registry.reserveExpiredLease(expired));
const reservation = beforeReservation.then(() =>
registry.beginLeaseEnd(expired, { sessionsSettled: true, providerRelease: 'confirmed' }),
);

const reissued = registry.putHostLease(leaseId, HUMAN_CONTROL_LEASE_REQUEST);
const work = registry.retainLeaseWork(reissued, () => true);
Expand All @@ -128,7 +131,34 @@ test('a delayed expiry reservation cannot fence a renewed host lease with the sa
resume();

const reserved = await reservation;
expect(registry.releaseLease({ ...HUMAN_CONTROL_LEASE_REQUEST, leaseId }).released).toBe(true);
expect(finishTestLease(registry, { ...HUMAN_CONTROL_LEASE_REQUEST, leaseId }).released).toBe(
true,
);
expect(registry.allocateLease(HUMAN_CONTROL_LEASE_REQUEST).leaseId).not.toBe(leaseId);
expect(reserved).toBe(false);
});

test('a confirmed provider release reports pending session cleanup without a claim refusal', () => {
const registry = new LeaseRegistry();
const scope = {
tenantId: 'tenant-a',
runId: 'run-a',
leaseProvider: 'limrun',
deviceKey: 'ios:fixture',
};
const lease = registry.allocateLease(scope);
registry.beginLeaseEnd(lease, { sessionsSettled: false, providerRelease: 'confirmed' });

expect(() => registry.allocateLease(scope)).toThrow(
expect.objectContaining({
code: 'DEVICE_IN_USE',
details: expect.objectContaining({ reason: 'session-cleanup-pending' }),
}),
);
const details = registry.leaseEndRefusal(lease.leaseId)?.details;
expect(details?.reason).toBe('session-cleanup-pending');
expect(details).not.toHaveProperty('releaseReason');
expect(details).not.toHaveProperty('releaseStatus');
expect(registry.confirmLeaseEnd(lease.leaseId, 'sessionsSettled')).toBe(true);
expect(() => registry.allocateLease(scope)).not.toThrow();
});
17 changes: 9 additions & 8 deletions packages/daemon/src/resources/__tests__/lease-registry.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { finishTestLease } from '../../__tests__/support/finish-test-lease.ts';
import { test } from 'vitest';
import assert from 'node:assert/strict';
import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors';
Expand Down Expand Up @@ -62,7 +63,7 @@ test('allocateLease keeps a caller-chosen lease id and refuses any id it already
(error: unknown) => error instanceof AppError && error.code === 'INVALID_ARGS',
);

assert.equal(registry.releaseLease({ leaseId: lease.leaseId }).released, true);
assert.equal(finishTestLease(registry, { leaseId: lease.leaseId }).released, true);
assert.throws(
() => registry.allocateLease({ tenantId: 'tenant-b', runId: 'run-2', leaseId: chosen }),
isLeaseIdInUse,
Expand All @@ -73,8 +74,8 @@ test('allocateLease keeps a caller-chosen lease id and refuses any id it already
tenantId: 'tenant-d',
runId: 'run-4',
});
assert.equal(registry.releaseLease({ leaseId: minted.leaseId }).released, true);
assert.equal(registry.releaseLease({ leaseId: hostIssued.leaseId }).released, true);
assert.equal(finishTestLease(registry, { leaseId: minted.leaseId }).released, true);
assert.equal(finishTestLease(registry, { leaseId: hostIssued.leaseId }).released, true);
for (const leaseId of [minted.leaseId, hostIssued.leaseId]) {
assert.throws(
() => registry.allocateLease({ tenantId: 'tenant-e', runId: 'run-5', leaseId }),
Expand Down Expand Up @@ -275,9 +276,9 @@ test('heartbeatLease extends active lease and releaseLease is idempotent', () =>
assert.equal(heartbeat.heartbeatAt, 5_000);
assert.equal(heartbeat.expiresAt, 25_000);

const released = registry.releaseLease({ leaseId: lease.leaseId });
const released = finishTestLease(registry, { leaseId: lease.leaseId });
assert.deepEqual(released, { released: true, lease: heartbeat });
const releasedAgain = registry.releaseLease({ leaseId: lease.leaseId });
const releasedAgain = finishTestLease(registry, { leaseId: lease.leaseId });
assert.deepEqual(releasedAgain, { released: false });
});

Expand All @@ -290,7 +291,7 @@ test('heartbeat/release enforce optional tenant/run scope matching', () => {
/Lease does not match tenant\/run scope/,
);
assert.throws(
() => registry.releaseLease({ leaseId: lease.leaseId, runId: 'run-2' }),
() => finishTestLease(registry, { leaseId: lease.leaseId, runId: 'run-2' }),
/Lease does not match tenant\/run scope/,
);
});
Expand Down Expand Up @@ -513,7 +514,7 @@ test('heartbeat/release require owner scope for device-aware leases', () => {
);
assert.throws(
() =>
registry.releaseLease({
finishTestLease(registry, {
leaseId: lease.leaseId,
tenantId: 'tenant-a',
runId: 'run-1',
Expand Down Expand Up @@ -902,7 +903,7 @@ test('releasing a lease drops the work claims recorded against it', () => {
const lease = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-9' });
const pass = registry.retainLeaseWork(lease, () => true);

registry.releaseLease({ leaseId: lease.leaseId });
finishTestLease(registry, { leaseId: lease.leaseId });
pass.release();

assert.deepEqual(inFlightClaimKeys(registry), []);
Expand Down
Loading
Loading