Repository navigation
Expand file tree
/
Copy pathlease.test.ts
More file actions
269 lines (258 loc) · 9.25 KB
/
Copy pathlease.test.ts
File metadata and controls
269 lines (258 loc) · 9.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import assert from 'node:assert/strict';
import { test } from 'vitest';
import { handleLeaseCommands } from '../lease.ts';
import { LeaseRegistry } from '../../lease-registry.ts';
import type { DaemonRequest } from '../../daemon-request.ts';
import { makeSessionStore } from '../../../__tests__/test-utils/store-factory.ts';
import type { DeviceLease } from '@agent-device/contracts/device';
import { AppError } from '@agent-device/kernel/errors';
import {
clearRequestCanceled,
markRequestCanceled,
registerRequestAbort,
} from '@agent-device/host-kit/request';
import {
HUMAN_CONTROL_LEASE_REQUEST,
HUMAN_CONTROL_SCOPE,
createControlLatch,
humanControlRequest,
} from '../../__tests__/human-control-fixtures.ts';
for (const operation of ['allocate', 'release'] as const) {
test(`host activation drains provider lease ${operation} before reporting active`, async () => {
const registry = new LeaseRegistry();
const lease = registry.allocateLease(HUMAN_CONTROL_LEASE_REQUEST);
const started = createControlLatch();
const finish = createControlLatch();
const request = humanControlRequest(lease, `lease_${operation}`, []);
const mutation = handleLeaseCommands({
req: request,
sessionName: request.session,
sessionStore: makeSessionStore('agent-device-held-provider-'),
leaseRegistry: registry,
leaseLifecycleProvider: {
[operation]: async () => {
started.resolve();
await finish.promise;
return {};
},
},
});
await started.promise;
let active = false;
const activation = registry
.putHumanControlHold({ kind: 'host' }, 'host', { scope: HUMAN_CONTROL_SCOPE })
.then(() => {
active = true;
});
await Promise.resolve();
assert.equal(active, false);
finish.resolve();
assert.equal((await mutation)?.ok, true);
await activation;
assert.equal(active, true);
});
}
test('activation drains canceled provider allocation and its release cleanup', async () => {
const registry = new LeaseRegistry();
const lease = registry.allocateLease(HUMAN_CONTROL_LEASE_REQUEST);
const started = createControlLatch();
const finish = createControlLatch();
const request = humanControlRequest(lease, 'lease_allocate', []);
const requestId = 'held-canceled-allocation';
request.meta = { ...request.meta, requestId };
let providerReleased = false;
const mutation = handleLeaseCommands({
req: request,
sessionName: request.session,
sessionStore: makeSessionStore('agent-device-held-canceled-provider-'),
leaseRegistry: registry,
leaseLifecycleProvider: {
allocate: async () => {
started.resolve();
await finish.promise;
markRequestCanceled(requestId);
return {};
},
release: async () => {
assert.equal(registry.listHumanControlHolds({ kind: 'host' })[0]?.state, 'activating');
providerReleased = true;
return {};
},
},
});
await started.promise;
const activation = registry.putHumanControlHold({ kind: 'host' }, 'host', {
scope: HUMAN_CONTROL_SCOPE,
});
finish.resolve();
try {
await assert.rejects(
mutation,
(error: unknown) => error instanceof AppError && error.details?.released === true,
);
await activation;
assert.equal(providerReleased, true);
assert.equal(registry.listActiveLeases().length, 0);
} finally {
clearRequestCanceled(requestId);
}
});
function allocateRequest(): DaemonRequest {
return {
token: 'test-token',
session: 'lease-ttl-test',
command: 'lease_allocate',
positionals: [],
flags: {},
meta: {
tenantId: 'tenant-a',
runId: 'run-a',
clientId: 'client-a',
leaseBackend: 'android-instance',
leaseProvider: 'cloud',
},
};
}
// A hosted provider can spend longer creating its session than the lease's inactivity
// TTL. Stamping the TTL when the registry record is created handed the client a lease
// that was already expired, and the paid session behind it was orphaned.
test('a lease whose provider allocation outlasts its TTL is active when allocation returns', async () => {
let now = 0;
const registry = new LeaseRegistry({ now: () => now, defaultLeaseTtlMs: 60_000 });
const response = await handleLeaseCommands({
req: allocateRequest(),
sessionName: 'lease-ttl-test',
sessionStore: makeSessionStore('agent-device-slow-provider-'),
leaseRegistry: registry,
leaseLifecycleProvider: {
allocate: async (lease) => {
now = 80_000;
assert.deepEqual(
registry.consumeExpiredLeases(),
[],
'the sweeper must not reap a lease mid-allocation',
);
now = 90_000;
return { providerSessionId: `session-${lease.leaseId}` };
},
},
});
assert.equal(response?.ok, true);
const lease = (response?.ok ? response.data?.lease : undefined) as DeviceLease;
assert.equal(lease.expiresAt, 150_000);
assert.deepEqual(
registry.listActiveLeases().map((entry) => [entry.leaseId, entry.expiresAt]),
[[lease.leaseId, 150_000]],
);
now = 149_999;
registry.assertLeaseAdmission({
leaseId: lease.leaseId,
tenantId: lease.tenantId,
runId: lease.runId,
leaseBackend: lease.backend,
leaseProvider: lease.leaseProvider,
});
});
test('a lease allocated without a provider keeps the TTL it was created with', async () => {
const now = 5_000;
const registry = new LeaseRegistry({ now: () => now, defaultLeaseTtlMs: 60_000 });
const response = await handleLeaseCommands({
req: allocateRequest(),
sessionName: 'lease-ttl-test',
sessionStore: makeSessionStore('agent-device-no-provider-'),
leaseRegistry: registry,
});
assert.equal(response?.ok, true);
const lease = (response?.ok ? response.data?.lease : undefined) as DeviceLease;
assert.equal(lease.createdAt, 5_000);
assert.equal(lease.heartbeatAt, 5_000);
assert.equal(lease.expiresAt, 65_000);
assert.deepEqual(registry.listActiveLeases(), [lease]);
});
// The registry hands a run's repeat allocation the lease it already holds. A provider refusing the
// repeat request (a profile field it does not read) must leave that lease and its session alone.
test("a refused repeat allocation keeps the run's live lease", async () => {
const registry = new LeaseRegistry();
const sessionStore = makeSessionStore('agent-device-refused-repeat-');
let calls = 0;
const allocate = async (req: DaemonRequest) =>
await handleLeaseCommands({
req,
sessionName: 'lease-ttl-test',
sessionStore,
leaseRegistry: registry,
leaseLifecycleProvider: {
allocate: async () => {
calls += 1;
if (calls === 1) return { providerSessionId: 'session-1' };
throw new AppError('INVALID_ARGS', '--provider-os-version is not supported by Cloud.');
},
},
});
const first = await allocate(allocateRequest());
const lease = (first?.ok ? first.data?.lease : undefined) as DeviceLease;
const repeat = allocateRequest();
repeat.flags = { providerOsVersion: '18.0' };
await assert.rejects(
allocate(repeat),
(error: unknown) => error instanceof AppError && error.code === 'INVALID_ARGS',
);
assert.equal(calls, 2);
assert.deepEqual(
registry.listActiveLeases().map((entry) => entry.leaseId),
[lease.leaseId],
);
assert.equal(
registry.resolveProviderSession({
provider: lease.leaseProvider,
providerSessionId: 'session-1',
tenantId: lease.tenantId,
})?.leaseId,
lease.leaseId,
);
});
// A requester that hangs up during its repeat allocation will never release the lease it reused, so
// the provider rejecting with the cancellation must release that lease and its session.
test('a repeat allocation canceled by its requester releases the reused lease', async () => {
const registry = new LeaseRegistry();
const sessionStore = makeSessionStore('agent-device-canceled-repeat-');
const requestId = 'canceled-repeat-allocation';
const releasedSessions: unknown[] = [];
let calls = 0;
const allocate = async (req: DaemonRequest) =>
await handleLeaseCommands({
req,
sessionName: 'lease-ttl-test',
sessionStore,
leaseRegistry: registry,
leaseLifecycleProvider: {
allocate: async (_lease, context) => {
calls += 1;
if (calls === 1) return { providerSessionId: 'session-1' };
markRequestCanceled(requestId);
context?.signal?.throwIfAborted();
throw new Error('the request signal was not aborted');
},
release: async (released) => {
releasedSessions.push(released.leaseId);
return { providerSessionId: 'session-1' };
},
},
});
const first = await allocate(allocateRequest());
const lease = (first?.ok ? first.data?.lease : undefined) as DeviceLease;
const repeat = allocateRequest();
repeat.meta = { ...repeat.meta, requestId };
const registration = registerRequestAbort(requestId);
try {
await assert.rejects(
allocate(repeat),
(error: unknown) => error instanceof AppError && error.details?.released === true,
);
} finally {
clearRequestCanceled(requestId, registration);
}
assert.equal(calls, 2);
assert.deepEqual(releasedSessions, [lease.leaseId]);
assert.deepEqual(registry.listActiveLeases(), []);
});