Skip to content

Commit dce5c56

Browse files
thymikeeclaude
andcommitted
fix(provision-kit): stop a late rental even when a driver's error factory throws
When a late start answer lands on an ending lease, the table builds the waiters' error with the driver's `releasing()` before it runs the follow-up teardown that stops the late rental. A driver whose factory threw skipped that teardown and left the device rented. The failure is now built inside a guard, and the follow-up teardown always runs. Tests: a start that fails 50 ms in answers its caller at once, stops what it rented and frees the lease for a new allocation; and a driver whose `releasing()` throws still has a late answer's device stopped. The table test that the seeded sweep's stop-overlap check covers is folded in, and the table's type docs are condensed to stay within the change's budget. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 0c401f9 commit dce5c56

2 files changed

Lines changed: 45 additions & 45 deletions

File tree

‎packages/provision-kit/src/provider-lease-table.test.ts‎

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ function deferred<T>(): Deferred<T> {
3636
* A provider whose starts and stops the test answers by hand. Each start waits on `starts`, each stop on
3737
* the next queued answer when one is queued, and every call is recorded.
3838
*/
39-
function fakeProvider(options: { startTimeoutMs?: number; stopTimeoutMs?: number } = {}) {
39+
function fakeProvider(
40+
options: { startTimeoutMs?: number; stopTimeoutMs?: number; releasingThrows?: boolean } = {},
41+
) {
4042
const controls: Array<ProviderLeaseStartControl<Handle>> = [];
4143
const stopped: string[] = [];
4244
const found: string[] = [];
@@ -65,7 +67,10 @@ function fakeProvider(options: { startTimeoutMs?: number; stopTimeoutMs?: number
6567
},
6668
shuttingDown: (lease) =>
6769
new TableError({ reason: 'runtime-shutting-down', leaseId: lease.leaseId }),
68-
releasing: (lease) => new TableError({ reason: 'lease-releasing', leaseId: lease.leaseId }),
70+
releasing: (lease) => {
71+
if (options.releasingThrows) throw new Error('driver bug');
72+
return new TableError({ reason: 'lease-releasing', leaseId: lease.leaseId });
73+
},
6974
gaveUp: (lease, caller, budgetMs, rented) =>
7075
new TableError({
7176
reason: caller.signal?.aborted ? 'request_canceled' : 'provider-not-ready',
@@ -404,14 +409,32 @@ test('a failed start is stopped before its failure reaches the caller', async ()
404409
});
405410
});
406411

407-
test('a start that rejects is cleaned up by the handle the provider finds for its lease', async () => {
408-
const provider = fakeProvider();
412+
test('a start that fails answers its caller at once, stops what it rented, and frees the lease', async () => {
413+
const provider = fakeProvider({ startTimeoutMs: 60_000 });
409414
const allocating = provider.table.allocate(lease(), {});
410415
await settle();
411-
provider.failStart(0, new Error('lost answer'));
416+
const startedAt = Date.now();
417+
setTimeout(() => provider.failStart(0, new Error('lost answer')), 50);
412418
await assert.rejects(allocating, /lost answer/);
419+
assert.ok(Date.now() - startedAt < 1_000, 'the failure is not held to the start timeout');
413420
assert.deepEqual(provider.found, ['lease-1']);
414421
assert.deepEqual(provider.stopped, ['found-lease-1']);
422+
// The stop is confirmed, so no entry is left: a new allocation starts afresh.
423+
const fresh = provider.table.allocate(lease(), {});
424+
await settle();
425+
provider.answerStart(1, ready('session-2'));
426+
assert.deepEqual(await fresh, { id: 'session-2' });
427+
});
428+
429+
test("a driver whose releasing() throws still has a late answer's device stopped", async () => {
430+
const provider = fakeProvider({ startTimeoutMs: 30, releasingThrows: true });
431+
void provider.table.allocate(lease(), {}).catch(() => undefined);
432+
await settle();
433+
await assert.rejects(provider.table.release('lease-1'), reason('provider-cleanup-pending'));
434+
provider.answerStart(0, ready('late'));
435+
await settle();
436+
await settle();
437+
assert.deepEqual(provider.stopped, ['late']);
415438
});
416439

417440
test('a lost start answer the provider cannot find keeps the lease until a retry finds it', async () => {
@@ -469,22 +492,6 @@ test('a published rental is stopped when its start stalls, and the late answer e
469492
assert.deepEqual(provider.stopped, ['instance-1']);
470493
});
471494

472-
test('a stop that outlives its budget is joined by the retry instead of sent twice', async () => {
473-
const provider = fakeProvider({ stopTimeoutMs: 20 });
474-
await allocated(provider);
475-
const stop = deferred<void>();
476-
provider.queueStop(async () => await stop.promise);
477-
478-
await assert.rejects(
479-
provider.table.release('lease-1'),
480-
reason('provider-cleanup-pending', 'release'),
481-
);
482-
const retry = provider.table.release('lease-1');
483-
stop.resolve();
484-
assert.equal((await retry)?.handle.id, 'session-1');
485-
assert.deepEqual(provider.stopped, ['session-1']);
486-
});
487-
488495
test('a rental named while an earlier stop is still in flight waits for that stop to confirm', async () => {
489496
const provider = fakeProvider({ startTimeoutMs: 30, stopTimeoutMs: 20 });
490497
const allocating = provider.table.allocate(lease(), {});

‎packages/provision-kit/src/provider-lease-table.ts‎

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@ export type ProviderLeaseBudget = Readonly<{ signal?: AbortSignal; deadline?: nu
1414

1515
export type ProviderLeaseAllocateOptions<Request> = ProviderLeaseBudget &
1616
Readonly<{
17-
/**
18-
* Refuses to join a start made for `started` when this allocation asks for something else. Throw the
19-
* refusal; the table calls this before the allocation joins anything.
20-
*/
17+
/** Throws to refuse joining a start made for another request; called before anything is joined. */
2118
requireJoinable?(started: Request): void;
2219
}>;
2320

@@ -30,19 +27,16 @@ export type ProviderLeaseStartControl<Handle> = Readonly<{
3027
/** Epoch-ms by which the start should answer: `startTimeoutMs` after it was sent. */
3128
deadline: number;
3229
/**
33-
* Publishes a rental as soon as the provider can stop it, before the start answers, so a release or a
34-
* drain can stop a device whose start stalls. A later call with another handle adds a rental; the table
35-
* stops every one it was told of. Do not publish a handle whose stop could arrive before the provider
36-
* created the session it names.
30+
* Publishes a rental the provider can already stop, before the start answers; the table stops every
31+
* rental it is told of. Never publish a handle whose stop could arrive before its session exists.
3732
*/
3833
rented(handle: Handle): void;
3934
}>;
4035

4136
/**
42-
* What one start amounted to. A ready start hands over its session and the handle that stops it. A failed
43-
* start names in `rented` what it left under rent; omitting it says the start rented nothing beyond what
44-
* it published through `rented`, which the table still stops. A start that rejects instead is read as one that may
45-
* have rented, and the table stops the published handle or what `findByLease` names.
37+
* What one start amounted to: a ready session and its handle, or a failure naming in `rented` what it
38+
* left rented beyond what it published. A rejection may have rented; the table stops what is published
39+
* or what `findByLease` names.
4640
*/
4741
export type ProviderLeaseStart<Session, Handle> =
4842
| Readonly<{ status: 'ready'; session: Session; handle: Handle }>
@@ -53,10 +47,7 @@ export type ProviderLeaseCleanupScope =
5347
| Readonly<{ route: 'start' | 'release' | 'recover'; leaseId: string }>
5448
| Readonly<{ route: 'shutdown' }>;
5549

56-
/**
57-
* A rental that stays rented, and why. `handle` is absent when the provider could not name the rental,
58-
* because the start never answered or `findByLease` failed.
59-
*/
50+
/** A rental that stays rented, and why; `handle` is absent when nobody could name it yet. */
6051
export type ProviderUnconfirmedStop<Handle> = Readonly<{
6152
leaseId: string;
6253
handle: Handle | undefined;
@@ -70,9 +61,7 @@ export type ProviderLeaseDriver<Session, Handle, Request> = Readonly<{
7061
*/
7162
startTimeoutMs: number;
7263
/**
73-
* How long one teardown waits for a stop to answer. A stop that outlives it is reported as unconfirmed,
74-
* and the next teardown joins the same stop instead of sending a second one. Unset waits for the answer.
75-
* Only the stop is bounded here; `findByLease` answers within the provider's own request budget.
64+
* How long a teardown waits for one stop; a later teardown joins a stop that outlived it. Unset waits.
7665
*/
7766
stopTimeoutMs?: number;
7867
start(
@@ -84,10 +73,7 @@ export type ProviderLeaseDriver<Session, Handle, Request> = Readonly<{
8473
stop(handle: Handle): Promise<void>;
8574
/** Identifies a rental, so one rental is stopped once whichever route named it. */
8675
handleKey(handle: Handle): string;
87-
/**
88-
* Names what a lease rented when the table cannot, as after a daemon restart or a start that rejected.
89-
* Rejects when the provider cannot name it, which keeps the lease pending for a later retry.
90-
*/
76+
/** Names what a lease rented after a restart or a rejected start; rejecting keeps the lease pending. */
9177
findByLease(lease: DeviceLease): Promise<Handle>;
9278
/** The error for an allocation that arrives or finishes while the runtime shuts down. */
9379
shuttingDown(lease: DeviceLease): Error;
@@ -402,7 +388,14 @@ class LeaseTable<Session, Handle, Request> {
402388
return { status: 'ready', session: answer.session };
403389
}
404390
}
405-
return await this.endFailedStart(entry, this.startFailure(entry, answer, caller, startedAt));
391+
let failure: unknown;
392+
try {
393+
failure = this.startFailure(entry, answer, caller, startedAt);
394+
} catch (error) {
395+
// A driver whose error factory throws must not keep a rented device from being stopped.
396+
failure = error;
397+
}
398+
return await this.endFailedStart(entry, failure);
406399
}
407400

408401
/** The start's answer, with a rejection read as an answer that may have rented. */

0 commit comments

Comments
 (0)