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
151 changes: 151 additions & 0 deletions packages/daemon/src/server/__tests__/provider-lease-expiry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,125 @@ test('does not release until the expired lease record is durable', async () => {
}
});

test.each(['timer', 'drain', 'shutdown', 'persistent failure'] as const)(
'%s retires a stale recovery record after provider confirmation',
async (retry) => {
vi.useFakeTimers();
const stateDir = mkdtempForTestSync('agent-device-expired-provider-lease-');
const recordPath = path.join(stateDir, 'expired-provider-leases.json');
const lease = new LeaseRegistry().allocateLease({
tenantId: 'tenant-a',
runId: 'run-1',
leaseProvider: 'limrun',
});
const removeFile = fs.rmSync;
const remove = vi.spyOn(fs, 'rmSync');
const recoverExpiredLease = vi.fn(async () => {
remove.mockImplementation((file, options) => {
if (file === recordPath) throw new Error('temporary disk failure');
removeFile(file, options);
});
});
const releaser = createExpiredProviderLeaseReleaser({
recoverExpiredLease,
stateDir,
recoverableProviderIds: ['limrun'],
retryDelayMs: 10,
});

try {
releaser.beginShutdown();
await expect(releaser.release(lease)).resolves.toEqual({ status: 'released' });
expect(JSON.parse(fs.readFileSync(recordPath, 'utf8')).leases).toEqual([lease]);

if (retry === 'persistent failure') {
await vi.advanceTimersByTimeAsync(10);
expect(fs.existsSync(recordPath)).toBe(true);
expect(vi.getTimerCount()).toBe(0);
}
if (retry !== 'shutdown') remove.mockRestore();
if (retry === 'timer') {
await vi.advanceTimersByTimeAsync(10);
expect(fs.existsSync(recordPath)).toBe(false);
}
expect(await releaser.drain(10)).toEqual({ pending: [], unknown: [], released: [lease] });
expect(fs.existsSync(recordPath)).toBe(retry === 'shutdown');

remove.mockRestore();
releaser.shutdown();
expect(fs.existsSync(recordPath)).toBe(false);
expect(recoverExpiredLease).toHaveBeenCalledExactlyOnceWith(lease);
expect(vi.getTimerCount()).toBe(0);
} finally {
remove.mockRestore();
releaser.shutdown();
vi.useRealTimers();
fs.rmSync(stateDir, { recursive: true, force: true });
}
},
);

test.each(['before handoff', 'after handoff'] as const)(
'a recovery confirmation %s cannot leave disk work running past registration',
async (confirmation) => {
vi.useFakeTimers();
const stateDir = mkdtempForTestSync('agent-device-expired-provider-lease-');
const recordPath = path.join(stateDir, 'expired-provider-leases.json');
const lease = new LeaseRegistry().allocateLease({
tenantId: 'tenant-a',
runId: 'run-1',
leaseProvider: 'limrun',
});
const release = Promise.withResolvers<void>();
const recoverExpiredLease = vi.fn(() => release.promise);
const releaser = createExpiredProviderLeaseReleaser({
recoverExpiredLease,
stateDir,
recoverableProviderIds: ['limrun'],
retryDelayMs: 10,
});

try {
releaser.beginShutdown();
const admitted = releaser.release(lease);
const drained = releaser.drain(10);
await vi.advanceTimersByTimeAsync(10);
expect(await drained).toEqual({ pending: [lease], unknown: [lease], released: [] });
releaser.shutdown();

if (confirmation === 'before handoff') {
const removeFile = fs.rmSync;
const remove = vi.spyOn(fs, 'rmSync').mockImplementation((file, options) => {
if (file === recordPath) throw new Error('temporary disk failure');
removeFile(file, options);
});
try {
release.resolve();
await expect(admitted).resolves.toEqual({ status: 'released' });
expect(fs.existsSync(recordPath)).toBe(true);
} finally {
remove.mockRestore();
}
releaser.finishPersistence({ retainRegistration: false });
expect(fs.existsSync(recordPath)).toBe(false);
} else {
releaser.finishPersistence({ retainRegistration: false });
const inheritedRecord = fs.readFileSync(recordPath, 'utf8');
release.resolve();
await expect(admitted).resolves.toEqual({ status: 'released' });
expect(fs.readFileSync(recordPath, 'utf8')).toBe(inheritedRecord);
}
expect(vi.getTimerCount()).toBe(0);
expect(recoverExpiredLease).toHaveBeenCalledExactlyOnceWith(lease);
} finally {
releaser.shutdown();
release.resolve();
vi.useRealTimers();
fs.rmSync(stateDir, { recursive: true, force: true });
}
},
);

test('shutdown drain reports releases completed before and during its final retry', async () => {
const leaseRegistry = new LeaseRegistry();
const releasedBeforeShutdown = leaseRegistry.allocateLease({
Expand Down Expand Up @@ -325,6 +444,38 @@ test('a daemon killed while holding a provider lease recovers it on restart', as
}
});

test('restart recovers a lease in both records once using the expired record', async () => {
const stateDir = mkdtempForTestSync('agent-device-live-provider-lease-');
const live = new LeaseRegistry().allocateLease({
tenantId: 't',
runId: 'run-1',
leaseProvider: 'revyl',
});
const expired = { ...live, expiresAt: live.expiresAt + 1_000 };
const journalPath = path.join(stateDir, 'live-provider-leases.json');
const expiredPath = path.join(stateDir, 'expired-provider-leases.json');
const recoverExpiredLease = vi.fn(async (_lease: DeviceLease) => undefined);
const restartedDaemon = createExpiredProviderLeaseReleaser({
recoverExpiredLease,
stateDir,
recoverableProviderIds: ['revyl'],
});

try {
fs.writeFileSync(journalPath, JSON.stringify({ version: 1, leases: [live] }));
fs.writeFileSync(expiredPath, JSON.stringify({ version: 1, leases: [expired] }));

await restartedDaemon.recoverInherited();

expect(recoverExpiredLease.mock.calls).toEqual([[expired]]);
expect(fs.existsSync(journalPath)).toBe(false);
expect(fs.existsSync(expiredPath)).toBe(false);
} finally {
restartedDaemon.shutdown();
fs.rmSync(stateDir, { recursive: true, force: true });
}
});

test('a provider lease released before the daemon stops is not recovered again', async () => {
const stateDir = mkdtempForTestSync('agent-device-live-provider-lease-');
const recoverExpiredLease = vi.fn(async (_lease: DeviceLease) => undefined);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { afterEach, test, vi } from 'vitest';
import type { DeviceLease } from '@agent-device/contracts/device';

Expand Down Expand Up @@ -41,8 +42,12 @@ vi.mock('../request-execution-scope.ts', async (importOriginal) => {
});

import { SessionStore } from '../../core/session-store.ts';
import { daemonRuntimeDepsFixture } from '../../__tests__/support/daemon-runtime-deps-fixture.ts';
import {
applicationLifecycleResourceFixture,
daemonRuntimeDepsFixture,
} from '../../__tests__/support/daemon-runtime-deps-fixture.ts';
import { startDaemonRuntime } from './daemon-runtime.ts';
import { lifecycleDeviceRuntimeGateway } from '../../__tests__/support/test-device-runtime-gateway.ts';
import { mkdtempForTestSync, createTestHostEnvironment } from '@agent-device/test-kit';

afterEach(() => {
Expand Down Expand Up @@ -159,6 +164,69 @@ test('a lease that expires after shutdown is refused and reported, not sent to i
}
});

test('a late provider confirmation retires the lease record when close retains registration', async () => {
vi.useFakeTimers();
const stateDir = mkdtempForTestSync('agent-device-daemon-retained-registration-');
const expiredRecord = path.join(stateDir, 'expired-provider-leases.json');
const provider = Promise.withResolvers<void>();
const recoverExpiredLease = vi.fn(() => provider.promise);
try {
const runtime = await startDaemonRuntime({
composeDeps: daemonRuntimeDepsFixture({
recoverExpiredLease,
recoverableProviderIds: ['limrun'],
deviceRuntimeGateway: Object.freeze({
...lifecycleDeviceRuntimeGateway,
applicationLifecycle: applicationLifecycleResourceFixture(),
shutdown: async () => {
throw new Error('platform owner could not close');
},
}),
}),
host: createTestHostEnvironment({
env: {
...process.env,
AGENT_DEVICE_STATE_DIR: stateDir,
AGENT_DEVICE_DAEMON_SERVER_MODE: 'http',
AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0',
AGENT_DEVICE_LEASE_MIN_TTL_MS: '1',
},
}),
stderr: { write: () => {} },
stdout: { write: () => {} },
});
assert.ok(runtime);
const [registry] = leaseProbe.registries;
assert.ok(registry);
const lease = registry.allocateLease({
tenantId: 'tenant-a',
runId: 'run-1',
leaseProvider: 'limrun',
ttlMs: 10,
});
await vi.advanceTimersByTimeAsync(11);
registry.consumeExpiredLease(lease.leaseId);
assert.equal(recoverExpiredLease.mock.calls.length, 1);

const closing = runtime.close();
await vi.runAllTimersAsync();
const report = await closing;
assert.equal(report.platformOwners, 'failed');
assert.deepEqual(report.providerReleases.unknown, [lease.leaseId]);
assert.ok(fs.existsSync(path.join(stateDir, 'daemon.lock')));
assert.ok(fs.existsSync(expiredRecord));

provider.resolve();
await vi.advanceTimersByTimeAsync(0);
assert.equal(fs.existsSync(expiredRecord), false);
assert.equal(recoverExpiredLease.mock.calls.length, 1);
} finally {
provider.resolve();
vi.useRealTimers();
fs.rmSync(stateDir, { recursive: true, force: true });
}
});

test('shutdown cancels and drains lease ends before it tears sessions down', async () => {
const closeAdmission = SessionStore.prototype.closeAdmission;
vi.spyOn(SessionStore.prototype, 'closeAdmission').mockImplementation(
Expand Down
11 changes: 9 additions & 2 deletions packages/daemon/src/server/http/daemon-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,7 @@ async function startDaemonRuntimeOnHost(
await deps.ownerLifecycle.clearDaemonLockConfiguration();
});
rollback.onRollback(async () => {
expiredProviderLeaseReleaser.finishPersistence({ retainRegistration: false });
await finishDaemonRegistration({
registration,
infoPath,
Expand Down Expand Up @@ -876,18 +877,24 @@ async function startDaemonRuntimeOnHost(
settleWithin(async () => await releasePngWorker(), DAEMON_PNG_WORKER_TERMINATE_TIMEOUT_MS),
Promise.resolve().then(() => pluginClose.close()),
]);
const retainRegistration = hasUnfinishedWork();
await Promise.allSettled([
withDaemonDiagnosticsScope({ logPath }, async () => {
expiredProviderLeaseReleaser.finishPersistence({ retainRegistration });
}),
]);
await Promise.allSettled([
finishDaemonRegistration({
registration,
infoPath,
logPath,
outcome: shutdownOutcome,
close: {
retainRegistration: hasUnfinishedWork(),
retainRegistration,
},
}),
]);
if (!hasUnfinishedWork()) {
if (!retainRegistration) {
try {
await deps.ownerLifecycle.clearDaemonLockConfiguration();
} catch {}
Expand Down
Loading
Loading