Skip to content

Commit 4ae7368

Browse files
committed
fix(limrun): answer one delete for one instance, with its reason
The instance delete joins the create under the same request contract: one attempt at the SDK, because a lost answer is ambiguous and this runtime retries deletes at its own budgets, not the SDK's. A 404 is Limrun answering that the instance is already gone — exactly what the delete was after — so it confirms the end instead of holding the lease for a retry that can only fail again. The recovery route that ends a lease from its labels keeps the same contract. Every refusal that says an instance is not confirmed deleted now carries the delete's own error as its cause, where a cause renders, beside the text in details; a create that both failed and could not be undone reports both reasons, not only the delete's. The disposal outcome records the delete's cause so each route can raise it without re-deriving anything. A replacement creation is observed the moment it is published, so the owner's promise that a creation cannot reach the process unobserved holds by construction on every path that installs one. Docs and shape: the teardown-scope marker and the reverse route keep their own comments, the capture lifecycle's paragraph sits on its class, shutdown's snapshot names its binding, and the close's report lists every lease it could not end with each of their reasons.
1 parent e5ebf76 commit 4ae7368

11 files changed

Lines changed: 333 additions & 97 deletions

‎packages/provider-limrun/src/android.ts‎

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -242,22 +242,21 @@ async function runLimrunAndroidAdb(
242242
return await runLimrunAndroidAdbAtSerial(session, serial, args, options);
243243
}
244244

245-
/**
246-
* The reverse manager's own route to the device. It is the session's route while the session is live, and
247-
* cleanup's route of its own once the session is retired: clearing reverse mappings means reaching the device
248-
* that is about to be disconnected, and that has to stay possible after every caller of this session was
249-
* refused. Only the cleanup's own dispatches carry its teardown scope, so no caller command is ever
250-
* dispatched at the serial the teardown is ending.
251-
*/
252245
/**
253246
* Whether one dispatch belongs to a session's teardown: true only for the dispatches that teardown itself
254-
* started. The reverse manager is given this predicate as its route, and a provider that hands a caller
255-
* command to it — a reverse command queued inside an operation of its own — carries no marker, so the
256-
* manager cannot have a caller's mapping bound at a serial that is on its way out. A marker set by one
257-
* session never authorises another session's route.
247+
* started. A provider that hands a caller command to the reverse route — a reverse command queued inside an
248+
* operation of its own — carries no marker, so the manager cannot have a caller's mapping bound at a serial
249+
* that is on its way out. A marker set by one session never authorises another session's route.
258250
*/
259251
const limrunAdbTeardownScope = new AsyncLocalStorage<boolean>();
260252

253+
/**
254+
* The reverse manager's own route to the device. It is the session's route while the session is live, and
255+
* cleanup's route of its own once the session is retired: clearing reverse mappings means reaching the device
256+
* that is about to be disconnected, and that has to stay possible after every caller of this session was
257+
* refused. Only a dispatch that carries its session's teardown scope may use the teardown's executor, so no
258+
* caller command is ever dispatched at the serial the teardown is ending.
259+
*/
261260
async function runLimrunAndroidReverseAdb(
262261
session: LimrunAndroidAdbSession,
263262
args: readonly string[],

‎packages/provider-limrun/src/capture-lifecycle.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ test('a repeat allocation stops waiting on a destination tunnel that never answe
2121
joined = true;
2222
});
2323
try {
24+
// Below the budget the join is still waiting: only its expiry ends it, not an early return.
25+
await vi.advanceTimersByTimeAsync(19_000);
26+
await Promise.resolve();
27+
assert.ok(!joined, 'expected the join to keep waiting inside its budget');
2428
await vi.advanceTimersByTimeAsync(CAPTURE_OPEN_WAIT_MS);
2529
await joining;
2630
} finally {

‎packages/provider-limrun/src/capture-lifecycle.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,6 @@ import type { NetworkCapture, SettledNetworkCapture } from './network-har.ts';
77
import { awaitLimrunWithinBudget } from './lifecycle-budget.ts';
88
import { errorMessage } from '@agent-device/kernel/errors';
99

10-
/**
11-
* What one lease's network capture goes through: starting it, ending it, and answering what `artifacts` can
12-
* say about it. The owner is where a capture lives, including a start whose destination tunnel is still being
13-
* opened, so the allocation that started one, a release that took the lease over, and an artifacts read all
14-
* look at the same thing and none of them can end up owning a tunnel nobody can close.
15-
*/
16-
1710
/**
1811
* How long a read or a teardown waits for a destination tunnel that is still being opened. The SDK gives this
1912
* handshake fifteen seconds of its own.
@@ -32,6 +25,12 @@ export type LimrunCaptureHost = Readonly<{
3225
heldOwners(): Iterable<LimrunLeaseOwner>;
3326
}>;
3427

28+
/**
29+
* What one lease's network capture goes through: starting it, ending it, and answering what `artifacts` can
30+
* say about it. The owner is where a capture lives, including a start whose destination tunnel is still being
31+
* opened, so the allocation that started one, a release that took the lease over, and an artifacts read all
32+
* look at the same thing and none of them can end up owning a tunnel nobody can close.
33+
*/
3534
export class LimrunCaptureLifecycle {
3635
/** The capture records this lifecycle settled, which outlive their lease so `artifacts` can still name them. */
3736
private readonly settled = new Map<string, SettledNetworkCapture>();

‎packages/provider-limrun/src/client-options.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type Limrun from '@limrun/api';
2-
import { AppError } from '@agent-device/kernel/errors';
2+
import { AppError, errorMessage } from '@agent-device/kernel/errors';
3+
import type { LimrunDeleteResult } from './lease-ownership.ts';
34

45
export const LIMRUN_CLIENT_ID = 'agent-device-cli';
56

@@ -19,6 +20,38 @@ export function limrunUserAgent(clientVersion: string): string {
1920
*/
2021
export const LIMRUN_SINGLE_ATTEMPT = Object.freeze({ maxRetries: 0 });
2122

23+
/**
24+
* Ends one instance, answering with no failure once Limrun has it gone and with a failure string and its error
25+
* otherwise. Like the create, the delete is asked for in one attempt: a lost answer is ambiguous, and this
26+
* runtime's retries happen at its own budgets, not the SDK's. A 404 is Limrun answering that the instance is
27+
* already gone, which is exactly what the delete was asked to achieve, so it confirms rather than refuses.
28+
*/
29+
export async function deleteLimrunInstance(
30+
limrun: Limrun,
31+
platform: 'ios' | 'android',
32+
instanceId: string,
33+
): Promise<LimrunDeleteResult> {
34+
try {
35+
if (platform === 'ios') {
36+
await limrun.iosInstances.delete(instanceId, LIMRUN_SINGLE_ATTEMPT);
37+
} else {
38+
await limrun.androidInstances.delete(instanceId, LIMRUN_SINGLE_ATTEMPT);
39+
}
40+
return { failure: undefined, cause: undefined };
41+
} catch (error) {
42+
// A 404 names the outcome this request was after, however it came about.
43+
if (readHttpStatus(error) === 404) return { failure: undefined, cause: undefined };
44+
return { failure: errorMessage(error), cause: error };
45+
}
46+
}
47+
48+
/** The HTTP status of an SDK failure, for a route that can answer for one particular refusal. */
49+
function readHttpStatus(error: unknown): number | undefined {
50+
if (!error || typeof error !== 'object') return undefined;
51+
const status = (error as { status?: unknown }).status;
52+
return typeof status === 'number' ? status : undefined;
53+
}
54+
2255
/** The organization client, or a typed refusal for an operation that needs the API key. */
2356
export function requireLimrunOrgClient(
2457
limrun: Limrun | undefined,

‎packages/provider-limrun/src/lease-ownership.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ export type LimrunLeaseOwner = {
6363
* a delete whose answer this disposal stopped waiting for is still the delete that instance is getting.
6464
*/
6565
pendingDelete:
66-
| Readonly<{ instanceId: string; requested: Promise<string | undefined> }>
66+
| Readonly<{ instanceId: string; requested: Promise<LimrunDeleteResult> }>
6767
| undefined;
6868
};
6969

@@ -99,10 +99,24 @@ export type LimrunDisposalOutcome = Readonly<{
9999
instanceId: string | undefined;
100100
/** Why a disposal could not be confirmed; absent once the instance is gone. */
101101
failure: string | undefined;
102+
/**
103+
* The refusal behind that failure, when one exists: the delete's own error. Reported as an error's cause,
104+
* where it renders, rather than only as a string in details.
105+
*/
106+
cause: unknown;
102107
/** The released capture's record, so a refusal can still carry the HAR that was written. */
103108
capture: SettledNetworkCapture | undefined;
104109
}>;
105110

111+
/**
112+
* What one instance delete came to: whether Limrun has the instance gone, and what refused it otherwise.
113+
*/
114+
export type LimrunDeleteResult = Readonly<{
115+
failure: string | undefined;
116+
/** The refusal behind that failure, for whoever has to report it. */
117+
cause: unknown;
118+
}>;
119+
106120
/**
107121
* What one create amounted to: the session it made, why it failed, or that the caller who started it was
108122
* refused before anything was billed. `refused_caller` is that caller's own answer and not the lease's: an

‎packages/provider-limrun/src/lease-release.test.ts‎

Lines changed: 83 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,17 @@
11
import { test, vi, expect } from 'vitest';
22
import type { DeviceLease } from '@agent-device/contracts/device';
3-
import { disposeLimrunLeaseOwner, type LimrunDisposalHost } from './lease-release.ts';
4-
import type { LimrunCreateOutcome, LimrunLeaseOwner } from './lease-ownership.ts';
3+
import { AppError } from '@agent-device/kernel/errors';
4+
import {
5+
cleanupLeftInstancesRunning,
6+
createLeftInstanceRunning,
7+
disposeLimrunLeaseOwner,
8+
type LimrunDisposalHost,
9+
} from './lease-release.ts';
10+
import type {
11+
LimrunCreateOutcome,
12+
LimrunDisposalOutcome,
13+
LimrunLeaseOwner,
14+
} from './lease-ownership.ts';
515

616
/*
717
* Each wait is longer than the budgets it steps past: a disposal's create wait, and everything a disposal
@@ -22,7 +32,7 @@ test('a create that answers late joins the delete its disposal already started',
2232
await new Promise<void>((resolve) => {
2333
reportDelete = resolve;
2434
});
25-
return undefined;
35+
return { failure: undefined, cause: undefined };
2636
});
2737
const host: LimrunDisposalHost = {
2838
deleteInstance: deleteHost,
@@ -60,6 +70,76 @@ test('a create that answers late joins the delete its disposal already started',
6070
expect(owner.deletedInstanceId).toBe('android-instance-1');
6171
});
6272

73+
/**
74+
* A delete Limrun refused keeps its own error on the disposal outcome, and the refusals every route raises
75+
* carry it as their cause — where a cause renders — beside the text that says the delete was unconfirmed.
76+
*/
77+
test("a refused delete reports its own error as the refusal's cause", async () => {
78+
await import('./lifecycle-budget.ts');
79+
const refusal = new Error('Limrun refused to delete the instance');
80+
const host: LimrunDisposalHost = {
81+
deleteInstance: async () => ({
82+
failure: 'Limrun refused to delete the instance',
83+
cause: refusal,
84+
}),
85+
endCapture: async () => undefined,
86+
};
87+
const owner = ownerWithRentedInstance(
88+
Promise.resolve<LimrunCreateOutcome>({ status: 'failed', error: new Error('boot failed') }),
89+
);
90+
const outcome = await disposeLimrunLeaseOwner(host, owner);
91+
expect(outcome.cleanup).toBe('uncertain');
92+
expect(outcome.cause).toBe(refusal);
93+
94+
// The allocation's refusal names both what it could not settle and why its create failed at all.
95+
const lease = (owner as unknown as { lease: DeviceLease }).lease;
96+
const thrown = captureThrow(() =>
97+
createLeftInstanceRunning(lease, outcome, new Error('boot failed')),
98+
);
99+
expect(thrown.details?.reason).toBe('limrun_instance_delete_unconfirmed');
100+
expect(String(thrown.details?.cause)).toContain('boot failed');
101+
expect(thrown.cause).toBe(refusal);
102+
});
103+
104+
/**
105+
* A daemon close that could not end two leases names both of them and why each is still held, not only the
106+
* first — every one of them may need to be named to Limrun by hand.
107+
*/
108+
test('a close that could not end two leases reports both reasons', async () => {
109+
const refusal = new Error('Limrun refused to delete the instance');
110+
const outcomes: LimrunDisposalOutcome[] = [
111+
{
112+
cleanup: 'uncertain',
113+
instanceId: 'android-instance-1',
114+
failure: 'delete one refused',
115+
cause: refusal,
116+
capture: undefined,
117+
},
118+
{
119+
cleanup: 'uncertain',
120+
instanceId: undefined,
121+
failure: undefined,
122+
cause: undefined,
123+
capture: undefined,
124+
},
125+
];
126+
const thrown = captureThrow(() => cleanupLeftInstancesRunning(outcomes));
127+
expect(thrown.details?.reason).toBe('limrun_instance_delete_unconfirmed');
128+
expect(thrown.details?.limrunInstanceIds).toEqual(['android-instance-1']);
129+
expect(String(thrown.details?.cause)).toContain('delete one refused');
130+
expect(String(thrown.details?.cause)).toContain('an unconfirmed delete');
131+
expect(thrown.cause).toBe(refusal);
132+
});
133+
134+
function captureThrow(raise: () => never): AppError {
135+
try {
136+
raise();
137+
} catch (error) {
138+
return error as AppError;
139+
}
140+
throw new Error('expected the refusal to throw');
141+
}
142+
63143
/** An owner whose create has rented an instance but has not answered, taken by a disposal. */
64144
function ownerWithRentedInstance(creation: Promise<LimrunCreateOutcome>): LimrunLeaseOwner {
65145
const lease = {

0 commit comments

Comments
 (0)