Skip to content

Commit a037cd6

Browse files
committed
fix: retire only the captured expired session lifetime
1 parent 0780e5e commit a037cd6

5 files changed

Lines changed: 157 additions & 64 deletions

File tree

‎src/daemon/__tests__/lease-lifecycle.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,9 @@ test('cleanupExpiredLeasedSession consumes expired lease and deletes the session
8383
});
8484

8585
expect(cleaned).toBe(true);
86-
expect(teardownSession).toHaveBeenCalledWith(session, 'default');
86+
expect(teardownSession).toHaveBeenCalledWith(
87+
expect.objectContaining({ address: 'default', session }),
88+
);
8789
expect(sessionStore.get('default')).toBeUndefined();
8890
expect(leaseRegistry.listActiveLeases()).toHaveLength(0);
8991
});
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import { expect, test, vi } from 'vitest';
2+
import { makeSession } from '../../__tests__/test-utils/session-factories.ts';
3+
import { LINUX_DEVICE } from '../../__tests__/test-utils/device-fixtures.ts';
4+
import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
5+
import { LeaseRegistry } from '../lease-registry.ts';
6+
import { createRequestExecutionScope } from '../request-execution-scope.ts';
7+
import type { DaemonRequest } from '../daemon-request.ts';
8+
9+
function makeRequest(overrides: Partial<DaemonRequest>): DaemonRequest {
10+
return {
11+
token: 't',
12+
session: 'default',
13+
command: 'snapshot',
14+
positionals: [],
15+
flags: {},
16+
...overrides,
17+
};
18+
}
19+
20+
test('expired leases remove owned sessions before the next command and free capacity', async () => {
21+
let now = 1_000;
22+
const sessionStore = makeSessionStore('agent-device-request-scope-');
23+
const leaseRegistry = new LeaseRegistry({
24+
maxActiveSimulatorLeases: 1,
25+
defaultLeaseTtlMs: 10,
26+
minLeaseTtlMs: 1,
27+
now: () => now,
28+
});
29+
const lease = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' });
30+
sessionStore.set(
31+
'default',
32+
makeSession('default', {
33+
device: LINUX_DEVICE,
34+
lease: {
35+
leaseId: lease.leaseId,
36+
tenantId: lease.tenantId,
37+
runId: lease.runId,
38+
leaseBackend: lease.backend,
39+
leaseProvider: 'proxy',
40+
deviceKey: 'ios:SIM-001',
41+
expiresAt: lease.expiresAt,
42+
},
43+
}),
44+
);
45+
now = 1_011;
46+
47+
const scope = await createRequestExecutionScope({
48+
req: makeRequest({ command: 'snapshot' }),
49+
sessionStore,
50+
leaseRegistry,
51+
});
52+
await scope.runLocked(async () => 'ran');
53+
54+
expect(sessionStore.get('default')).toBeUndefined();
55+
const nextLease = leaseRegistry.allocateLease({ tenantId: 'tenant-b', runId: 'run-2' });
56+
expect(nextLease.tenantId).toBe('tenant-b');
57+
});
58+
59+
test.each(['rebuild', 'retire'] as const)(
60+
'scoped lease expiry preserves a public-name session and a %s during held teardown',
61+
async (change) => {
62+
let now = 1_000;
63+
const store = makeSessionStore('request-scope-lease-lifetime-');
64+
const leases = new LeaseRegistry({ defaultLeaseTtlMs: 10, minLeaseTtlMs: 1, now: () => now });
65+
const lease = leases.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' });
66+
const address = 'cwd:ownership:default';
67+
const original = store.publish(
68+
address,
69+
makeSession('default', {
70+
device: LINUX_DEVICE,
71+
sessionScope: { kind: 'cwd', id: 'ownership' },
72+
lease: {
73+
leaseId: lease.leaseId,
74+
tenantId: lease.tenantId,
75+
runId: lease.runId,
76+
leaseBackend: lease.backend,
77+
},
78+
}),
79+
);
80+
const decoy = store.publish(
81+
'default',
82+
makeSession('default', {
83+
device: { ...LINUX_DEVICE, id: 'public-name-decoy' },
84+
appName: 'decoy',
85+
}),
86+
);
87+
let enter!: () => void;
88+
let resume!: () => void;
89+
const entered = new Promise<void>((resolve) => {
90+
enter = resolve;
91+
});
92+
const release = new Promise<void>((resolve) => {
93+
resume = resolve;
94+
});
95+
const stopSnapshotHelper = vi.fn(async () => {
96+
enter();
97+
await release;
98+
});
99+
now = 1_011;
100+
const scope = await createRequestExecutionScope({
101+
req: makeRequest({ session: address, flags: { session: address } }),
102+
sessionStore: store,
103+
leaseRegistry: leases,
104+
platformResourceCleanup: {
105+
stopSnapshotHelper,
106+
closeManagedBrowser: async () => {},
107+
cleanupSessionlessExecutionHost: async () => {},
108+
retainExecutionHostAfterClose: () => false,
109+
},
110+
});
111+
expect(scope.sessionName).toBe(address);
112+
const running = scope.runLocked(async () => 'ran');
113+
await entered;
114+
let successor: ReturnType<typeof store.publish> | undefined;
115+
if (change === 'retire') {
116+
store.retire(original);
117+
successor = store.publish(
118+
address,
119+
makeSession('default', {
120+
device: { ...LINUX_DEVICE, id: 'successor' },
121+
appName: 'successor',
122+
}),
123+
);
124+
} else store.update(original, { appName: 'latest' });
125+
resume();
126+
await expect(running).resolves.toBe('ran');
127+
expect(stopSnapshotHelper).toHaveBeenCalledExactlyOnceWith(original.session.device);
128+
expect(store.requireCurrent(decoy)).toBe(decoy.session);
129+
if (successor) expect(store.requireCurrent(successor)).toBe(successor.session);
130+
else expect(store.lookup(address)).toBeUndefined();
131+
},
132+
);

‎src/daemon/__tests__/request-execution-scope.test.ts‎

Lines changed: 0 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,7 @@ import {
99
import {
1010
makeAndroidSession,
1111
makeIosSession,
12-
makeSession,
1312
} from '../../__tests__/test-utils/session-factories.ts';
14-
import { LINUX_DEVICE } from '../../__tests__/test-utils/device-fixtures.ts';
1513
import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
1614
import { LeaseRegistry } from '../lease-registry.ts';
1715
import { clearRequestCanceled, markRequestCanceled } from '@agent-device/host-kit/request';
@@ -497,45 +495,6 @@ test('provider lease admission succeeds without a device key', async () => {
497495
expect(scope.sessionName).toBe('default');
498496
});
499497

500-
test('expired leases remove owned sessions before the next command and free capacity', async () => {
501-
let now = 1_000;
502-
const sessionStore = makeSessionStore('agent-device-request-scope-');
503-
const leaseRegistry = new LeaseRegistry({
504-
maxActiveSimulatorLeases: 1,
505-
defaultLeaseTtlMs: 10,
506-
minLeaseTtlMs: 1,
507-
now: () => now,
508-
});
509-
const lease = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' });
510-
sessionStore.set(
511-
'default',
512-
makeSession('default', {
513-
device: LINUX_DEVICE,
514-
lease: {
515-
leaseId: lease.leaseId,
516-
tenantId: lease.tenantId,
517-
runId: lease.runId,
518-
leaseBackend: lease.backend,
519-
leaseProvider: 'proxy',
520-
deviceKey: 'ios:SIM-001',
521-
expiresAt: lease.expiresAt,
522-
},
523-
}),
524-
);
525-
now = 1_011;
526-
527-
const scope = await createRequestExecutionScope({
528-
req: makeRequest({ command: 'snapshot' }),
529-
sessionStore,
530-
leaseRegistry,
531-
});
532-
await scope.runLocked(async () => 'ran');
533-
534-
expect(sessionStore.get('default')).toBeUndefined();
535-
const nextLease = leaseRegistry.allocateLease({ tenantId: 'tenant-b', runId: 'run-2' });
536-
expect(nextLease.tenantId).toBe('tenant-b');
537-
});
538-
539498
// A lease renewed only at admission lets one command slower than its inactivity TTL
540499
// expire the lease paying for the device it is using, and expiry then tears the
541500
// provider session down under the client still waiting for that same command. Found

‎src/daemon/lease-lifecycle.ts‎

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@ import {
1414
} from './request-admission.ts';
1515
import type { SessionStore } from './session-store.ts';
1616
import type { DaemonRequest } from './daemon-request.ts';
17-
import type { SessionState } from './session-state.ts';
17+
import type { SessionRef, SessionState } from './session-state.ts';
1818
import { providerSessionIdFromData } from './provider-session-ownership.ts';
1919

2020
export type ExpiredProviderLeaseRecovery = (lease: DeviceLease) => Promise<void>;
2121

22-
export type SessionTeardown = (session: SessionState, sessionName: string) => Promise<void>;
22+
export type SessionTeardown = (ref: SessionRef) => Promise<void>;
2323

2424
export async function releaseExpiredProviderLease(
2525
recoverExpiredLease: ExpiredProviderLeaseRecovery | undefined,
@@ -62,9 +62,10 @@ export async function cleanupExpiredLeasedSession(params: {
6262
leaseRegistry: LeaseRegistry;
6363
teardownSession: SessionTeardown;
6464
}): Promise<boolean> {
65-
const session = params.sessionStore.get(params.sessionName);
65+
const ref = params.sessionStore.lookup(params.sessionName);
66+
const session = ref?.session;
6667
const lease = session?.lease;
67-
if (!session || !lease) return false;
68+
if (!ref || !session || !lease) return false;
6869
const expiredLease = params.leaseRegistry.consumeExpiredLease(lease.leaseId);
6970
if (!expiredLease) return false;
7071
emitDiagnostic({
@@ -77,7 +78,7 @@ export async function cleanupExpiredLeasedSession(params: {
7778
deviceKey: lease.deviceKey,
7879
},
7980
});
80-
await params.teardownSession(session, session.name).catch((error) => {
81+
await params.teardownSession(ref).catch((error) => {
8182
emitDiagnostic({
8283
level: 'debug',
8384
phase: 'leased_session_expiry_cleanup_failed',
@@ -100,7 +101,7 @@ export async function cleanupExpiredLeasedSession(params: {
100101
},
101102
});
102103
});
103-
params.sessionStore.delete(session.name);
104+
params.sessionStore.retire(ref);
104105
return true;
105106
}
106107

@@ -112,7 +113,8 @@ export function admitRequestLeaseForLockedScope(params: {
112113
providerAppCatalog?: ProviderAppCatalog;
113114
}): DaemonRequest {
114115
const { sessionName, sessionStore, leaseRegistry } = params;
115-
const existingSession = sessionStore.get(sessionName);
116+
const ref = sessionStore.lookup(sessionName);
117+
const existingSession = ref?.session;
116118
const activeLease = assertRequestLeaseAdmission(params.req, leaseRegistry, existingSession, {
117119
providerAppCatalog: params.providerAppCatalog,
118120
});
@@ -125,15 +127,14 @@ export function admitRequestLeaseForLockedScope(params: {
125127
admittedLease: activeLease,
126128
},
127129
};
128-
if (existingSession?.lease) {
129-
sessionStore.set(sessionName, {
130-
...existingSession,
130+
if (ref && existingSession?.lease) {
131+
sessionStore.update(ref, (current) => ({
131132
lease: {
132-
...existingSession.lease,
133+
...current.lease!,
133134
leaseBackend: activeLease.backend,
134135
expiresAt: activeLease.expiresAt,
135136
},
136-
});
137+
}));
137138
}
138139
return nextReq;
139140
}

‎src/daemon/request-execution-scope.ts‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ import type { LeaseRegistry } from './lease-registry.ts';
4545
import { type SessionStore } from './session-store.ts';
4646
import { resolveSessionRequestLog, resolveSessionRunnerLogPath } from './session-artifact-paths.ts';
4747
import type { DaemonRequest, DaemonResponse } from './daemon-request.ts';
48-
import type { SessionState } from './session-state.ts';
48+
import type { SessionRef, SessionState } from './session-state.ts';
4949
import { teardownSessionResources } from './session-teardown.ts';
5050
import { finalizeBoundSessionApplicationLifecycle } from './application-lifecycle-recovery.ts';
5151
import { runtimeHintValues } from './session-runtime.ts';
@@ -273,10 +273,9 @@ export async function createRequestExecutionScope(params: {
273273
sessionName,
274274
sessionStore,
275275
leaseRegistry,
276-
teardownSession: async (session, expiredSessionName) =>
276+
teardownSession: async (ref) =>
277277
await teardownExpiredSession({
278-
session,
279-
sessionName: expiredSessionName,
278+
ref,
280279
sessionStore,
281280
inspectFacts: scope.inspectFacts,
282281
bindDevice: scope.bindDevice,
@@ -410,16 +409,16 @@ function createRequestDeviceAccess(params: {
410409
}
411410

412411
async function teardownExpiredSession(params: {
413-
session: SessionState;
414-
sessionName: string;
412+
ref: SessionRef;
415413
sessionStore: SessionStore;
416414
inspectFacts: InspectDeviceRuntimeFacts;
417415
bindDevice: BindDeviceRuntime;
418416
platformCleanup: PlatformResourceCleanup;
419417
}): Promise<void> {
420-
const { session, sessionName, sessionStore, inspectFacts, bindDevice, platformCleanup } = params;
421-
const ref = sessionStore.lookup(sessionName);
422-
if (!ref) return;
418+
const { ref, sessionStore, inspectFacts, bindDevice, platformCleanup } = params;
419+
const session = sessionStore.resolveCurrent(ref) ?? ref.session;
420+
const sessionName = ref.address;
421+
const runtimeHints = runtimeHintValues(sessionStore.getRuntimeHints(ref.address));
423422
let primaryError: unknown;
424423
try {
425424
await teardownSessionResources({
@@ -437,7 +436,7 @@ async function teardownExpiredSession(params: {
437436
bindDevice,
438437
session,
439438
stateDir: sessionStore.resolveDaemonStateDir(),
440-
runtimeHints: runtimeHintValues(sessionStore.getRuntimeHints(sessionName)),
439+
runtimeHints,
441440
});
442441
} catch (cleanupError) {
443442
if (primaryError !== undefined) {

0 commit comments

Comments
 (0)