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
2 changes: 1 addition & 1 deletion src/core/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic
`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.
`killed` → shut down each unleased `ready` virtual device; with delete, destroy each `shutdown` one; a device it cannot reset is logged, the rest go on.
7. **Startup** — `readStartup` (`listManaged` per driver, parallel) → `doctor.reconcile({ read })`
→ leasing's reconcile → `core.converge`: re-arm quarantine → recover interrupted reclaims →
delete spent devices → start warm pool and `CapacityObserver`. Skips unreadable, leased, claimed.
Expand Down
1 change: 1 addition & 0 deletions src/core/create-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ export function createCore(options: CoreOptions): Core {
},
devices: deviceLifecycle,
leases: leaseMaintenance.leases,
...(options.logger === undefined ? {} : { logger: options.logger }),
registry,
});
const doctor = new Doctor({
Expand Down
151 changes: 151 additions & 0 deletions src/core/nuke-service.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { describe, expect, it } from "vitest";

import { EventBus } from "../bus/index.js";
import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js";
import { Registry } from "./index.js";
import type { VirtualDevice, LeaseRecord } from "./domain.js";
import { FakeDriver } from "./fake-driver.js";
import { DeviceOperationClaims } from "./device-operation-claims.js";
import { DriverCatalog } from "./driver-catalog.js";
import { ManagedDeviceLifecycle } from "./managed-device-lifecycle.js";
import { SerializedDecision } from "./serialized-decision.js";
import { NukeService, type NukeDeviceLifecycle, type NukeRegistryView } from "./nuke-service.js";

const device = (id: string, state: VirtualDevice["state"]): VirtualDevice => ({
Expand Down Expand Up @@ -235,4 +243,147 @@ describe("NukeService", () => {
"maintenance:end",
]);
});

it("does not abort the reset on a device whose platform has no driver, and still resets every device after it", async () => {
// why: the driverless records are registered first so the attempts that must throw precede
// the healthy ones — that order is what a whole-run abort turns on. Only an ios driver is
// catalogued, so acting on an android record throws NoDriverError, as it does for a platform
// discovery refused. The ready ghost exercises the shutdown verb, the shut-down ghost the
// destroy verb; a healthy ios device follows each. `--delete-devices` makes one pass prove
// both verbs.
const clock = new FakeClock(1_000);
const eventBus = new EventBus(clock);
const driver = new FakeDriver({ availableOsVersions: ["1"], clock, platform: "ios" });
let nextId = 1;
const registry = await Registry.load({
clock,
eventBus,
filesystem: new MemoryFilesystem(),
idGenerator: { generate: () => `${nextId++}` },
statePath: "/state.json",
});
const lifecycle = new ManagedDeviceLifecycle(
new DriverCatalog([driver]),
registry,
new SerializedDecision(),
new DeviceOperationClaims(),
clock,
);
const service = new NukeService({
acquisition: {
async beginMaintenance() {},
async endMaintenance() {},
},
devices: lifecycle,
leases: {
async beginMaintenance() {},
async releaseAllDuringMaintenance() {
return [];
},
async endMaintenance() {},
},
registry,
});

async function register(
spec: VirtualDevice["spec"],
driverData: unknown,
driverDeviceId: string,
) {
const device = await registry.registerDevice({
driverData,
driverDeviceId,
provisionDuration: 0,
spec,
});
await registry.transitionDevice(device.id, "ready", {
event: "device.ready",
payload: { bootDuration: 0, deviceId: device.id },
});
return device;
}
const android = {
physical: false,
model: "Pixel 8",
osVersion: "35",
platform: "android",
} as const;
const ios = { physical: false, model: "Phone", osVersion: "1", platform: "ios" } as const;

const ghostReady = await register(android, {}, "ghost-ready-android");
const provisionedReady = await driver.provision(ios);
const healthyReady = await register(
ios,
provisionedReady.driverData,
provisionedReady.deviceId,
);
const ghostShutdown = await register(android, {}, "ghost-shutdown-android");
await registry.transitionDevice(ghostShutdown.id, "shutdown", {
event: "device.shutdown",
payload: { deviceId: ghostShutdown.id, initiator: "test" },
});
const provisionedShutdown = await driver.provision(ios);
const healthyShutdown = await register(
ios,
provisionedShutdown.driverData,
provisionedShutdown.deviceId,
);
await registry.transitionDevice(healthyShutdown.id, "shutdown", {
event: "device.shutdown",
payload: { deviceId: healthyShutdown.id, initiator: "test" },
});

await expect(service.nuke(true)).resolves.toEqual({ releasedLeaseIds: [] });

const stateOf = (deviceId: string) =>
registry.snapshot.devices.find((candidate) => candidate.id === deviceId)?.state;
expect([
stateOf(ghostReady.id),
stateOf(healthyReady.id),
stateOf(ghostShutdown.id),
stateOf(healthyShutdown.id),
]).toEqual(["ready", "deleted", "shutdown", "deleted"]);
expect(
driver.calls
.filter((call) => call.operation === "shutdown" || call.operation === "destroy")
.map((call) => `${call.operation} ${(call.arguments[0] as { deviceId: string }).deviceId}`)
.sort(),
).toEqual(
[
`destroy ${healthyShutdown.driverDeviceId}`,
`destroy ${healthyReady.driverDeviceId}`,
`shutdown ${healthyReady.driverDeviceId}`,
].sort(),
);
});

it("logs a device it cannot reset at error, naming the device, platform and error", async () => {
const sink = new MemoryLogSink();
const harness = createHarness([device("dev_1", "ready")]);
harness.lifecycle.shutdown = async () => {
throw new Error("reset exploded");
};
const service = new NukeService({
acquisition: { async beginMaintenance() {}, async endMaintenance() {} },
devices: harness.lifecycle,
leases: {
async beginMaintenance() {},
async releaseAllDuringMaintenance() {
return [];
},
async endMaintenance() {},
},
logger: new JsonLinesLogger({ clock: new FakeClock(1_000), sink }),
registry: harness.registry,
});

await service.nuke(false);
expect(sink.records).toEqual([
expect.objectContaining({
level: "error",
module: "daemon.nuke",
fields: { deviceId: "dev_1", error: "Error: reset exploded", platform: "ios" },
}),
]);
});
});
19 changes: 17 additions & 2 deletions src/core/nuke-service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { LeaseRecord, VirtualDevice } from "./domain.js";
import { type Logger, NoopLogger } from "../ports/index.js";
import type { NukeExecutor } from "./core-ports.js";
import { stableError } from "./stable-error.js";

/** Release maintenance boundary required by an operator reset. */
export interface LeaseMaintenance {
Expand Down Expand Up @@ -41,6 +43,7 @@ export interface NukeServiceOptions {
readonly acquisition: AcquisitionMaintenance;
readonly leases: LeaseMaintenance;
readonly registry: NukeRegistryView;
readonly logger?: Logger;
}

/**
Expand All @@ -51,7 +54,11 @@ export interface NukeServiceOptions {
export class NukeService implements NukeExecutor {
#tail: Promise<void> = Promise.resolve();

constructor(private readonly options: NukeServiceOptions) {}
readonly #logger: Logger;

constructor(private readonly options: NukeServiceOptions) {
this.#logger = options.logger?.child("nuke") ?? new NoopLogger();
}

async nuke(deleteDevices: boolean): Promise<{ readonly releasedLeaseIds: readonly string[] }> {
let release!: () => void;
Expand All @@ -78,7 +85,15 @@ export class NukeService implements NukeExecutor {
const releasedLeaseIds = await this.options.leases.releaseAllDuringMaintenance("killed");

for (const device of this.options.registry.snapshot.virtualDevices) {
await this.#resetDevice(device, deleteDevices);
try {
await this.#resetDevice(device, deleteDevices);
} catch (error: unknown) {
this.#logger.error("nuke could not reset a device", {
deviceId: device.id,
platform: device.spec.platform,
error: stableError(error),
});
}
}

return { releasedLeaseIds };
Expand Down
Loading