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
4 changes: 2 additions & 2 deletions src/core/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic
physical one. Physical not present: wait `health.probeIntervalMs`, not counted.
5. **Cleanup** — `CleanupReaper` on `lease.released`, `daemon.started`, `disk.pressure-detected`, a
tick. `idle-shutdown`: leased once, `ready`, idle past T1, not warm-targeted. `idle-destroy`:
`shutdown`, idle (lease end, else `shutdownAt`) past T2, or T1 under disk pressure.
`CleanupExecutor` revalidates, acts under `cleanup`, emits `cleanup.executed`.
`shutdown`, idle (lease end, else `shutdownAt`) past T2, or T1 under pressure. `CleanupExecutor`
revalidates, acts, emits `cleanup.executed`; a throwing action is logged, the run goes on.
6. **Nuke** — one at a time: close acquisition, settle reclaim and warm pool → release all leases
`killed` → shut down each unleased `ready` virtual device; with delete, destroy each `shutdown` one.
7. **Startup** — `readStartup` (`listManaged` per driver, parallel) → `doctor.reconcile({ read })`
Expand Down
127 changes: 126 additions & 1 deletion src/core/reaper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ async function createHarness(
...(options.tickMs === undefined ? {} : { tickMs: options.tickMs }),
});

return { clock, driver, engine, eventBus, filesystem, reaper, registry };
return { clock, driver, engine, eventBus, executor, filesystem, reaper, registry };
}

async function seedReady(harness: Awaited<ReturnType<typeof createHarness>>) {
Expand Down Expand Up @@ -558,6 +558,131 @@ describe("CleanupReaper", () => {
harness.reaper.dispose();
});

it("does not abort its run on a device whose platform has no driver, and still cleans up every device proposed after it", async () => {
const harness = await createHarness(automaticCleanupRules);
// why: the driverless records are registered first so the proposals that must throw precede
// the healthy ones -- that order is what a whole-run abort turns on. Only an ios driver is
// registered, so acting on an android record throws NoDriverError, as it does for a platform
// discovery refused. The ready one exercises the shutdown path, the shut-down one the
// destroy path; a healthy device follows each.
const ghostReady = await harness.registry.registerDevice({
driverData: {},
driverDeviceId: "ghost-ready-android",
provisionDuration: 0,
spec: { model: "Pixel 8", osVersion: "35", physical: false, platform: "android" },
});
await harness.registry.transitionDevice(ghostReady.id, "ready", {
event: "device.ready",
payload: { bootDuration: 0, deviceId: ghostReady.id },
});
const ghostReadyLease = await harness.registry.createLease({
deviceId: ghostReady.id,
ownerId: "agent-1",
requesterId: "agent-1",
ttlMs: 60_000,
ttlDeadline: 2_000,
});
await harness.registry.beginRelease(ghostReadyLease.id);
await harness.registry.transitionDevice(ghostReady.id, "ready", {
event: "device.reclaimed",
payload: { deviceId: ghostReady.id, duration: 0, strategy: "erase" },
});
const idleReady = await seedReleased(harness, "ready");
const ghostShutdown = await harness.registry.registerDevice({
driverData: {},
driverDeviceId: "ghost-shutdown-android",
provisionDuration: 0,
spec: { model: "Pixel 8", osVersion: "35", physical: false, platform: "android" },
});
await harness.registry.transitionDevice(ghostShutdown.id, "ready", {
event: "device.ready",
payload: { bootDuration: 0, deviceId: ghostShutdown.id },
});
await harness.registry.transitionDevice(ghostShutdown.id, "shutdown", {
event: "device.shutdown",
payload: { deviceId: ghostShutdown.id, initiator: "test" },
});
const idleShutdown = await seedReleased(harness, "shutdown");
// why: one second past T2, so every destroy proposal fires and every shutdown one already has.
harness.clock.advance(31_000);

// why: loose on purpose -- whether the run still reports the driverless devices' proposals is
// for the fix to decide; skipping the platform or surviving the failed action both answer it.
await expect(harness.reaper.run()).resolves.toEqual(
expect.arrayContaining([
expect.objectContaining({
action: "shutdown",
rule: "idle-shutdown",
target: idleReady.id,
}),
expect.objectContaining({
action: "destroy",
rule: "idle-destroy",
target: idleShutdown.id,
}),
]),
);

const stateOf = (deviceId: string) =>
harness.registry.snapshot.devices.find((device) => device.id === deviceId)?.state;
expect([
stateOf(ghostReady.id),
stateOf(idleReady.id),
stateOf(ghostShutdown.id),
stateOf(idleShutdown.id),
]).toEqual(["ready", "shutdown", "shutdown", "deleted"]);
expect(
harness.driver.calls
.filter((call) => call.operation === "shutdown" || call.operation === "destroy")
.map((call) => `${call.operation} ${(call.arguments[0] as { deviceId: string }).deviceId}`)
.sort(),
).toEqual(
[`destroy ${idleShutdown.driverDeviceId}`, `shutdown ${idleReady.driverDeviceId}`].sort(),
);
expect(
harness.eventBus
.replay()
.filter((entry) => entry.event === "cleanup.executed")
.map((entry) => (entry.payload as { target: string }).target)
.sort(),
).toEqual([idleReady.id, idleShutdown.id].sort());

harness.reaper.dispose();
});

it("logs a cleanup action that throws at error, naming the action, rule and target, and still resolves the run", async () => {
const sink = new MemoryLogSink();
const rule: CleanupRule = {
evaluate: () => [
{ action: "shutdown", reason: "test cleanup", rule: "test-rule", target: "dev_1" },
],
name: "test-rule",
};
const harness = await createHarness(
[rule],
{},
{ logger: new JsonLinesLogger({ clock: new FakeClock(1_000), sink }), tickMs: 10_000 },
);
await seedReady(harness);
vi.spyOn(harness.executor, "execute").mockRejectedValue(new Error("action exploded"));

await expect(harness.reaper.run()).resolves.toHaveLength(1);
expect(sink.records).toEqual([
expect.objectContaining({
level: "error",
module: "daemon.reaper",
fields: {
action: "shutdown",
error: "Error: action exploded",
rule: "test-rule",
step: "cleanup",
target: "dev_1",
},
}),
]);
harness.reaper.dispose();
});

it("prevents leasing from granting a device while cleanup is shutting it down", async () => {
const rule: CleanupRule = {
evaluate: () => [
Expand Down
15 changes: 14 additions & 1 deletion src/core/reaper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,20 @@ export class CleanupReaper {
}

for (const proposal of proposals) {
await this.options.executor.execute(proposal);
// why: one action that throws (a device whose platform has no driver) must not abort the
// proposals after it. Only the action is contained: a rule or registry-view failure above
// still rejects the run.
try {
await this.options.executor.execute(proposal);
} catch (error: unknown) {
this.#logger.error("cleanup action failed", {
step: "cleanup",
action: proposal.action,
rule: proposal.rule,
target: proposal.target,
error: stableError(error),
});
}
}

return proposals;
Expand Down
Loading