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/contract/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -506,8 +506,8 @@ export const statusCapacitySchema = z.object({
ios: platformCapacityEntrySchema,
android: platformCapacityEntrySchema,
global: runningCapacityEntrySchema.extend({ warm: z.number() }),
/** Present only under a strategy that keeps a RAM budget. `usedBytes` counts every
* non-deleted device by the mode it reports, without in-flight provisioning. */
/** why: present only under a strategy that keeps a RAM budget. `usedBytes` counts every
* device neither deleted nor shut down, by the mode it reports, without in-flight provisioning. */
ramBudget: z
.object({
limitBytes: z.number().finite(),
Expand Down
8 changes: 4 additions & 4 deletions src/core/capacity/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Callers: leasing's `AcquisitionPlanner`, the warm pool, `status.get`. Parent: [c
- `tryReserveProvisioning(planned, devices)` — `canProvision`, then a running slot. Counts as a
device and a running slot until released.
- `tryReserveBoot(device, devices)` — `canBoot` (RAM first), then a running slot. The device
counts `full` in every decision until released.
counts `full` and no longer `shutdown` (so it holds RAM) in every decision until released.
- Release is idempotent. Every take and release calls the observer.
6. **Read** — `runningCapacity` (running, reserved, max, `overLimit` per platform and global),
`deviceLimit`, `ramBudget` (devices only, reservations left out), `atRamBudget(platform)`: would
Expand All @@ -49,10 +49,10 @@ Callers: leasing's `AcquisitionPlanner`, the warm pool, `status.get`. Parent: [c

**`resource`** (default). Limits from the machine, plus a RAM budget.

- Limit = `totalRamBytes` − 4 GiB. Used = sum over every device not `deleted` (shut down
included), each by platform and mode; a slim size left unset is the full size.
- Limit = `totalRamBytes` − 4 GiB. Used = sum over every device neither `deleted` nor
`shutdown`, each by platform and mode; a slim size left unset is the full size.
- `canProvision`: device limit, then used + new device's size > limit → `ram-budget`.
- `canBoot`: extra = full size − own size; refused `ram-budget` when used + extra > limit.
- `canBoot`: extra = full size for a shut-down device (it holds none), else full size − own size; refused `ram-budget` when used + extra > limit.
- Over the limit (sizes raised by a restart): every create and every boot that adds RAM is
refused. Nothing is stopped or reclaimed for it.

Expand Down
8 changes: 4 additions & 4 deletions src/core/capacity/coordinator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ describe("CapacityCoordinator", () => {
),
);
const slim = iosDevice("slim-1", "slim", "shutdown");
// 8 GiB used of 8, and the one iOS running slot taken: both would refuse; RAM is named.
// why: 7 GiB used of 8, the boot would add 3 GiB, and the one iOS running slot taken: both would refuse; RAM is named.
const devices: CapacityDevice[] = [
slim,
iosDevice("ready-1", "full", "ready"),
Expand All @@ -224,7 +224,7 @@ describe("CapacityCoordinator", () => {
it("holds a boot's extra size until the boot reservation is released", () => {
const capacity = sizedCoordinator();
const slim = iosDevice("slim-1", "slim", "shutdown");
// 5 GiB used of 8: booting the slim device adds 2 GiB, leaving 1.
// why: 4 GiB used of 8: booting the shut-down slim device adds its full 3 GiB, leaving 1.
const devices = [
slim,
iosDevice("ready-1", "full", "ready"),
Expand All @@ -233,7 +233,7 @@ describe("CapacityCoordinator", () => {

const boot = capacity.tryReserveBoot(slim, devices);
if (!boot.ok) throw new Error("expected a boot reservation");
// 7 GiB counted: no room for a new device's 3 GiB, nor for a second slim boot's 2 GiB.
// why: 7 GiB counted: no room for a new device's 3 GiB, nor for a second slim boot's 3 GiB.
expect(capacity.tryReserveProvisioning({ mode: "full", platform: "ios" }, devices)).toEqual({
ok: false,
reason: "ram-budget",
Expand Down Expand Up @@ -301,7 +301,7 @@ describe("CapacityCoordinator", () => {
expect(capacity.ramBudget([slim, iosDevice("ready-1", "full", "ready")])).toEqual({
limitBytes: 8 * gibibyte,
overLimit: false,
usedBytes: 4 * gibibyte,
usedBytes: 3 * gibibyte,
});
});

Expand Down
6 changes: 5 additions & 1 deletion src/core/capacity/coordinator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,11 @@ export class CapacityCoordinator {
return [
...devices.map((device) =>
device.id !== undefined && booting.has(device.id)
? { ...device, mode: "full" as const }
? {
...device,
mode: "full" as const,
state: device.state === "shutdown" ? "booting" : device.state,
}
: device,
),
...this.#provisioningReservations.map(asProvisioningDevice),
Expand Down
57 changes: 57 additions & 0 deletions src/core/capacity/shutdown-ram.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { describe, expect, it } from "vitest";

import { FakeSystemStats } from "../../ports/index.js";
import { CapacityCoordinator } from "./index.js";
import { resourceStrategy } from "./testing.js";

const gibibyte = 1024 ** 3;

function capacity(): CapacityCoordinator {
return new CapacityCoordinator(
resourceStrategy.create(
{
limits: {
android: { maxDevices: 8, maxRunning: 8 },
ios: { maxDevices: 8, maxRunning: 8 },
maxRunning: 16,
},
ramBudget: {
androidBytesPerDevice: 4 * gibibyte,
iosBytesPerDevice: 3 * gibibyte,
iosSlimBytesPerDevice: gibibyte,
},
},
new FakeSystemStats({ cpuCount: 8, totalRamBytes: 12 * gibibyte }),
),
);
}

describe("shutdown RAM accounting (#779 proposal)", () => {
it("releases shutdown devices' RAM for status, provisioning and slim boots", () => {
const devices = [
{ id: "ios-full", mode: "full" as const, platform: "ios" as const, state: "shutdown" },
{ id: "ios-slim", mode: "slim" as const, platform: "ios" as const, state: "shutdown" },
{
id: "android-full",
mode: "full" as const,
platform: "android" as const,
state: "shutdown",
},
] as const;
const planned = { mode: "full" as const, platform: "ios" as const };
expect(capacity().tryReserveProvisioning(planned, [])).toMatchObject({ ok: true });
expect(capacity().tryReserveBoot(devices[1], [devices[1]])).toMatchObject({ ok: true });

expect.soft(capacity().runningCapacity(devices).global.running).toBe(0);
expect.soft(capacity().ramBudget(devices)).toEqual({
limitBytes: 8 * gibibyte,
overLimit: false,
usedBytes: 0,
});
for (const platform of ["ios", "android"] as const) {
expect.soft(capacity().atRamBudget(platform, devices), platform).toBe(false);
}
expect.soft(capacity().tryReserveProvisioning(planned, devices)).toMatchObject({ ok: true });
expect.soft(capacity().tryReserveBoot(devices[1], devices)).toMatchObject({ ok: true });
});
});
19 changes: 10 additions & 9 deletions src/core/capacity/strategies/resource/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,27 +204,28 @@ describe("resource strategy RAM budget by mode", () => {
iosSlimBytesPerDevice: gibibyte,
});
const shutdown = device("ios", "slim", "shutdown");
// 7 GiB used of 8: booting adds the 1 GiB between the slim and the full size.
// why: 6 GiB used of 8 (the shut-down device holds none): booting adds its full 2 GiB.
const fits = [shutdown, device("ios", "full"), device("ios", "full"), device("ios", "full")];
expect(strategy.canBoot(shutdown, fits)).toEqual({ ok: true });
// 8 GiB used: the same boot would reach 9.
// why: 7 GiB used: the same boot would reach 9.
expect(strategy.canBoot(shutdown, [...fits, device("ios", "slim")])).toEqual({
ok: false,
reason: "ram-budget",
});
});

it("never refuses booting a shut-down full device for RAM, even over the limit", () => {
it("charges booting a shut-down full device its whole size, refusing it only when that no longer fits", () => {
const strategy = sized({
androidBytesPerDevice: 4 * gibibyte,
iosBytesPerDevice: 3 * gibibyte,
iosSlimBytesPerDevice: gibibyte,
});
const shutdown = device("ios", "full", "shutdown");
const over = [shutdown, device("ios", "full"), device("ios", "full")];

expect(strategy.ramBudget(over)?.overLimit).toBe(true);
expect(strategy.canBoot(shutdown, over)).toEqual({ ok: true });
expect(strategy.canBoot(shutdown, [shutdown, device("ios", "full")])).toEqual({ ok: true });
expect(
strategy.canBoot(shutdown, [shutdown, device("ios", "full"), device("ios", "full")]),
).toEqual({ ok: false, reason: "ram-budget" });
});

it("counts slim and full devices on both platforms at the sum of each device's own size", () => {
Expand Down Expand Up @@ -262,7 +263,7 @@ describe("resource strategy RAM budget by mode", () => {
});
});

it("reports the limit as total RAM minus the reserve, use over non-deleted devices, and over only past the limit", () => {
it("reports the limit as total RAM minus the reserve, use over devices neither deleted nor shut down, and over only past the limit", () => {
const strategy = sized({
androidBytesPerDevice: 4 * gibibyte,
iosBytesPerDevice: 2 * gibibyte,
Expand All @@ -277,9 +278,9 @@ describe("resource strategy RAM budget by mode", () => {
expect(strategy.ramBudget(atLimit)).toEqual({
limitBytes: 8 * gibibyte,
overLimit: false,
usedBytes: 8 * gibibyte,
usedBytes: 6 * gibibyte,
});
expect(strategy.ramBudget([...atLimit, device("ios", "slim")])).toEqual({
expect(strategy.ramBudget([...atLimit, device("android", "full")])).toEqual({
limitBytes: 8 * gibibyte,
overLimit: true,
usedBytes: 10 * gibibyte,
Expand Down
12 changes: 7 additions & 5 deletions src/core/capacity/strategies/resource/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import {

const GIBIBYTE = 1024 ** 3;
const OS_RAM_RESERVE_BYTES = 4 * GIBIBYTE;
// why: a shut-down device holds no RAM, so it is the one state the budget leaves out.
const SHUTDOWN = "shutdown";

/**
* Device and running ceilings derived from the machine, with a RAM budget gate
Expand Down Expand Up @@ -60,8 +62,9 @@ class ResourceCapacityStrategy implements CapacityStrategy {
}

canBoot(device: CapacityDevice, devices: readonly CapacityDevice[]): CapacityDecision {
const fullBytes = this.#bytesPerDevice({ ...device, mode: "full" });
const extraBytes =
this.#bytesPerDevice({ ...device, mode: "full" }) - this.#bytesPerDevice(device);
device.state === SHUTDOWN ? fullBytes : fullBytes - this.#bytesPerDevice(device);
if (extraBytes <= 0) return { ok: true };
return this.#usedBytes(devices) + extraBytes > this.#limitBytes()
? { ok: false, reason: "ram-budget" }
Expand Down Expand Up @@ -98,10 +101,9 @@ class ResourceCapacityStrategy implements CapacityStrategy {
}

#usedBytes(devices: readonly CapacityDevice[]): number {
return activeDevices(devices).reduce(
(total, device) => total + this.#bytesPerDevice(device),
0,
);
return activeDevices(devices)
.filter((device) => device.state !== SHUTDOWN)
.reduce((total, device) => total + this.#bytesPerDevice(device), 0);
}

#bytesPerDevice({ platform, mode }: PlannedCapacityDevice): number {
Expand Down
6 changes: 3 additions & 3 deletions src/core/capacity/strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ export interface CapacityStrategy {
canProvision(device: PlannedCapacityDevice, devices: readonly CapacityDevice[]): CapacityDecision;

/**
* Whether the shut-down `device`, already among `devices`, may boot. A device
* boots at its platform's full size before any slim pass, so a boot needs room
* for the difference between that and the size the device counts at.
* why: Whether the shut-down `device`, already among `devices`, may boot. A device
* boots at its platform's full size before any slim pass. A shut-down device holds
* no RAM, so a boot needs room for that whole size; a running one needs the difference.
*/
canBoot(device: CapacityDevice, devices: readonly CapacityDevice[]): CapacityDecision;

Expand Down
6 changes: 3 additions & 3 deletions src/leasing/acquisition-planner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ describe("AcquisitionPlanner", () => {
};
const leases = [leaseOn(android)];

// 6 GiB used of 8: the boot adds the 2.5 GiB between the slim and the full size.
// why: 5 GiB used of 8: the boot adds the shut-down device's full 3.5 GiB.
const devices = [android, idleOther, shutdownSlim];
expect(plan(acquisitionPlanner, devices, { leases, spec: slimSpec })).toEqual({
kind: "wait",
Expand All @@ -382,12 +382,12 @@ describe("AcquisitionPlanner", () => {
expect(claims.isClaimed(idleOther.id)).toBe(false);
expect(claims.isClaimed(shutdownSlim.id)).toBe(false);

// Without the idle device, 5 GiB is used and the boot fits.
// why: Without the idle device, 4 GiB is used and the boot fits.
const boot = plan(acquisitionPlanner, [android, shutdownSlim], { leases, spec: slimSpec });
expect(boot).toMatchObject({ device: shutdownSlim, kind: "boot-shutdown" });
});

it("evicts an idle slim device for a full request at the device limit, then waits when the freed RAM is not enough", () => {
it("evicts an idle shut-down slim device for a full request at the device limit, then waits when the RAM is still not enough", () => {
const { planner: acquisitionPlanner } = sizedPlanner(2);
const android = device("android", "leased", {
physical: false,
Expand Down
2 changes: 1 addition & 1 deletion src/leasing/acquisition-planner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ export class AcquisitionPlanner {
}

#planShutdownBoot(input: AcquisitionPlannerInput, device: VirtualDevice): AcquisitionPlan {
// A boot refused for RAM evicts nothing: freeing a running slot frees no RAM.
// why: only a running-limit refusal picks a victim (#runningVictim); a RAM-budget refusal waits.
const running = this.capacity.tryReserveBoot(
capacityDevice(device),
capacityDevices(input.snapshot.virtualDevices),
Expand Down
14 changes: 5 additions & 9 deletions src/leasing/create-leasing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1497,7 +1497,7 @@ describe("createLeasing RAM budget by mode", () => {
});
});

it("over its limit after a restart with larger sizes, creates no device in either mode and boots no shut-down slim device, but grants an idle one; a delete brings it back under", async () => {
it("over its limit after a restart with larger sizes, creates no device in either mode and boots no shut-down slim device, but grants an idle one; shutting the idle one down brings it back under", async () => {
const clock = new FakeClock(1_000);
const driver = new FakeDriver({
knownModels: ["iPhone 16", "iPhone 16 Pro"],
Expand Down Expand Up @@ -1528,15 +1528,14 @@ describe("createLeasing RAM budget by mode", () => {
rule: "test",
target: toShutDown.device.id,
});
expect(before.engine.ramBudget?.usedBytes).toBe(1.5 * gibibyte);
expect(before.engine.ramBudget?.usedBytes).toBe(1 * gibibyte);

// Restarted at 2 GiB slim: the three slim devices use 6 GiB of 5.
const after = await createHarness({
driver,
state: before.state,
idleShutdownAfterMs: 0,
limits: roomy,
ramBudget: { ...ramBudget, iosSlimBytesPerDevice: 2 * gibibyte },
ramBudget: { ...ramBudget, iosSlimBytesPerDevice: 3 * gibibyte },
totalRamBytes: 9 * gibibyte,
});
await after.engine.convergeRunningCapacity();
Expand Down Expand Up @@ -1571,8 +1570,6 @@ describe("createLeasing RAM budget by mode", () => {
expect(reused.device.id).toBe(idle.device.id);
expect(after.registry.snapshot.leases.map((lease) => lease.deviceId)).toContain(held.device.id);

// A release lowers nothing; deleting both idle devices brings use to 2 GiB of 5, and a new
// device's 3 GiB fits again.
await after.engine.release(reused.lease.id, "explicit");
await after.engine.settle();
expect(after.engine.ramBudget?.overLimit).toBe(true);
Expand All @@ -1584,12 +1581,11 @@ describe("createLeasing RAM budget by mode", () => {
await after.engine.cleanup.execute({ action, reason: "test", rule: "test", target });
}
await after.engine.settle();
// why: the pool keeps the kind the reused lease taught it: the one slim device it made takes the 2 GiB the deletes freed.
expect(operations(driver, "makeReady")).toBe(boots + 1);
expect(operations(driver, "makeReady")).toBe(boots);
expect(after.engine.ramBudget).toEqual({
limitBytes: 5 * gibibyte,
overLimit: false,
usedBytes: 4 * gibibyte,
usedBytes: 3 * gibibyte,
});
});
});
Expand Down
8 changes: 4 additions & 4 deletions website/src/content/docs/docs/worker/capacity.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ A lease request that needs a new device or a boot does this, in order:
5. At a running limit, it shuts down an idle booted device to make room.
6. Otherwise it waits in the queue until a device frees up. With `--no-wait` it fails with `NO_CAPACITY` instead.

A leased device is never shut down or deleted to make room. When the RAM budget is what blocks a request, Simlock does not shut anything down, because a shut-down device still counts against the budget. The request waits until a device is deleted.
A leased device is never shut down or deleted to make room. When the RAM budget is what blocks a request, Simlock shuts nothing down for it: only a running limit makes it shut down an idle device. The request waits until enough RAM is free, for example when an idle device shuts down on its own or a device is deleted.

## Size by the machine: the `resource` strategy

Expand All @@ -69,7 +69,7 @@ A leased device is never shut down or deleted to make room. When the RAM budget

The defaults are computed from the machine, not from your other settings. If you raise `ios.maxDevices` and leave `ios.maxRunning` out, the running limit stays at the machine's default. Set the device, platform running and global running limits together.

The RAM budget is the machine's total RAM minus 4 GiB kept for macOS or Linux. Every device that exists counts, booted or shut down, at its platform's size. Simlock refuses to create a device that would push the total over the budget. It does not measure the RAM a device really uses.
The RAM budget is the machine's total RAM minus 4 GiB kept for macOS or Linux. Every device that exists and is not shut down counts at its platform's size; a shut-down device counts nothing against the budget, though it still counts against the device limit. Simlock refuses to create a device that would push the total over the budget. It does not measure the RAM a device really uses.

This config lets an Apple silicon Mac run eight simulators and two emulators, ten at a time:

Expand Down Expand Up @@ -149,8 +149,8 @@ To fit more slim simulators in the RAM budget, give them a smaller size:

- A device counts at the full size until it has booted, because a slim device boots full first. Creating any device needs room for the full size.
- After it boots, a device counts by the mode it has. A slim request that got a full device counts as full.
- Booting a shut-down slim device also needs room for the full size. If there is none, it stays shut down and the request waits.
- If you restart with larger sizes than the devices were created under, the budget can show `(over limit)`. Until a device is deleted, no new device is created.
- Booting a shut-down device, slim or full, needs room for its full size, since a shut-down device holds none. If there is none, it stays shut down and the request waits.
- If you restart with larger sizes than the devices were created under, the budget can show `(over limit)`. Until enough RAM is free, no new device is created and no shut-down device boots if its full size does not fit.

## Keep devices booted: the warm pool

Expand Down
Loading