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
1 change: 1 addition & 0 deletions src/core/capacity/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Does: how many virtual devices may exist and run at once — limits, RAM budget,
- Until its reservation is released, a device being booted counts `full` and no longer `shutdown`, so it holds RAM in every decision.
- `ramBudget` reads devices only; reservations are left out.
- Running slots ignore mode; RAM does not. A `quarantined` device holds a running slot. Physical devices are never read.
- At `new-devices-paused` (the memory pressure port) every reservation that adds a device or RAM is refused `memory-pressure` before the strategy is asked, under every strategy; it evicts nothing. `canProvision` and `canBoot` stay the strategy's answer.
- A boot refused for RAM evicts nothing; the request waits.
- Over the RAM limit (sizes raised by a restart), every create and every boot that adds RAM is refused. Nothing is stopped or reclaimed for it.
- Release is idempotent. Every take and release calls the observer.
Expand Down
16 changes: 16 additions & 0 deletions src/core/capacity/coordinator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ import type {
RunningCapacity,
} from "./strategy.js";

/** why: the one thing capacity reads of a worker's memory pressure, so it never names host-load. */
export interface MemoryPressureStepReader {
current(): { readonly step: "none" | "warming-paused" | "new-devices-paused" } | undefined;
}

const NEW_DEVICES_PAUSED: CapacityRefusal = { ok: false, reason: "memory-pressure" };

/** A releasable capacity reservation. Releasing it more than once is safe. */
export interface CapacityReservation {
release(): void;
Expand Down Expand Up @@ -51,8 +58,14 @@ export class CapacityCoordinator {
constructor(
private readonly strategy: CapacityStrategy,
private readonly onReservationsChanged: () => void = () => undefined,
private readonly memoryPressure?: MemoryPressureStepReader,
) {}

/** why: checked before the strategy is asked, under every strategy (ADR 0068 §4). */
newDevicesPaused(): boolean {
return this.memoryPressure?.current()?.step === "new-devices-paused";
}

/**
* Reserves both a future device slot and its future running slot.
* Provisioning counts against the strategy's device budget and running limits
Expand All @@ -62,6 +75,7 @@ export class CapacityCoordinator {
device: PlannedCapacityDevice,
devices: readonly CapacityDevice[],
): CapacityReservationAttempt {
if (this.newDevicesPaused()) return NEW_DEVICES_PAUSED;
const provision = this.canProvision(device, devices);
if (!provision.ok) return provision;

Expand All @@ -85,6 +99,7 @@ export class CapacityCoordinator {
device: RegisteredCapacityDevice,
devices: readonly CapacityDevice[],
): CapacityReservationAttempt {
if (this.newDevicesPaused()) return NEW_DEVICES_PAUSED;
const boot = this.canBoot(device, devices);
if (!boot.ok) return boot;
const running = this.canReserveRunning(device.platform, devices);
Expand Down Expand Up @@ -115,6 +130,7 @@ export class CapacityCoordinator {
device: RegisteredCapacityDevice,
devices: readonly CapacityDevice[],
): CapacityReservationAttempt {
if (this.newDevicesPaused()) return NEW_DEVICES_PAUSED;
const boot = this.canBoot(device, devices);
if (!boot.ok) return boot;

Expand Down
6 changes: 5 additions & 1 deletion src/core/create-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ const NO_MEMORY_PRESSURE: MemoryPressureReader = {

export function createCore(options: CoreOptions): Core {
const { decisions, registry } = options;
const memoryPressure = options.memoryPressure ?? NO_MEMORY_PRESSURE;
let ports: CorePorts | undefined;
const port = <Name extends keyof CorePorts>(name: Name): CorePorts[Name] => {
if (ports === undefined) throw new CorePortMissingError(name);
Expand All @@ -193,6 +194,7 @@ export function createCore(options: CoreOptions): Core {
const capacity = new CapacityCoordinator(
createCapacityStrategy(options.config.capacity, options.systemStats),
() => capacityObserver.changed(),
memoryPressure,
);
const devices = () => capacityDevices(registry.snapshot.virtualDevices);
const capacityReader: CapacityReader = {
Expand Down Expand Up @@ -270,6 +272,8 @@ export function createCore(options: CoreOptions): Core {
...(options.logger === undefined ? {} : { logger: options.logger }),
registry,
});
// why: a waiting request is only planned again by an event; the step lifting is the one that frees it.
options.eventBus.subscribe("memory.pressure-changed", notifyAvailability);
// why: removing a runtime or image is what makes a baseline stale, so the check follows it.
options.eventBus.subscribe("component.removed", () => {
baselines.checkStale().catch((error: unknown) => {
Expand Down Expand Up @@ -400,7 +404,7 @@ export function createCore(options: CoreOptions): Core {
return {
capacity,
capacityReader,
memoryPressure: options.memoryPressure ?? NO_MEMORY_PRESSURE,
memoryPressure,
warmPoolReader: warmPool,
warmKinds: { forget: (match) => warmPool.forgetKinds(match) },
baselines,
Expand Down
3 changes: 3 additions & 0 deletions src/core/device-provisioner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,8 @@ describe("DeviceProvisioner and a component removal (ADR 0010 §8)", () => {
[join("core", "test-registry.ts")]: 1,
// why: the harness the lease-acquisition coordinator tests split out of one file share (ADR 0063).
[join("leasing", "test-lease-acquisition.ts")]: 1,
// why: the dispatcher tests' seeded warm device, shared by the files that start from one.
[join("daemon", "test-dispatcher.ts")]: 1,
});
expect(callSites(/\.provision\(/g)).toEqual({
// The driver call itself.
Expand All @@ -462,6 +464,7 @@ describe("DeviceProvisioner and a component removal (ADR 0010 §8)", () => {
[join("drivers", "android", "testing.ts")]: 2,
// why: the harness's fixture devices, as for registerDevice above.
[join("leasing", "test-lease-acquisition.ts")]: 1,
[join("daemon", "test-dispatcher.ts")]: 1,
});
});

Expand Down
1 change: 1 addition & 0 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ export {
export { SerializedDecision } from "./serialized-decision.js";
export {
type CapacityReader,
type MemoryPressureReader,
type CatalogReader,
type LeaseExpirer,
type PassthroughResolver,
Expand Down
40 changes: 1 addition & 39 deletions src/daemon/dispatcher-except.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { describe, expect, it, vi } from "vitest";

import { readyTransitionUpdate } from "../core/testing.js";
import { DriverCrashError } from "../core/index.js";
import { classifyError } from "./error-code.js";
import { buildDispatcher, session } from "./test-dispatcher.js";
import { buildDispatcher, seedSlimDevice, session } from "./test-dispatcher.js";

/** why: the answer of a request that must settle by itself once the event loop has run to rest; a hang fails here, on a named assertion, rather than by the test's timeout. */
async function grantedOnceSettled<T>(request: Promise<T>): Promise<T> {
Expand All @@ -16,43 +15,6 @@ async function grantedOnceSettled<T>(request: Promise<T>): Promise<T> {
return answer as T;
}

/** why: a slim device a worker already holds, ready or shut down, as the warm pool or an earlier lease leaves one. */
async function seedSlimDevice(
built: Awaited<ReturnType<typeof buildDispatcher>>,
state: "ready" | "shutdown",
) {
const spec = {
mode: "slim",
model: "iPhone 17 Pro",
osVersion: "26.5",
physical: false,
platform: "ios",
} as const;
const driverDevice = await built.driver.provision(spec);
const driven = await built.driver.makeReady(driverDevice, { mode: "slim", purpose: "prepare" });
// why: the seed is a slim device whatever the fake reports on its boot, so a test whose driver answers `full` still starts from slim.
const ready = { ...driven, mode: "slim" as const };
const registered = await built.registry.registerDevice({
driverData: driverDevice.driverData,
driverDeviceId: driverDevice.deviceId,
provisionDuration: 0,
spec,
});
await built.registry.transitionDevice(
registered.id,
"ready",
{ event: "device.ready", payload: { bootDuration: 0, deviceId: registered.id } },
readyTransitionUpdate(ready),
);
if (state === "ready") return registered;
await built.driver.shutdown(driverDevice);
await built.registry.transitionDevice(registered.id, "shutdown", {
event: "device.shutdown",
payload: { deviceId: registered.id, initiator: "test" },
});
return registered;
}

describe("Dispatcher: lease.request with an except list", () => {
it("a client leases slim with except and is granted a device reporting it", async () => {
const except = ["store", "other"];
Expand Down
148 changes: 147 additions & 1 deletion src/daemon/dispatcher-leases.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@ import type { DispatcherOptions } from "./dispatcher.js";
import { classifyError } from "./error-code.js";
import { UnknownLeaseError } from "../core/index.js";
import { RequestCancelledError } from "../leasing/index.js";
import { HOST_SYSTEM, buildDispatcher, flush, gibibyte, session } from "./test-dispatcher.js";
import {
HOST_SYSTEM,
buildDispatcher,
flush,
gibibyte,
seedSlimDevice,
session,
} from "./test-dispatcher.js";

describe("Dispatcher: ownership", () => {
async function grantLease(dispatcher: Awaited<ReturnType<typeof buildDispatcher>>["dispatcher"]) {
Expand Down Expand Up @@ -1295,3 +1302,142 @@ describe("Dispatcher: lease.request requires", () => {
expect(JSON.stringify(requested?.payload)).not.toContain("requires");
});
});

describe("Dispatcher: lease.request at new-devices-paused", () => {
const slimmable = { slimmableOsVersions: ["26.5"] };
const ask = { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" } as const;
const slim = { ...ask, mode: "slim" } as const;
const asker = () => session({ principal: "tok_asker" });
const waiting = (built: Awaited<ReturnType<typeof buildDispatcher>>) =>
built.dispatcher.dispatch("list.get", { kind: "requests" }, session({ role: "admin" }));
const fixed: Config["capacity"] = { strategy: "fixed", config: { maxRunning: 4 } };

it.each([
{ name: "needs a new device", seed: undefined, input: ask, options: {} },
{ name: "boots a shut-down device", seed: "shutdown", input: slim, options: {} },
{
name: "needs the reboot of an idle device for its except list",
seed: "ready",
input: { ...slim, except: ["store"] },
options: {},
},
{
name: "is refused for RAM too",
seed: undefined,
input: ask,
options: {
capacity: {
strategy: "resource",
config: {
limits: {
android: { maxDevices: 1, maxRunning: 1 },
ios: { maxDevices: 4, maxRunning: 4 },
maxRunning: 6,
},
ramBudget: { androidBytesPerDevice: 4 * gibibyte, iosBytesPerDevice: 30 * gibibyte },
},
},
},
},
{
name: "runs under the fixed strategy",
seed: undefined,
input: ask,
options: { capacity: fixed },
},
] as const)(
"a request that $name waits, or gets NO_CAPACITY under noWait, with memory-pressure",
async (row) => {
const start = async () => {
const built = await buildDispatcher({
driverOptions: slimmable,
memoryPressureStep: "new-devices-paused",
...row.options,
});
if (row.seed !== undefined) await seedSlimDevice(built, row.seed);
return { built, seededCalls: built.driver.calls.length };
};
const driven = (world: Awaited<ReturnType<typeof start>>) =>
world.built.driver.calls
.slice(world.seededCalls)
.filter((call) => ["provision", "makeReady", "shutdown"].includes(call.operation));

const waiter = await start();
void waiter.built.dispatcher
.dispatch("lease.request", row.input, asker())
.catch(() => undefined);
await flush();
const listed = await waiting(waiter.built);
const refused = await start();

await expect(
refused.built.dispatcher.dispatch("lease.request", { ...row.input, noWait: true }, asker()),
).rejects.toMatchObject({
code: "NO_CAPACITY",
details: { capacityReason: "memory-pressure" },
});
expect(listed).toMatchObject([{ reason: "memory-pressure", stage: "queued" }]);
expect(driven(waiter)).toEqual([]);
expect(driven(refused)).toEqual([]);
},
);

it("grants a request that fits an idle booted device, and does not evict an idle device of another kind", async () => {
const granted = await buildDispatcher({
driverOptions: slimmable,
memoryPressureStep: "new-devices-paused",
});
const registered = await seedSlimDevice(granted, "ready");
await expect(
granted.dispatcher.dispatch("lease.request", slim, asker()),
).resolves.toMatchObject({ device: { id: registered.id } });

const limited = await buildDispatcher({
capacity: {
strategy: "resource",
config: {
limits: {
android: { maxDevices: 1, maxRunning: 1 },
ios: { maxDevices: 4, maxRunning: 1 },
maxRunning: 6,
},
ramBudget: { androidBytesPerDevice: 4 * gibibyte, iosBytesPerDevice: gibibyte },
},
},
driverOptions: slimmable,
memoryPressureStep: "new-devices-paused",
});
const idle = await seedSlimDevice(limited, "ready");
await expect(
limited.dispatcher.dispatch("lease.request", { ...ask, mode: "full", noWait: true }, asker()),
).rejects.toMatchObject({ details: { capacityReason: "memory-pressure" } });
expect(limited.registry.snapshot.virtualDevices.find((d) => d.id === idle.id)?.state).toBe(
"ready",
);
});

it.each(["none", "warming-paused"] as const)(
"a request waiting on memory pressure reads memory-pressure, then is served when the step lifts to %s with no other event",
async (lifted) => {
const built = await buildDispatcher({ memoryPressureStep: "new-devices-paused" });
let granted: unknown;
void built.dispatcher.dispatch("lease.request", ask, asker()).then((grant) => {
granted = grant;
});
await flush();
const before = await waiting(built);

built.setMemoryPressure(lifted);
built.eventBus.emit(
"memory.pressure-changed",
{ from: "new-devices-paused", to: lifted },
"test",
);

await flush();

expect(before).toMatchObject([{ reason: "memory-pressure" }]);
expect(granted).toMatchObject({ lease: { ownerId: "tok_asker" } });
},
);
});
Loading
Loading