From 783d701c188c2c9a5bd8cd78843d73dcb888339d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:09:06 +0100 Subject: [PATCH 01/26] test: a worker's status.get reports the memory pressure step its reading meets (#1361) --- src/daemon/main-host-load.test.ts | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/daemon/main-host-load.test.ts b/src/daemon/main-host-load.test.ts index 27fa24358..02960ee0d 100644 --- a/src/daemon/main-host-load.test.ts +++ b/src/daemon/main-host-load.test.ts @@ -360,3 +360,45 @@ describe("startDaemon host load by role", () => { }, ); }); + +function memoryReading( + pressure: "normal" | "warn" | "critical" | undefined, + availablePercent: number, +): HostLoadCounters { + const { pressure: _pressure, ...memory } = COUNTERS.memory!; + return { + ...COUNTERS, + memory: { + ...memory, + availableBytes: Math.round(160 * availablePercent), + totalBytes: 16_000, + ...(pressure === undefined ? {} : { pressure }), + }, + }; +} + +describe("startDaemon memory pressure", () => { + const statusOf = async (daemon: DaemonServer) => + (await daemon.dispatch("status.get", {}, hostLoadAdmin)) as { + capacity?: { memoryPressure?: unknown }; + }; + + it("reports in status.get the memory pressure step the worker's reading meets", async () => { + const cases = [ + { + reading: memoryReading("warn", 34), + expected: { + cause: { availablePercent: 34, level: "warn", trigger: "level" }, + since: 1_000, + step: "warming-paused", + }, + }, + ]; + for (const { reading, expected } of cases) { + const { daemon } = await startOnClock({ hostLoadProbe: new FakeHostLoadProbe(reading) }); + await expect + .poll(async () => (await statusOf(daemon)).capacity?.memoryPressure) + .toEqual(expected); + } + }); +}); From 77d17fb3453016db1ab8d266a121cb6053a08803 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:11:33 +0100 Subject: [PATCH 02/26] feat(host-load): status.get reports the memory pressure step a reading meets (#1361) --- src/contract/config-schemas.ts | 11 +++ src/contract/protocol.ts | 2 +- src/contract/status-schemas.ts | 20 ++++++ src/core/config.ts | 18 +++++ src/daemon/dispatcher.ts | 8 ++- src/daemon/main-host-load.test.ts | 5 +- src/daemon/server.ts | 5 ++ src/daemon/worker-composition.ts | 25 ++++++- src/host-load/index.ts | 11 ++- src/host-load/memory-pressure.ts | 107 ++++++++++++++++++++++++++++++ src/host-load/sampler.ts | 17 ++++- 11 files changed, 221 insertions(+), 8 deletions(-) create mode 100644 src/host-load/memory-pressure.ts diff --git a/src/contract/config-schemas.ts b/src/contract/config-schemas.ts index 409faacd0..6877e5722 100644 --- a/src/contract/config-schemas.ts +++ b/src/contract/config-schemas.ts @@ -52,6 +52,11 @@ const proxyAuthSchema = z.object({ signOutUrl: z.string().optional(), }); +const memoryPressureRuleSchema = z.object({ + level: z.enum(["normal", "warn", "critical", "off"]), + minAvailablePercent: z.number(), +}); + export const configSchema = z.object({ mode: z.enum(["worker", "gateway"]), capabilities: z.record( @@ -108,6 +113,12 @@ export const configSchema = z.object({ }), exec: z.object({ timeoutMs: z.number() }), diskPressure: z.object({ freeBytesThreshold: z.number() }), + memoryPressure: z.object({ + enabled: z.boolean(), + pauseWarming: memoryPressureRuleSchema, + pauseNewDevices: memoryPressureRuleSchema, + clearAfterMs: z.number(), + }), eventBuffer: z.object({ capacity: z.number() }), log: z.object({ level: z.enum(["debug", "info", "warn", "error"]), diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 82f753c3e..6753fcc3b 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 82, max: 82 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 83, max: 83 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/contract/status-schemas.ts b/src/contract/status-schemas.ts index 953afd2f4..fc1aafa7a 100644 --- a/src/contract/status-schemas.ts +++ b/src/contract/status-schemas.ts @@ -26,6 +26,24 @@ const platformCapacityEntrySchema = runningCapacityEntrySchema.extend({ atRamBudget: z.boolean(), }); +const memoryPressureStepSchema = z.enum(["none", "warming-paused", "new-devices-paused"]); + +/** why: the reading that turned the current step on; a floor trigger names the floor it fell under. */ +const memoryPressureCauseSchema = z.object({ + trigger: z.enum(["level", "floor"]), + availablePercent: z.number().int().min(0).max(100), + level: z.enum(["normal", "warn", "critical"]).optional(), + floorPercent: z.number().min(0).max(100).optional(), +}); + +export const statusMemoryPressureSchema = z.object({ + step: memoryPressureStepSchema, + since: z.number().finite().nonnegative().optional(), + cause: memoryPressureCauseSchema.optional(), +}); + +export type StatusMemoryPressure = z.infer; + export const statusCapacitySchema = z.object({ ios: platformCapacityEntrySchema, android: platformCapacityEntrySchema, @@ -39,6 +57,8 @@ export const statusCapacitySchema = z.object({ overLimit: z.boolean(), }) .optional(), + /** why: present only while host load is on and a reading has been taken. */ + memoryPressure: statusMemoryPressureSchema.optional(), }); /** why: a gateway parses the warm pool block off the wire from every worker, so it is bounded. */ diff --git a/src/core/config.ts b/src/core/config.ts index 6bcfd3bdc..dd9a917ce 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -256,6 +256,11 @@ export type MaxPerRequester = number | { readonly ios?: number; readonly android */ export type DaemonMode = "worker" | "gateway"; +interface MemoryPressureRule { + readonly level: "normal" | "warn" | "critical" | "off"; + readonly minAvailablePercent: number; +} + export interface Config { readonly capabilities: Readonly< Record>> @@ -339,6 +344,13 @@ export interface Config { */ readonly exec: { readonly timeoutMs: number }; readonly diskPressure: { readonly freeBytesThreshold: number }; + /** why: ADR 0068 §1: when host memory pauses a worker's warming and its new devices; worker only. */ + readonly memoryPressure: { + readonly enabled: boolean; + readonly pauseWarming: MemoryPressureRule; + readonly pauseNewDevices: MemoryPressureRule; + readonly clearAfterMs: number; + }; readonly eventBuffer: { readonly capacity: number }; readonly log: { readonly level: LogLevel; readonly rotateBytes: number }; readonly eventLog: { @@ -994,6 +1006,12 @@ function defaultConfig( }, exec: { timeoutMs: DEFAULT_EXEC_TIMEOUT_MS }, diskPressure: { freeBytesThreshold: 10 * 1024 ** 3 }, + memoryPressure: { + enabled: true, + pauseWarming: { level: "warn", minAvailablePercent: 20 }, + pauseNewDevices: { level: "critical", minAvailablePercent: 10 }, + clearAfterMs: 60_000, + }, eventBuffer: { capacity: 1_000 }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, eventLog: { diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 054340571..36b46b490 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -88,6 +88,7 @@ import { type ComponentProgress, type OperationName, type StatusLoad, + type StatusMemoryPressure, waitingRequestSchema, WORKER_VIEW_CATALOG_EVENTS, WORKER_VIEW_REFRESH_INTERVAL_MS, @@ -199,6 +200,7 @@ export interface DispatcherOptions { readonly health: () => "starting" | "running" | "failed"; readonly hostFacts: () => HostFacts; readonly load?: () => StatusLoad | undefined; + readonly memoryPressure?: () => StatusMemoryPressure | undefined; readonly awaitReady: () => Promise; readonly instanceId: string; readonly version: string; @@ -397,6 +399,7 @@ export class Dispatcher { const host = this.options.hostFacts(); const load = this.options.load?.(); const loadField = load === undefined ? {} : { load }; + const memoryPressure = this.options.memoryPressure?.(); // why: while starting, the registry has not been checked against the machine, so what it holds // is a claim nobody has looked at; the answer is the daemon, its host and the load reading. const history = this.options.eventHistory.status(); @@ -405,7 +408,10 @@ export class Dispatcher { const snapshot = this.options.registry.snapshot; const answer = { ...(capabilities === undefined ? {} : { capabilities }), - capacity: buildCapacityFigures(snapshot.virtualDevices, this.options.capacity), + capacity: { + ...buildCapacityFigures(snapshot.virtualDevices, this.options.capacity), + ...(memoryPressure === undefined ? {} : { memoryPressure }), + }, devices: snapshot.devices.map((device) => this.#decorateDevice(device)), daemon, history, diff --git a/src/daemon/main-host-load.test.ts b/src/daemon/main-host-load.test.ts index 02960ee0d..aac35b95c 100644 --- a/src/daemon/main-host-load.test.ts +++ b/src/daemon/main-host-load.test.ts @@ -196,14 +196,15 @@ describe("startDaemon host load", () => { expect(load?.ageMs).toBe(86_400_000); }); - it("with hostLoadProbe: null answers the same as with a probe, apart from load", async () => { + it("with hostLoadProbe: null answers the same as with a probe, apart from load and the memory pressure step", async () => { const withProbe = await startOnClock({ hostLoadProbe: new FakeHostLoadProbe(COUNTERS) }); const without = await startOnClock({ hostLoadProbe: null }); await expect.poll(async () => (await workerStatus(withProbe.daemon)).load).toBeDefined(); const { load: _load, ...probed } = await workerStatus(withProbe.daemon); + const { memoryPressure: _step, ...capacity } = probed.capacity as Record; - expect(probed).toEqual(await workerStatus(without.daemon)); + expect({ ...probed, capacity }).toEqual(await workerStatus(without.daemon)); }); it("starts the sampler only after the daemon holds its socket", async () => { diff --git a/src/daemon/server.ts b/src/daemon/server.ts index a9aafabb8..9a9360f42 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -41,6 +41,7 @@ import { type ProtocolRange, type Role, type StatusLoad, + type StatusMemoryPressure, } from "../contract/index.js"; import type { LinkChannel, LinkConnection } from "../link/index.js"; import { DaemonAlreadyRunningError, type ConnectionHost } from "./connection-host.js"; @@ -123,6 +124,7 @@ export interface DaemonServerCommonOptions { readonly eventBus: EventBus; readonly host: ConnectionHost; readonly hostLoad?: { start(): void; dispose(): void }; + readonly memoryPressure?: { current(): StatusMemoryPressure | undefined }; readonly logger?: Logger; readonly protocolVersion?: number | ProtocolRange; readonly version: string; @@ -246,6 +248,9 @@ function buildDispatcher( health: hooks.health, hostFacts: options.hostFacts, ...(options.load === undefined ? {} : { load: options.load }), + ...(options.memoryPressure === undefined + ? {} + : { memoryPressure: () => options.memoryPressure?.current() }), instanceId: options.instanceId, leases: options.leases, ...(options.logger === undefined ? {} : { logger: options.logger }), diff --git a/src/daemon/worker-composition.ts b/src/daemon/worker-composition.ts index 7703aa7c9..66ccbb757 100644 --- a/src/daemon/worker-composition.ts +++ b/src/daemon/worker-composition.ts @@ -3,7 +3,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { EventBus } from "../bus/index.js"; import { fitHostFacts, fitHostLoad, type ProtocolRange } from "../contract/index.js"; -import { HostLoadSampler } from "../host-load/index.js"; +import { HostLoadSampler, MemoryPressureTracker } from "../host-load/index.js"; import { type EventHistoryHandle, HISTORY_DB_NAME } from "../history/index.js"; import { type Config, @@ -240,10 +240,19 @@ export async function composeWorker( options.hostLoadProbe === undefined ? productionHostLoadProbe({ dataDirectory, platform: process.platform }) : options.hostLoadProbe; + const memoryPressure = + hostLoadProbe === null + ? undefined + : new MemoryPressureTracker({ clock, config: config.memoryPressure }); const hostLoad = hostLoadProbe === null ? undefined - : new HostLoadSampler({ clock, logger: logger.child("host-load"), probe: hostLoadProbe }); + : new HostLoadSampler({ + clock, + logger: logger.child("host-load"), + onReading: (reading) => memoryPressure?.observe(reading), + probe: hostLoadProbe, + }); const decisions = new SerializedDecision(); const components = new ComponentInstaller({ clock, @@ -499,6 +508,18 @@ export async function composeWorker( physicalDeviceWatcher: leasing.physicalDeviceWatcher, hostFacts: () => fitHostFacts(hostFacts.current()), ...(hostLoad === undefined ? {} : { hostLoad, load: () => fitHostLoad(hostLoad.current()) }), + ...(memoryPressure === undefined + ? {} + : { + memoryPressure: { + current: () => { + const state = memoryPressure.current(); + if (state === undefined) return undefined; + const { readingAt: _readingAt, ...figures } = state; + return figures; + }, + }, + }), instanceId, host: new DaemonEndpointHost({ connector: ipc, diff --git a/src/host-load/index.ts b/src/host-load/index.ts index c3e1e3723..444f36daa 100644 --- a/src/host-load/index.ts +++ b/src/host-load/index.ts @@ -1 +1,10 @@ -export { HostLoadSampler } from "./sampler.js"; +export { HostLoadSampler, type HostLoadReading } from "./sampler.js"; +export { + MemoryPressureTracker, + type MemoryPressureCause, + type MemoryPressureConfig, + type MemoryPressureLevel, + type MemoryPressureRule, + type MemoryPressureState, + type MemoryPressureStep, +} from "./memory-pressure.js"; diff --git a/src/host-load/memory-pressure.ts b/src/host-load/memory-pressure.ts new file mode 100644 index 000000000..dcb2a859d --- /dev/null +++ b/src/host-load/memory-pressure.ts @@ -0,0 +1,107 @@ +import type { Clock, MemoryCounters } from "../ports/index.js"; + +export type MemoryPressureLevel = "normal" | "warn" | "critical"; +export type MemoryPressureStep = "none" | "warming-paused" | "new-devices-paused"; + +export interface MemoryPressureRule { + readonly level: MemoryPressureLevel | "off"; + readonly minAvailablePercent: number; +} + +export interface MemoryPressureConfig { + readonly enabled: boolean; + readonly pauseWarming: MemoryPressureRule; + readonly pauseNewDevices: MemoryPressureRule; + readonly clearAfterMs: number; +} + +export interface MemoryPressureCause { + readonly trigger: "level" | "floor"; + readonly availablePercent: number; + readonly level?: MemoryPressureLevel; + readonly floorPercent?: number; +} + +export interface MemoryPressureState { + readonly step: MemoryPressureStep; + readonly since?: number; + readonly cause?: MemoryPressureCause; + readonly readingAt: number; +} + +interface MemoryPressureOptions { + readonly clock: Clock; + readonly config: MemoryPressureConfig; +} + +interface HeldStep { + readonly since: number; + readonly cause: MemoryPressureCause; +} + +const LEVEL_RANK: Record = { normal: 0, warn: 1, critical: 2 }; + +/** + * why: the step a worker is at, worked out from each host-load reading. A step comes on at the + * first reading that meets it and lifts `clearAfterMs` after the first reading that no longer does. + */ +export class MemoryPressureTracker { + #warming: HeldStep | undefined; + #newDevices: HeldStep | undefined; + #readingAt: number | undefined; + + constructor(private readonly options: MemoryPressureOptions) {} + + observe(reading: { readonly memory?: MemoryCounters }): void { + const now = this.options.clock.now(); + this.#readingAt = now; + const { config } = this.options; + const memory = config.enabled ? reading.memory : undefined; + this.#warming = this.#hold(this.#warming, config.pauseWarming, memory, now); + this.#newDevices = this.#hold(this.#newDevices, config.pauseNewDevices, memory, now); + } + + current(): MemoryPressureState | undefined { + if (this.#readingAt === undefined) return undefined; + const held = + this.#newDevices === undefined + ? this.#warming === undefined + ? undefined + : ({ held: this.#warming, step: "warming-paused" } as const) + : ({ held: this.#newDevices, step: "new-devices-paused" } as const); + if (held === undefined) return { readingAt: this.#readingAt, step: "none" }; + return { + cause: held.held.cause, + readingAt: this.#readingAt, + since: held.held.since, + step: held.step, + }; + } + + #hold( + held: HeldStep | undefined, + rule: MemoryPressureRule, + memory: MemoryCounters | undefined, + now: number, + ): HeldStep | undefined { + const cause = memory === undefined ? undefined : meets(rule, memory); + if (cause === undefined) return held; + return held ?? { cause, since: now }; + } +} + +function meets(rule: MemoryPressureRule, memory: MemoryCounters): MemoryPressureCause | undefined { + const exactPercent = (100 * memory.availableBytes) / memory.totalBytes; + const availablePercent = Math.floor(Math.min(100, Math.max(0, exactPercent))); + if ( + rule.level !== "off" && + memory.pressure !== undefined && + LEVEL_RANK[memory.pressure] >= LEVEL_RANK[rule.level] + ) { + return { availablePercent, level: memory.pressure, trigger: "level" }; + } + if (exactPercent < rule.minAvailablePercent) { + return { availablePercent, floorPercent: rule.minAvailablePercent, trigger: "floor" }; + } + return undefined; +} diff --git a/src/host-load/sampler.ts b/src/host-load/sampler.ts index 839929c32..b423d2c22 100644 --- a/src/host-load/sampler.ts +++ b/src/host-load/sampler.ts @@ -16,7 +16,7 @@ interface HostLoadCpu { readonly limited: boolean; } -interface HostLoadReading { +export interface HostLoadReading { readonly ageMs: number; readonly cpu?: HostLoadCpu; readonly memory?: MemoryCounters; @@ -27,6 +27,8 @@ interface HostLoadSamplerOptions { readonly clock: Clock; readonly probe: HostLoadProbe; readonly logger?: Logger; + /** why: called after each recorded reading, a failed read included, so a reader works from every reading and not from polling `current()`. */ + readonly onReading?: (reading: HostLoadReading) => void; } const SAMPLE_INTERVAL_MS = 15_000; @@ -144,6 +146,7 @@ export class HostLoadSampler { } this.#reading = { at: now, parts: {} }; this.#markFirstReading(); + this.#notify(); return; } for (const part of ["cpu", "memory", "disk"] as const) { @@ -159,6 +162,18 @@ export class HostLoadSampler { if (counters.disk !== undefined) parts.disk = counters.disk; this.#reading = { at: now, parts }; this.#markFirstReading(); + this.#notify(); + } + + #notify(): void { + const { onReading } = this.options; + const reading = this.current(); + if (onReading === undefined || reading === undefined) return; + try { + onReading(reading); + } catch (error) { + this.#logger.warn("Host load reading listener failed", { error: describe(error) }); + } } #note(part: Part, present: boolean): void { From 3d9d2d0aa62309f93acdcafdfb32e727d2290e3d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:12:08 +0100 Subject: [PATCH 03/26] docs(config): list the memoryPressure keys (#1361) --- website/src/content/docs/docs/reference/configuration.mdx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index e72852e0a..7eb86900e 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -157,6 +157,12 @@ Any other field in a target stops the daemon from starting. A target never downl | `idle.shutdownAfterMs` | non-negative number | `600000` (10 min) | How long an unused running device stays up before it is shut down. Devices the warm pool keeps are exempt. | Worker | | `idle.deleteAfterMs` | non-negative number | `3600000` (1 h) | How long a shut-down device stays on disk before it is deleted. | Worker | | `diskPressure.freeBytesThreshold` | non-negative number | `10737418240` (10 GiB) | Free disk space below which the machine is under disk pressure: idle devices are deleted sooner. | Worker | +| `memoryPressure.enabled` | boolean | `true` | Work out a memory pressure step from the host's memory. Off, a worker is never paused for memory. | Worker | +| `memoryPressure.pauseWarming.level` | `normal`, `warn`, `critical` or `off` | `warn` | The macOS memory pressure level at which the worker is at the `warming-paused` step. Other systems report no level. `off` ignores the level. | Worker | +| `memoryPressure.pauseWarming.minAvailablePercent` | number 0 to 100 | `20` | Available memory, as a percent of total, below which the worker is at the `warming-paused` step. `0` ignores the floor. | Worker | +| `memoryPressure.pauseNewDevices.level` | `normal`, `warn`, `critical` or `off` | `critical` | The level at which the worker is at the `new-devices-paused` step. | Worker | +| `memoryPressure.pauseNewDevices.minAvailablePercent` | number 0 to 100 | `10` | Available memory percent below which the worker is at the `new-devices-paused` step. | Worker | +| `memoryPressure.clearAfterMs` | non-negative number | `60000` (1 min) | How long a step stays on after the first reading that no longer meets it. A reading that meets it again restarts the wait. | Worker | | `health.enabled` | boolean | `true` | Watch leased simulators and emulators for crashes and reboot them under their lease. Physical devices are watched either way. | Worker | | `health.probeIntervalMs` | positive number | `30000` (30 s) | How often leased devices are checked, and how often enrolled physical devices are checked for presence. | Worker | | `health.stableObservations` | positive integer | `2` | Bad readings in a row before a device counts as crashed, or a physical device as absent. | Worker | From 59ae41eb56f8c32aeb6183041b498a66fd85b4cf Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:13:07 +0100 Subject: [PATCH 04/26] test: an operator's memoryPressure config is defaulted and checked (#1361) --- src/core/config.test.ts | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/core/config.test.ts b/src/core/config.test.ts index e928b3fd8..58d7d3758 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -1924,6 +1924,42 @@ describe("loadConfig modes (ADR 0005)", () => { expect((await load({}, { role: "worker" })).mode).toBe("worker"); }); + it("defaults the memoryPressure section, refuses a bad value naming its key, and warns a gateway it is worker-only", async () => { + expect((await load({})).memoryPressure).toEqual({ + clearAfterMs: 60_000, + enabled: true, + pauseNewDevices: { level: "critical", minAvailablePercent: 10 }, + pauseWarming: { level: "warn", minAvailablePercent: 20 }, + }); + const accepted = await load({ + memoryPressure: { pauseWarming: { level: "off", minAvailablePercent: 0 }, clearAfterMs: 0 }, + }); + expect(accepted.memoryPressure).toMatchObject({ + clearAfterMs: 0, + pauseWarming: { level: "off", minAvailablePercent: 0 }, + }); + + const refused = [ + { memoryPressure: { pauseWarming: { level: "bogus" } } }, + { memoryPressure: { pauseNewDevices: { minAvailablePercent: 101 } } }, + { memoryPressure: { pauseNewDevices: { minAvailablePercent: -1 } } }, + { memoryPressure: { clearAfterMs: -1 } }, + ]; + const keys = [ + "memoryPressure.pauseWarming.level", + "memoryPressure.pauseNewDevices.minAvailablePercent", + "memoryPressure.pauseNewDevices.minAvailablePercent", + "memoryPressure.clearAfterMs", + ]; + for (const [index, file] of refused.entries()) { + await expect(load(file)).rejects.toThrow(keys[index]!); + } + + const warn = vi.fn(); + await load({ memoryPressure: { enabled: false } }, { role: "gateway", warn }); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring "memoryPressure"')); + }); + it("HTTP defaults to port 4700 for a gateway and 4701 for a worker", async () => { expect((await load({}, { role: "gateway" })).http.port).toBe(4700); expect((await load({})).http.port).toBe(4701); From 053c082e287f62b8854defc7fd3889cae69e31fd Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:13:25 +0100 Subject: [PATCH 05/26] feat(config): the memoryPressure section is checked on load (#1361) --- src/core/config.ts | 12 ++++++++++++ src/core/validation.ts | 15 +++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/core/config.ts b/src/core/config.ts index dd9a917ce..f64e2abf8 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -28,6 +28,7 @@ import { booleanValue, ConfigError, integerInRange, + numberInRange, invalidValue, nonNegativeNumber, numberAtLeast, @@ -1163,6 +1164,12 @@ export function configValidators( }), exec: objectValidator({ timeoutMs: positiveNumber }), diskPressure: objectValidator({ freeBytesThreshold: nonNegativeNumber }), + memoryPressure: objectValidator({ + enabled: booleanValue, + pauseWarming: memoryPressureRuleValidator, + pauseNewDevices: memoryPressureRuleValidator, + clearAfterMs: nonNegativeNumber, + }), eventBuffer: objectValidator({ capacity: positiveInteger }), log: objectValidator({ level: stringUnion(LOG_LEVELS), rotateBytes: positiveInteger }), eventLog: objectValidator({ @@ -1206,6 +1213,11 @@ export function configValidators( }; } +const memoryPressureRuleValidator = objectValidator({ + level: stringUnion(["normal", "warn", "critical", "off"]), + minAvailablePercent: numberInRange(0, 100), +}); + function driverValidators( driverSections: readonly DriverConfigEntry[], platform: Platform, diff --git a/src/core/validation.ts b/src/core/validation.ts index 6a99853f9..daf193cf4 100644 --- a/src/core/validation.ts +++ b/src/core/validation.ts @@ -127,6 +127,21 @@ export function numberAtLeast(minimum: number): Validator { }; } +export function numberInRange(minimum: number, maximum: number): Validator { + return (value: unknown, path: string) => { + if ( + typeof value !== "number" || + !Number.isFinite(value) || + value < minimum || + value > maximum + ) { + throw invalidValue(path, `a number between ${minimum} and ${maximum}`); + } + + return value; + }; +} + export function integerInRange(minimum: number, maximum: number): Validator { return (value: unknown, path: string) => { if ( From 96e5358a431e573dedf89af21e32675b4e2aa7aa Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:13:55 +0100 Subject: [PATCH 06/26] test: status.get reports each level, floor and off case of the memory pressure step (#1361) --- src/daemon/main-host-load.test.ts | 69 +++++++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 7 deletions(-) diff --git a/src/daemon/main-host-load.test.ts b/src/daemon/main-host-load.test.ts index aac35b95c..68914fea0 100644 --- a/src/daemon/main-host-load.test.ts +++ b/src/daemon/main-host-load.test.ts @@ -385,18 +385,73 @@ describe("startDaemon memory pressure", () => { }; it("reports in status.get the memory pressure step the worker's reading meets", async () => { - const cases = [ + const level = (availablePercent: number, name: "warn" | "critical") => ({ + availablePercent, + level: name, + trigger: "level", + }); + const floor = (availablePercent: number, floorPercent: number) => ({ + availablePercent, + floorPercent, + trigger: "floor", + }); + const cases: readonly { + readonly reading: HostLoadCounters; + readonly expected: unknown; + readonly overrides?: NonNullable["memoryPressure"]; + }[] = [ + { reading: memoryReading("normal", 34), expected: { step: "none" } }, { reading: memoryReading("warn", 34), - expected: { - cause: { availablePercent: 34, level: "warn", trigger: "level" }, - since: 1_000, - step: "warming-paused", + expected: { cause: level(34, "warn"), since: 1_000, step: "warming-paused" }, + }, + { + reading: memoryReading("critical", 34), + expected: { cause: level(34, "critical"), since: 1_000, step: "new-devices-paused" }, + }, + { + reading: memoryReading("warn", 8), + expected: { cause: floor(8, 10), since: 1_000, step: "new-devices-paused" }, + }, + { + reading: memoryReading("critical", 8), + expected: { cause: level(8, "critical"), since: 1_000, step: "new-devices-paused" }, + }, + { + reading: memoryReading("normal", 8), + expected: { cause: floor(8, 10), since: 1_000, step: "new-devices-paused" }, + }, + { reading: memoryReading(undefined, 25), expected: { step: "none" } }, + { + reading: memoryReading(undefined, 15), + expected: { cause: floor(15, 20), since: 1_000, step: "warming-paused" }, + }, + { + reading: memoryReading(undefined, 9.9), + expected: { cause: floor(9, 10), since: 1_000, step: "new-devices-paused" }, + }, + { + reading: memoryReading("critical", 5), + overrides: { + pauseNewDevices: { level: "off", minAvailablePercent: 0 }, + pauseWarming: { level: "off", minAvailablePercent: 0 }, }, + expected: { step: "none" }, + }, + { + reading: memoryReading("critical", 5), + overrides: { enabled: false }, + expected: { step: "none" }, }, ]; - for (const { reading, expected } of cases) { - const { daemon } = await startOnClock({ hostLoadProbe: new FakeHostLoadProbe(reading) }); + for (const { reading, expected, overrides } of cases) { + const { daemon } = await startOnClock({ + configOverrides: { + ...STANDALONE_OFF, + ...(overrides === undefined ? {} : { memoryPressure: overrides }), + }, + hostLoadProbe: new FakeHostLoadProbe(reading), + }); await expect .poll(async () => (await statusOf(daemon)).capacity?.memoryPressure) .toEqual(expected); From 488f5b1363c5813201ff572c68288007430081d6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:14:42 +0100 Subject: [PATCH 07/26] test: a memory pressure step lifts only after clearAfterMs with no meeting reading (#1361) --- src/daemon/main-host-load.test.ts | 77 +++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/src/daemon/main-host-load.test.ts b/src/daemon/main-host-load.test.ts index 68914fea0..5a52d1383 100644 --- a/src/daemon/main-host-load.test.ts +++ b/src/daemon/main-host-load.test.ts @@ -458,3 +458,80 @@ describe("startDaemon memory pressure", () => { } }); }); + +describe("startDaemon memory pressure hold", () => { + const statusOf = async (daemon: DaemonServer) => + (await daemon.dispatch("status.get", {}, hostLoadAdmin)) as { + capacity?: { memoryPressure?: unknown }; + load?: { ageMs: number }; + }; + + it("lifts a memory pressure step only after clearAfterMs with no meeting reading", async () => { + const level = (name: "warn" | "critical") => ({ + availablePercent: 34, + level: name, + trigger: "level", + }); + const warming = (since: number) => ({ + cause: level("warn"), + since, + step: "warming-paused", + }); + const calm = memoryReading("normal", 34); + const scenarios = [ + { + // why: calm from +15 s lifts at +75 s: 45 s after the first calm reading it still holds. + name: "calm for 45 s still holds, for 60 s lifts", + readings: [ + { reading: memoryReading("warn", 34), expected: warming(1_000) }, + { reading: calm, expected: warming(1_000) }, + { reading: calm, expected: warming(1_000) }, + { reading: calm, expected: warming(1_000) }, + { reading: calm, expected: warming(1_000) }, + { reading: calm, expected: { step: "none" } }, + ], + }, + { + name: "a meeting reading restarts the hold and keeps since and cause", + readings: [ + { reading: memoryReading("warn", 34), expected: warming(1_000) }, + { reading: calm, expected: warming(1_000) }, + { reading: memoryReading("warn", 30), expected: warming(1_000) }, + { reading: calm, expected: warming(1_000) }, + { reading: calm, expected: warming(1_000) }, + { reading: calm, expected: warming(1_000) }, + { reading: calm, expected: warming(1_000) }, + { reading: calm, expected: { step: "none" } }, + ], + }, + { + name: "new devices paused falls to warming paused with warming's own since and cause", + readings: [ + { reading: memoryReading("warn", 34), expected: warming(1_000) }, + { + reading: memoryReading("critical", 34), + expected: { cause: level("critical"), since: 16_000, step: "new-devices-paused" }, + }, + ...[0, 1, 2, 3].map(() => ({ + reading: memoryReading("warn", 34), + expected: { cause: level("critical"), since: 16_000, step: "new-devices-paused" }, + })), + { reading: memoryReading("warn", 34), expected: warming(1_000) }, + ], + }, + ]; + for (const { name, readings } of scenarios) { + const probe = new FakeHostLoadProbe(); + const { clock, daemon } = await startOnClock({ hostLoadProbe: probe }); + for (const [index, { reading, expected }] of readings.entries()) { + if (index > 0) clock.advance(15_000); + await expect.poll(() => probe.reads, { message: name }).toBe(index + 1); + probe.answer(reading); + await expect.poll(async () => (await statusOf(daemon)).load?.ageMs).toBe(0); + expect((await statusOf(daemon)).capacity?.memoryPressure, `${name} #${index}`).toEqual( + expected, + ); + } + } + }); +}); From a8eaa14811067af89674563ca03d8fcdd04e8194 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:14:59 +0100 Subject: [PATCH 08/26] feat(host-load): a memory pressure step lifts clearAfterMs after the first reading that no longer meets it (#1361) --- src/daemon/server.ts | 3 +- src/daemon/worker-composition.ts | 1 + src/host-load/memory-pressure.ts | 66 +++++++++++++++++++++----------- 3 files changed, 47 insertions(+), 23 deletions(-) diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 9a9360f42..f2c4ed545 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -124,7 +124,7 @@ export interface DaemonServerCommonOptions { readonly eventBus: EventBus; readonly host: ConnectionHost; readonly hostLoad?: { start(): void; dispose(): void }; - readonly memoryPressure?: { current(): StatusMemoryPressure | undefined }; + readonly memoryPressure?: { current(): StatusMemoryPressure | undefined; dispose(): void }; readonly logger?: Logger; readonly protocolVersion?: number | ProtocolRange; readonly version: string; @@ -658,6 +658,7 @@ export class DaemonServer { for (const unsubscribe of this.#unsubscribeLeaseLost.splice(0)) unsubscribe(); this.#ownerRoutedFacts.dispose(); this.options.hostLoad?.dispose(); + this.options.memoryPressure?.dispose(); this.#workerDispatcher?.dispose(); this.#engine?.reaper.dispose(); this.#engine?.healthMonitor?.dispose(); diff --git a/src/daemon/worker-composition.ts b/src/daemon/worker-composition.ts index 66ccbb757..d5ea25e51 100644 --- a/src/daemon/worker-composition.ts +++ b/src/daemon/worker-composition.ts @@ -512,6 +512,7 @@ export async function composeWorker( ? {} : { memoryPressure: { + dispose: () => memoryPressure.dispose(), current: () => { const state = memoryPressure.current(); if (state === undefined) return undefined; diff --git a/src/host-load/memory-pressure.ts b/src/host-load/memory-pressure.ts index dcb2a859d..e4f47dbc7 100644 --- a/src/host-load/memory-pressure.ts +++ b/src/host-load/memory-pressure.ts @@ -1,4 +1,4 @@ -import type { Clock, MemoryCounters } from "../ports/index.js"; +import type { Clock, MemoryCounters, TimerHandle } from "../ports/index.js"; export type MemoryPressureLevel = "normal" | "warn" | "critical"; export type MemoryPressureStep = "none" | "warming-paused" | "new-devices-paused"; @@ -37,8 +37,11 @@ interface MemoryPressureOptions { interface HeldStep { readonly since: number; readonly cause: MemoryPressureCause; + clearTimer?: TimerHandle; } +type StepKey = "warming" | "newDevices"; + const LEVEL_RANK: Record = { normal: 0, warn: 1, critical: 2 }; /** @@ -46,8 +49,10 @@ const LEVEL_RANK: Record = { normal: 0, warn: 1, cr * first reading that meets it and lifts `clearAfterMs` after the first reading that no longer does. */ export class MemoryPressureTracker { - #warming: HeldStep | undefined; - #newDevices: HeldStep | undefined; + readonly #held: Record = { + newDevices: undefined, + warming: undefined, + }; #readingAt: number | undefined; constructor(private readonly options: MemoryPressureOptions) {} @@ -57,37 +62,54 @@ export class MemoryPressureTracker { this.#readingAt = now; const { config } = this.options; const memory = config.enabled ? reading.memory : undefined; - this.#warming = this.#hold(this.#warming, config.pauseWarming, memory, now); - this.#newDevices = this.#hold(this.#newDevices, config.pauseNewDevices, memory, now); + this.#hold("warming", config.pauseWarming, memory, now); + this.#hold("newDevices", config.pauseNewDevices, memory, now); } current(): MemoryPressureState | undefined { if (this.#readingAt === undefined) return undefined; - const held = - this.#newDevices === undefined - ? this.#warming === undefined - ? undefined - : ({ held: this.#warming, step: "warming-paused" } as const) - : ({ held: this.#newDevices, step: "new-devices-paused" } as const); - if (held === undefined) return { readingAt: this.#readingAt, step: "none" }; - return { - cause: held.held.cause, - readingAt: this.#readingAt, - since: held.held.since, - step: held.step, - }; + const newDevices = this.#held.newDevices; + const warming = this.#held.warming; + if (newDevices !== undefined) return state("new-devices-paused", newDevices, this.#readingAt); + if (warming !== undefined) return state("warming-paused", warming, this.#readingAt); + return { readingAt: this.#readingAt, step: "none" }; + } + + dispose(): void { + for (const key of ["warming", "newDevices"] as const) { + this.#cancelClear(this.#held[key]); + this.#held[key] = undefined; + } } #hold( - held: HeldStep | undefined, + key: StepKey, rule: MemoryPressureRule, memory: MemoryCounters | undefined, now: number, - ): HeldStep | undefined { + ): void { + const held = this.#held[key]; const cause = memory === undefined ? undefined : meets(rule, memory); - if (cause === undefined) return held; - return held ?? { cause, since: now }; + if (cause !== undefined) { + this.#cancelClear(held); + this.#held[key] ??= { cause, since: now }; + return; + } + if (held === undefined || held.clearTimer !== undefined) return; + held.clearTimer = this.options.clock.setTimer(this.options.config.clearAfterMs, () => { + this.#held[key] = undefined; + }); } + + #cancelClear(held: HeldStep | undefined): void { + if (held?.clearTimer === undefined) return; + this.options.clock.cancel(held.clearTimer); + delete held.clearTimer; + } +} + +function state(step: MemoryPressureStep, held: HeldStep, readingAt: number): MemoryPressureState { + return { cause: held.cause, readingAt, since: held.since, step }; } function meets(rule: MemoryPressureRule, memory: MemoryCounters): MemoryPressureCause | undefined { From 09d3e1c4dae62db0e8ba91a58feec41ffa5e2602 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:15:21 +0100 Subject: [PATCH 09/26] test: no usable memory reading is no step, at once (#1361) --- src/daemon/main-host-load.test.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/daemon/main-host-load.test.ts b/src/daemon/main-host-load.test.ts index 5a52d1383..61d2a44a9 100644 --- a/src/daemon/main-host-load.test.ts +++ b/src/daemon/main-host-load.test.ts @@ -534,4 +534,32 @@ describe("startDaemon memory pressure hold", () => { } } }); + + it("drops the step at once when there is no usable reading: a failed read or no memory part, and with host load off no field", async () => { + const { disk, cpu } = COUNTERS; + const unusable = [ + new Error("sysctl failed"), + { cpu: cpu!, disk: disk! } satisfies HostLoadCounters, + ]; + for (const next of unusable) { + const probe = new FakeHostLoadProbe(); + const { clock, daemon } = await startOnClock({ hostLoadProbe: probe }); + await expect.poll(() => probe.reads).toBe(1); + probe.answer(memoryReading("critical", 5)); + await expect + .poll(async () => (await statusOf(daemon)).capacity?.memoryPressure) + .toMatchObject({ cause: { availablePercent: 5 }, step: "new-devices-paused" }); + + clock.advance(15_000); + await expect.poll(() => probe.reads).toBe(2); + probe.answer(next); + + await expect + .poll(async () => (await statusOf(daemon)).capacity?.memoryPressure) + .toEqual({ step: "none" }); + } + + const off = await startOnClock({ hostLoadProbe: null }); + expect((await statusOf(off.daemon)).capacity).not.toHaveProperty("memoryPressure"); + }); }); From af4226e8612bd78cf1c0748b8367bf4f0db5227b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:15:40 +0100 Subject: [PATCH 10/26] feat(host-load): a reading with no memory drops the memory pressure step at once (#1361) --- src/host-load/memory-pressure.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/host-load/memory-pressure.ts b/src/host-load/memory-pressure.ts index e4f47dbc7..22452cd26 100644 --- a/src/host-load/memory-pressure.ts +++ b/src/host-load/memory-pressure.ts @@ -62,6 +62,10 @@ export class MemoryPressureTracker { this.#readingAt = now; const { config } = this.options; const memory = config.enabled ? reading.memory : undefined; + if (memory === undefined) { + this.#dropAll(); + return; + } this.#hold("warming", config.pauseWarming, memory, now); this.#hold("newDevices", config.pauseNewDevices, memory, now); } @@ -76,20 +80,19 @@ export class MemoryPressureTracker { } dispose(): void { + this.#dropAll(); + } + + #dropAll(): void { for (const key of ["warming", "newDevices"] as const) { this.#cancelClear(this.#held[key]); this.#held[key] = undefined; } } - #hold( - key: StepKey, - rule: MemoryPressureRule, - memory: MemoryCounters | undefined, - now: number, - ): void { + #hold(key: StepKey, rule: MemoryPressureRule, memory: MemoryCounters, now: number): void { const held = this.#held[key]; - const cause = memory === undefined ? undefined : meets(rule, memory); + const cause = meets(rule, memory); if (cause !== undefined) { this.#cancelClear(held); this.#held[key] ??= { cause, since: now }; From 49407e51323eea09563fa9c3d1e6965d90c0c61b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:15:48 +0100 Subject: [PATCH 11/26] test: a tracker with no reading for 60 s drops its step (#1361) --- src/host-load/memory-pressure.test.ts | 37 +++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/host-load/memory-pressure.test.ts diff --git a/src/host-load/memory-pressure.test.ts b/src/host-load/memory-pressure.test.ts new file mode 100644 index 000000000..25df4c6a5 --- /dev/null +++ b/src/host-load/memory-pressure.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; + +import { FakeClock } from "../ports/index.js"; +import { MemoryPressureTracker } from "./index.js"; + +const CONFIG = { + clearAfterMs: 60_000, + enabled: true, + pauseNewDevices: { level: "critical", minAvailablePercent: 10 }, + pauseWarming: { level: "warn", minAvailablePercent: 20 }, +} as const; + +const memory = (pressure: "normal" | "warn" | "critical") => ({ + availableBytes: 3_400, + limited: false, + pressure, + swapUsedBytes: 0, + totalBytes: 10_000, +}); + +describe("MemoryPressureTracker", () => { + it("drops the step at once when no reading arrives for 60 s", () => { + const clock = new FakeClock(1_000); + const tracker = new MemoryPressureTracker({ clock, config: CONFIG }); + tracker.observe({ memory: memory("warn") }); + expect(tracker.current()).toMatchObject({ since: 1_000, step: "warming-paused" }); + + clock.advance(59_999); + expect(tracker.current()).toMatchObject({ step: "warming-paused" }); + + clock.advance(1); + const dropped = tracker.current(); + expect(dropped?.step).toBe("none"); + expect(dropped).not.toHaveProperty("since"); + expect(dropped).not.toHaveProperty("cause"); + }); +}); From 34211618c0f34ab9d1057946c15b00df226420ed Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:16:06 +0100 Subject: [PATCH 12/26] feat(host-load): a tracker with no reading for 60 s drops its step (#1361) --- src/host-load/memory-pressure.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/host-load/memory-pressure.ts b/src/host-load/memory-pressure.ts index 22452cd26..68fc80d16 100644 --- a/src/host-load/memory-pressure.ts +++ b/src/host-load/memory-pressure.ts @@ -42,6 +42,9 @@ interface HeldStep { type StepKey = "warming" | "newDevices"; +/** why: a reading older than this says nothing about the host now (ADR 0068 §1). */ +const STALE_AFTER_MS = 60_000; + const LEVEL_RANK: Record = { normal: 0, warn: 1, critical: 2 }; /** @@ -54,12 +57,14 @@ export class MemoryPressureTracker { warming: undefined, }; #readingAt: number | undefined; + #staleTimer: TimerHandle | undefined; constructor(private readonly options: MemoryPressureOptions) {} observe(reading: { readonly memory?: MemoryCounters }): void { const now = this.options.clock.now(); this.#readingAt = now; + this.#armStale(); const { config } = this.options; const memory = config.enabled ? reading.memory : undefined; if (memory === undefined) { @@ -80,9 +85,19 @@ export class MemoryPressureTracker { } dispose(): void { + if (this.#staleTimer !== undefined) this.options.clock.cancel(this.#staleTimer); + this.#staleTimer = undefined; this.#dropAll(); } + #armStale(): void { + if (this.#staleTimer !== undefined) this.options.clock.cancel(this.#staleTimer); + this.#staleTimer = this.options.clock.setTimer(STALE_AFTER_MS, () => { + this.#staleTimer = undefined; + this.#dropAll(); + }); + } + #dropAll(): void { for (const key of ["warming", "newDevices"] as const) { this.#cancelClear(this.#held[key]); From a0ec5c089a17534333bdf53609eaded8b695a453 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:17:00 +0100 Subject: [PATCH 13/26] test: the worker emits memory.pressure-changed once per step change (#1361) --- src/daemon/main-host-load.test.ts | 39 +++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/daemon/main-host-load.test.ts b/src/daemon/main-host-load.test.ts index 61d2a44a9..0a3d7b655 100644 --- a/src/daemon/main-host-load.test.ts +++ b/src/daemon/main-host-load.test.ts @@ -562,4 +562,43 @@ describe("startDaemon memory pressure hold", () => { const off = await startOnClock({ hostLoadProbe: null }); expect((await statusOf(off.daemon)).capacity).not.toHaveProperty("memoryPressure"); }); + + it("emits memory.pressure-changed once per step change with the new step's cause", async () => { + const level = (name: "warn" | "critical") => ({ + availablePercent: 34, + level: name, + trigger: "level", + }); + const warn = memoryReading("warn", 34); + const calm = memoryReading("normal", 34); + // why: warming comes on at +0 s, new devices at +15 s and lifts 60 s after its first non-meeting reading at +30 s; calm from +105 s lifts warming at +165 s. + const readings = [ + warn, + memoryReading("critical", 34), + ...[0, 1, 2, 3, 4].map(() => warn), + ...[0, 1, 2, 3, 4].map(() => calm), + calm, + ]; + const probe = new FakeHostLoadProbe(); + const { clock, daemon } = await startOnClock({ hostLoadProbe: probe }); + for (const [index, reading] of readings.entries()) { + if (index > 0) clock.advance(15_000); + await expect.poll(() => probe.reads).toBe(index + 1); + probe.answer(reading); + await expect.poll(async () => (await statusOf(daemon)).load?.ageMs).toBe(0); + } + + const replayed = (await daemon.dispatch("events.replay", {}, hostLoadAdmin)) as readonly { + event: string; + payload: unknown; + }[]; + expect( + replayed.filter((entry) => entry.event === "memory.pressure-changed").map((e) => e.payload), + ).toEqual([ + { cause: level("warn"), from: "none", to: "warming-paused" }, + { cause: level("critical"), from: "warming-paused", to: "new-devices-paused" }, + { cause: level("warn"), from: "new-devices-paused", to: "warming-paused" }, + { from: "warming-paused", to: "none" }, + ]); + }); }); From 1972d7c909ace28908bf3ac106af0bfe8d1b4374 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:17:32 +0100 Subject: [PATCH 14/26] feat(bus): memory.pressure-changed is emitted once per step change (#1361) --- docs/internal/EVENTS.md | 1 + src/bus/index.test.ts | 1 + src/bus/index.ts | 10 +++++ src/daemon/worker-composition.ts | 2 +- src/host-load/memory-pressure.test.ts | 7 +++- src/host-load/memory-pressure.ts | 39 +++++++++++++++---- .../content/docs/docs/reference/events.mdx | 1 + 7 files changed, 51 insertions(+), 10 deletions(-) diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 608f92ffa..7fd94c1ec 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -157,6 +157,7 @@ left behind (#79), each when there is one. | `daemon.update-started` | from, to, forced | an update began: `daemon.update` resolved the version and entered `waiting` or `installing` (ADR 0042 §11); `forced` is whether it was asked with `force` at the start | UpdateCoordinator | implemented | | `daemon.update-failed` | stage (`installing` or `restarting`), from, to, message (at most 2000 characters) | an update ended without a new daemon: the updater reported a failed line or exited non-zero while this daemon runs (it serves again), or a rolled back update's result file was read at start (ADR 0042 §7, §8) | UpdateCoordinator | implemented | | `disk.pressure-detected` | free bytes, threshold | free disk crossed under the configured threshold (edge-triggered: once per crossing, not once per tick while it persists) | CleanupReaper | implemented | +| `memory.pressure-changed` | from, to (`none`, `warming-paused`, `new-devices-paused`), cause (the new step's reading: trigger `level` or `floor`, availablePercent, level or floorPercent; absent to `none`) | a worker's memory pressure step changed: once per change, never per reading; no usable reading drops the step at once (ADR 0068 §5) | MemoryPressureTracker | implemented | | `cleanup.executed` | rule name, action, target, reason | cleanup executor committed a proposed action | CleanupExecutor | implemented | | `doctor.reconciled` | drift findings | daemon reconciliation completed | Doctor | implemented | | `driver.root-rejected` | platform, root path, reason (not-absolute/missing-marker/invalid-marker/wrong-instance/symlink/wrong-owner/wrong-permissions/non-empty-unowned-root/unreadable/invalid-device-set/device-set-changed) | a driver's device root failed ownership validation at startup, or (iOS) `drivers.ios.deviceSet` was not `simlock` or `default`, conflicted with `drivers.ios.deviceRoot` or with `ios.simulator.headless: false`, or was switched with simulators left in the set being given up (ADR 0048; `root` is then the configured value or the set holding them), so that platform's driver did not start | DaemonServer | implemented | diff --git a/src/bus/index.test.ts b/src/bus/index.test.ts index 39b36a0a1..c93605968 100644 --- a/src/bus/index.test.ts +++ b/src/bus/index.test.ts @@ -52,6 +52,7 @@ const EVENT_NAMES: Record = { "daemon.update-failed": true, "daemon.update-started": true, "disk.pressure-detected": true, + "memory.pressure-changed": true, "cleanup.executed": true, "doctor.reconciled": true, "driver.root-rejected": true, diff --git a/src/bus/index.ts b/src/bus/index.ts index 1b7b6ddd4..ba313414f 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -270,6 +270,16 @@ export interface EventMap { readonly forced: boolean; }; "disk.pressure-detected": { readonly freeBytes: number; readonly threshold: number }; + "memory.pressure-changed": { + readonly from: "none" | "warming-paused" | "new-devices-paused"; + readonly to: "none" | "warming-paused" | "new-devices-paused"; + readonly cause?: { + readonly trigger: "level" | "floor"; + readonly availablePercent: number; + readonly level?: "normal" | "warn" | "critical"; + readonly floorPercent?: number; + }; + }; "device.foreign-provenance-detected": { readonly deviceId: string; readonly platform: string; diff --git a/src/daemon/worker-composition.ts b/src/daemon/worker-composition.ts index d5ea25e51..7cbe04eaa 100644 --- a/src/daemon/worker-composition.ts +++ b/src/daemon/worker-composition.ts @@ -243,7 +243,7 @@ export async function composeWorker( const memoryPressure = hostLoadProbe === null ? undefined - : new MemoryPressureTracker({ clock, config: config.memoryPressure }); + : new MemoryPressureTracker({ clock, config: config.memoryPressure, eventBus }); const hostLoad = hostLoadProbe === null ? undefined diff --git a/src/host-load/memory-pressure.test.ts b/src/host-load/memory-pressure.test.ts index 25df4c6a5..fac7cd7d4 100644 --- a/src/host-load/memory-pressure.test.ts +++ b/src/host-load/memory-pressure.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; +import { EventBus } from "../bus/index.js"; import { FakeClock } from "../ports/index.js"; import { MemoryPressureTracker } from "./index.js"; @@ -21,7 +22,11 @@ const memory = (pressure: "normal" | "warn" | "critical") => ({ describe("MemoryPressureTracker", () => { it("drops the step at once when no reading arrives for 60 s", () => { const clock = new FakeClock(1_000); - const tracker = new MemoryPressureTracker({ clock, config: CONFIG }); + const tracker = new MemoryPressureTracker({ + clock, + config: CONFIG, + eventBus: new EventBus(clock), + }); tracker.observe({ memory: memory("warn") }); expect(tracker.current()).toMatchObject({ since: 1_000, step: "warming-paused" }); diff --git a/src/host-load/memory-pressure.ts b/src/host-load/memory-pressure.ts index 68fc80d16..8aab5784f 100644 --- a/src/host-load/memory-pressure.ts +++ b/src/host-load/memory-pressure.ts @@ -1,3 +1,4 @@ +import type { EventBus } from "../bus/index.js"; import type { Clock, MemoryCounters, TimerHandle } from "../ports/index.js"; export type MemoryPressureLevel = "normal" | "warn" | "critical"; @@ -32,6 +33,7 @@ export interface MemoryPressureState { interface MemoryPressureOptions { readonly clock: Clock; readonly config: MemoryPressureConfig; + readonly eventBus: EventBus; } interface HeldStep { @@ -67,12 +69,14 @@ export class MemoryPressureTracker { this.#armStale(); const { config } = this.options; const memory = config.enabled ? reading.memory : undefined; - if (memory === undefined) { - this.#dropAll(); - return; - } - this.#hold("warming", config.pauseWarming, memory, now); - this.#hold("newDevices", config.pauseNewDevices, memory, now); + this.#changing(() => { + if (memory === undefined) { + this.#dropAll(); + return; + } + this.#hold("warming", config.pauseWarming, memory, now); + this.#hold("newDevices", config.pauseNewDevices, memory, now); + }); } current(): MemoryPressureState | undefined { @@ -94,10 +98,27 @@ export class MemoryPressureTracker { if (this.#staleTimer !== undefined) this.options.clock.cancel(this.#staleTimer); this.#staleTimer = this.options.clock.setTimer(STALE_AFTER_MS, () => { this.#staleTimer = undefined; - this.#dropAll(); + this.#changing(() => this.#dropAll()); }); } + /** why: the event follows the change it reports, and only a change of step is one. */ + #changing(mutate: () => void): void { + const from = this.current(); + mutate(); + const to = this.current(); + if (from === undefined || to === undefined || from.step === to.step) return; + this.options.eventBus.emit( + "memory.pressure-changed", + { + from: from.step, + to: to.step, + ...(to.cause === undefined ? {} : { cause: to.cause }), + }, + "host-load", + ); + } + #dropAll(): void { for (const key of ["warming", "newDevices"] as const) { this.#cancelClear(this.#held[key]); @@ -115,7 +136,9 @@ export class MemoryPressureTracker { } if (held === undefined || held.clearTimer !== undefined) return; held.clearTimer = this.options.clock.setTimer(this.options.config.clearAfterMs, () => { - this.#held[key] = undefined; + this.#changing(() => { + this.#held[key] = undefined; + }); }); } diff --git a/website/src/content/docs/docs/reference/events.mdx b/website/src/content/docs/docs/reference/events.mdx index 484268b0c..7b11cdc21 100644 --- a/website/src/content/docs/docs/reference/events.mdx +++ b/website/src/content/docs/docs/reference/events.mdx @@ -195,6 +195,7 @@ as `incompatible` in `simlock --gateway worker list`. | `doctor.reconciled` | Simlock compared its records with the devices that exist (at start and on `simlock doctor`). | `driftFindings` | Relayed | | `cleanup.executed` | Cleanup shut down or deleted an idle device. | `ruleName` (`idle-shutdown` or `idle-destroy`), `action` (`shutdown` or `destroy`), `target`, `reason` | Relayed | | `disk.pressure-detected` | Free disk space fell below `diskPressure.freeBytesThreshold`. Once per crossing. | `freeBytes`, `threshold` | Relayed | +| `memory.pressure-changed` | A worker's memory pressure step changed, from `none`, `warming-paused` or `new-devices-paused` to another. Once per change, never per reading. See `memoryPressure.*`. | `from`, `to`, `cause` (`trigger` `level` or `floor`, `availablePercent`, `level` or `floorPercent`; absent when `to` is `none`) | Relayed | | `driver.root-rejected` | A platform did not start because of its device folder: the folder failed its ownership check, or (iOS) `drivers.ios.deviceSet` was invalid, conflicted with `ios.simulator.headless: false`, or was switched while simulators were left in the old set. `simlock doctor` says what to fix. Reasons include `invalid-device-set` and `device-set-changed`; `root` is then the configured value or the set that holds the leftovers. | `platform`, `root`, `reason` | Relayed | | `driver.adb-server-rejected` | The adb server Simlock runs for its emulators could not start (see `drivers.android.adbServerPort`), so Android did not start. | `port`, `reason` (`occupied`, `start-failed`, `invalid-port`) | Relayed | From 075ac4af3349876b90dda5d8fdc286d995d506f1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:18:08 +0100 Subject: [PATCH 15/26] test: simlock status prints the Memory pressure line (#1361) --- src/cli/index.test.ts | 46 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 629dd450e..f676336d4 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6098,6 +6098,52 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = expect(await print(EMPTY_STATUS)).not.toContain("Load:"); expect(await print(STARTING)).not.toContain("Load:"); }); + + it("simlock status prints the Memory pressure line with the step, when it began and why, and none when there is no step", async () => { + const at = (hours: number, minutes: number) => + new Date(2026, 10, 6, hours, minutes).getTime(); + const memoryLine = async (memoryPressure: unknown) => { + const stdout = await print({ + ...EMPTY_STATUS, + capacity: { ...EMPTY_STATUS.capacity, memoryPressure }, + load: LOAD, + } as StatusGetOutput); + return stdout.split("\n").find((line) => line.startsWith("Memory pressure:")); + }; + + expect( + await memoryLine({ + cause: { availablePercent: 34, level: "warn", trigger: "level" }, + since: at(9, 12), + step: "warming-paused", + }), + ).toBe("Memory pressure: warming paused since 09:12 (pressure warn)"); + expect( + await memoryLine({ + cause: { availablePercent: 8, floorPercent: 10, trigger: "floor" }, + since: at(9, 40), + step: "new-devices-paused", + }), + ).toBe("Memory pressure: new devices paused since 09:40 (8% available, floor 10%)"); + expect(await memoryLine({ step: "none" })).toBeUndefined(); + expect(await memoryLine(undefined)).toBeUndefined(); + + const stdout = await print({ + ...EMPTY_STATUS, + capacity: { + ...EMPTY_STATUS.capacity, + memoryPressure: { + cause: { availablePercent: 34, level: "warn", trigger: "level" }, + since: at(9, 12), + step: "warming-paused", + }, + }, + load: LOAD, + } as StatusGetOutput); + expect(stdout).toContain( + `${FULL_LINE}Memory pressure: warming paused since 09:12 (pressure warn)\nRunning global`, + ); + }); }); it("simlock status prints the console address when HTTP is enabled", async () => { From e06b55000309d52b72f0596b598954a218145646 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:18:20 +0100 Subject: [PATCH 16/26] feat(cli): simlock status prints the Memory pressure line (#1361) --- src/cli/format.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/cli/format.ts b/src/cli/format.ts index 3e10a7e32..0297d6316 100644 --- a/src/cli/format.ts +++ b/src/cli/format.ts @@ -154,6 +154,20 @@ function formatLoadLine( return `Load: ${[...cpuPart, ...memoryParts, ...diskPart, age].join(" · ")}`; } +function memoryPressureLines(status: StatusGetOutput): string[] { + const pressure = status.capacity?.memoryPressure; + if (pressure === undefined || pressure.step === "none") return []; + const { cause, since } = pressure; + const words = pressure.step === "warming-paused" ? "warming paused" : "new devices paused"; + const at = new Date(since ?? 0); + const pad = (value: number): string => String(value).padStart(2, "0"); + const why = + cause?.trigger === "floor" + ? `${cause.availablePercent}% available, floor ${cause.floorPercent}%` + : `pressure ${cause?.level}`; + return [`Memory pressure: ${words} since ${pad(at.getHours())}:${pad(at.getMinutes())} (${why})`]; +} + function loadLines(status: StatusGetOutput): string[] { return status.load === undefined ? [] @@ -295,6 +309,7 @@ export function formatStatus(status: StatusGetOutput, now: number, cliVersion?: ...daemonLines(daemon, cliVersion), `Host: ${formatHost(host)}`, ...loadLines(status), + ...memoryPressureLines(status), ...historyLines(status.history), globalLine, ...capacityLines, From 0b75633a36cf04f9b9c7bb054d086706a01c3490 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:18:48 +0100 Subject: [PATCH 17/26] test: simlock list --requests names host memory pressure (#1361) --- src/cli/index.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index f676336d4..8a12b8a31 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -9570,6 +9570,7 @@ describe("simlock list --requests", () => { ["behind-earlier-request", "ios", "behind an earlier request"], ["device-limit", "ios", "full: device limit"], ["ram-budget", "ios", "full: RAM budget"], + ["memory-pressure", "ios", "full: host memory pressure"], ["global-running-limit", "ios", "full: running limit"], ["platform-running-limit", "ios", "full: running limit for iOS"], ["platform-running-limit", "android", "full: running limit for Android"], @@ -9686,6 +9687,7 @@ describe("simlock list --requests", () => { ["full", "ios", undefined, "full"], ["full", "ios", "device-limit", "full: device limit"], ["full", "ios", "ram-budget", "full: RAM budget"], + ["full", "ios", "memory-pressure", "full: host memory pressure"], ["full", "ios", "global-running-limit", "full: running limit"], ["full", "ios", "platform-running-limit", "full: running limit for iOS"], ["full", "android", "platform-running-limit", "full: running limit for Android"], From 7699520d89b7bc3ae6ee676badef586236edf4e6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:19:32 +0100 Subject: [PATCH 18/26] feat(cli): simlock list --requests names host memory pressure (#1361) --- src/cli/commands/list.ts | 1 + src/contract/errors.ts | 1 + src/contract/lease-schemas.ts | 2 ++ src/contract/operations.test.ts | 12 ++++++++++++ src/contract/status-schemas.ts | 1 + src/core/capacity/strategy.ts | 1 + src/gateway/routing/pipeline.ts | 1 + src/http/lease-declarations.ts | 8 +++++++- src/leasing/acquisition-planner.ts | 1 + ui/src/model/waiting.ts | 1 + 10 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/cli/commands/list.ts b/src/cli/commands/list.ts index 7aca52e2e..ca983718c 100644 --- a/src/cli/commands/list.ts +++ b/src/cli/commands/list.ts @@ -54,6 +54,7 @@ const WAITING_REASON_TEXT: Readonly "Every matching device is leased or absent", "platform-running-limit": (platform) => `Full: running limit for ${platform === "ios" ? "iOS" : "Android"}`, + "memory-pressure": () => "Full: host memory pressure", "ram-budget": () => "Full: RAM budget", "waiting-for-device": () => "A matching device is starting", }; diff --git a/src/contract/errors.ts b/src/contract/errors.ts index 8f5a67edf..f1be51ea0 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -38,6 +38,7 @@ export interface ErrorDetailsMap { readonly capacityReason?: | "device-limit" | "ram-budget" + | "memory-pressure" | "global-running-limit" | "platform-running-limit"; }; diff --git a/src/contract/lease-schemas.ts b/src/contract/lease-schemas.ts index 893659f12..1a26ecc24 100644 --- a/src/contract/lease-schemas.ts +++ b/src/contract/lease-schemas.ts @@ -94,6 +94,7 @@ const waitingReasonSchema = z.enum([ "behind-earlier-request", "device-limit", "ram-budget", + "memory-pressure", "global-running-limit", "platform-running-limit", "waiting-for-device", @@ -103,6 +104,7 @@ const waitingReasonSchema = z.enum([ export const capacityReasonSchema = z.enum([ "device-limit", "ram-budget", + "memory-pressure", "global-running-limit", "platform-running-limit", ]); diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index b99fd8983..2a4996bbd 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -1322,6 +1322,12 @@ describe("operation input/output round trips", () => { }, exec: { timeoutMs: 1 }, diskPressure: { freeBytesThreshold: 1 }, + memoryPressure: { + clearAfterMs: 60_000, + enabled: true, + pauseNewDevices: { level: "critical", minAvailablePercent: 10 }, + pauseWarming: { level: "warn", minAvailablePercent: 20 }, + }, drivers: {}, eventBuffer: { capacity: 1 }, log: { level: "info", rotateBytes: 1 }, @@ -1402,6 +1408,12 @@ describe("operation input/output round trips", () => { exec: { timeoutMs: 1 }, drivers: {}, diskPressure: { freeBytesThreshold: 1 }, + memoryPressure: { + clearAfterMs: 60_000, + enabled: true, + pauseNewDevices: { level: "critical", minAvailablePercent: 10 }, + pauseWarming: { level: "warn", minAvailablePercent: 20 }, + }, eventBuffer: { capacity: 1 }, log: { level: "info", rotateBytes: 1 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, diff --git a/src/contract/status-schemas.ts b/src/contract/status-schemas.ts index fc1aafa7a..c3bebba57 100644 --- a/src/contract/status-schemas.ts +++ b/src/contract/status-schemas.ts @@ -81,6 +81,7 @@ const warmPoolShortSchema = z.enum([ "running-limit", "reserve", "ram-budget", + "memory-pressure", ]); const warmPoolTargetSchema = z.object({ diff --git a/src/core/capacity/strategy.ts b/src/core/capacity/strategy.ts index c4503466a..fb7e8c596 100644 --- a/src/core/capacity/strategy.ts +++ b/src/core/capacity/strategy.ts @@ -30,6 +30,7 @@ export interface RamBudget { export type CapacityRefusalReason = | "device-limit" | "ram-budget" + | "memory-pressure" | "global-running-limit" | "platform-running-limit"; diff --git a/src/gateway/routing/pipeline.ts b/src/gateway/routing/pipeline.ts index 6fd856004..f1004217d 100644 --- a/src/gateway/routing/pipeline.ts +++ b/src/gateway/routing/pipeline.ts @@ -18,6 +18,7 @@ export interface RoutableRequest { export type CapacityReason = | "device-limit" | "ram-budget" + | "memory-pressure" | "global-running-limit" | "platform-running-limit"; diff --git a/src/http/lease-declarations.ts b/src/http/lease-declarations.ts index 3bff2db37..bb2fb5500 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -263,7 +263,13 @@ export const leaseRequestCreateRoute = declareRoute({ 503: { fields: { capacityReason: z - .enum(["device-limit", "ram-budget", "global-running-limit", "platform-running-limit"]) + .enum([ + "device-limit", + "ram-budget", + "memory-pressure", + "global-running-limit", + "platform-running-limit", + ]) .optional(), }, headers: { diff --git a/src/leasing/acquisition-planner.ts b/src/leasing/acquisition-planner.ts index c879de234..d3ca1f34f 100644 --- a/src/leasing/acquisition-planner.ts +++ b/src/leasing/acquisition-planner.ts @@ -62,6 +62,7 @@ export type WaitingReason = const CAPACITY_WAITING_REASON: Record = { "device-limit": "device-limit", "global-running-limit": "global-running-limit", + "memory-pressure": "memory-pressure", "platform-running-limit": "platform-running-limit", "ram-budget": "ram-budget", }; diff --git a/ui/src/model/waiting.ts b/ui/src/model/waiting.ts index 054d90266..88564a9d1 100644 --- a/ui/src/model/waiting.ts +++ b/ui/src/model/waiting.ts @@ -65,6 +65,7 @@ const WHY_TEXT: Readonly< "global-running-limit": () => "Full: running limit", "no-free-physical": () => "Every matching device is leased or absent", "platform-running-limit": (platform) => `Full: running limit for ${platform}`, + "memory-pressure": () => "Full: host memory pressure", "ram-budget": () => "Full: RAM budget", "waiting-for-device": () => "A matching device is starting", }; From c58b03d4ec273ec037f763da81e1e6902a52eb59 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:19:47 +0100 Subject: [PATCH 19/26] test: the console's waiting list names host memory pressure (#1361) --- ui/src/model/waiting.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ui/src/model/waiting.test.ts b/ui/src/model/waiting.test.ts index 1c9bd404b..ed2e1c277 100644 --- a/ui/src/model/waiting.test.ts +++ b/ui/src/model/waiting.test.ts @@ -184,6 +184,7 @@ describe("why a request waits", () => { ["behind-earlier-request", "ios", "Behind an earlier request"], ["device-limit", "ios", "Full: device limit"], ["ram-budget", "ios", "Full: RAM budget"], + ["memory-pressure", "ios", "Full: host memory pressure"], ["global-running-limit", "ios", "Full: running limit"], ["platform-running-limit", "ios", "Full: running limit for iOS"], ["platform-running-limit", "android", "Full: running limit for Android"], @@ -261,6 +262,7 @@ describe("the waiting table on a gateway", () => { ["full", undefined, "Full"], ["full", "device-limit", "Full: device limit"], ["full", "ram-budget", "Full: RAM budget"], + ["full", "memory-pressure", "Full: host memory pressure"], ["full", "global-running-limit", "Full: running limit"], ["no-free-physical", undefined, "Every matching device is leased or absent"], ["not-chosen", undefined, "Not chosen this time"], From 933d14bc1572d0b81ebf78bd44d6ac9cc55ee873 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:19:58 +0100 Subject: [PATCH 20/26] test: the console's waiting list names host memory pressure (#1361) --- ui/src/model/waiting.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/src/model/waiting.test.ts b/ui/src/model/waiting.test.ts index ed2e1c277..5d6377654 100644 --- a/ui/src/model/waiting.test.ts +++ b/ui/src/model/waiting.test.ts @@ -204,7 +204,7 @@ describe("why a request waits", () => { expect(field).toBeDefined(); const listed = (field as { unwrap(): { options: readonly string[] } }).unwrap().options; - expect(listed).toHaveLength(7); + expect(listed).toHaveLength(8); for (const reason of listed) { const why = whyOf(withReason(reason)); expect(why).toBeDefined(); From baec6ab8f8fee6c27ee7633bd762f8dc00630e01 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:21:14 +0100 Subject: [PATCH 21/26] feat(alerts): memory.pressure-changed is an alert event with a Slack message (#1361) --- src/alerts/alerts.test.ts | 41 ++++++++++++++++++- src/alerts/formats/slack/messages.ts | 12 ++++++ src/core/config.ts | 1 + .../src/content/docs/docs/gateway/alerts.mdx | 1 + .../docs/docs/reference/configuration.mdx | 2 +- 5 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/alerts/alerts.test.ts b/src/alerts/alerts.test.ts index c03abf2fe..ea0763030 100644 --- a/src/alerts/alerts.test.ts +++ b/src/alerts/alerts.test.ts @@ -113,14 +113,26 @@ describe("alerts", () => { module: "quarantine", }); + const pressure = (h: Harness) => + h.eventBus.republish({ + id: "evt_pressure", + timestamp: 43, + event: "memory.pressure-changed", + payload: { from: "none", to: "warming-paused", workerId: "wrk_8" } as never, + module: "host-load", + }); + it.each([ ["a gateway-own worker.connected", gatewayOwn, "wrk_1"], ["a republished device.quarantine-abandoned", relayed, "wrk_9"], + ["a republished memory.pressure-changed", pressure, "wrk_8"], ])( "posts a listed event to a generic destination as the envelope with Content-Type, User-Agent, X-Simlock-Event, X-Simlock-Delivery and a signature that verifies with the secret (%s)", async (_name, emitEnvelope, workerId) => { const h = harness([ - destination({ events: ["worker.connected", "device.quarantine-abandoned"] }), + destination({ + events: ["worker.connected", "device.quarantine-abandoned", "memory.pressure-changed"], + }), ]); const envelope = emitEnvelope(h); await settle(); @@ -157,7 +169,7 @@ describe("alerts", () => { }); }); - it("each of the eleven events posts its message word for word", async () => { + it("each of the twelve events posts its message word for word", async () => { const rows: [EventName, Record, string][] = [ [ "worker.connected", @@ -221,6 +233,31 @@ describe("alerts", () => { { workerId: "wrk_1", platform: "ios", componentId: "runtime-18", error: "no space" }, "❌ Installing ios runtime-18 on wrk_1 failed: no space.", ], + [ + "memory.pressure-changed", + { + workerId: "wrk_1", + from: "none", + to: "new-devices-paused", + cause: { trigger: "level", availablePercent: 8, level: "critical" }, + }, + "🧠 Worker wrk_1 paused new devices: memory pressure critical.", + ], + [ + "memory.pressure-changed", + { + workerId: "wrk_1", + from: "none", + to: "warming-paused", + cause: { trigger: "floor", availablePercent: 15, floorPercent: 20 }, + }, + "🧠 Worker wrk_1 paused warming: 15% of memory available (floor 20%).", + ], + [ + "memory.pressure-changed", + { workerId: "wrk_1", from: "warming-paused", to: "none" }, + "✅ Worker wrk_1 is no longer under memory pressure.", + ], ]; const events = [...new Set(rows.map(([event]) => event))] as AlertDestination["events"]; const h = harness([slackDestination({ events })]); diff --git a/src/alerts/formats/slack/messages.ts b/src/alerts/formats/slack/messages.ts index 9a8496d3b..7785ea13e 100644 --- a/src/alerts/formats/slack/messages.ts +++ b/src/alerts/formats/slack/messages.ts @@ -15,6 +15,13 @@ function more(count: unknown): string { : ""; } +function pressureCause(cause: unknown): string { + const fields = (typeof cause === "object" && cause !== null ? cause : {}) as Payload; + return fields.trigger === "level" + ? `memory pressure ${part(fields.level)}` + : `${part(fields.availablePercent)}% of memory available (floor ${part(fields.floorPercent)}%)`; +} + export const SLACK_MESSAGES: Record = { "worker.connected": (p, worker) => p.version === undefined @@ -35,6 +42,11 @@ export const SLACK_MESSAGES: Record `💾 Worker ${worker} is low on disk: ${formatBytes(p.freeBytes)} free (threshold ${formatBytes(p.threshold)}).`, + "memory.pressure-changed": (p, worker) => { + if (p.to === "none") return `✅ Worker ${worker} is no longer under memory pressure.`; + const paused = p.to === "new-devices-paused" ? "new devices" : "warming"; + return `🧠 Worker ${worker} paused ${paused}: ${pressureCause(p.cause)}.`; + }, "component.install-failed": (p, worker) => `❌ Installing ${part(p.platform)} ${part(p.componentId)} on ${worker} failed: ${part(p.error)}.`, "alerts.test-sent": (p) => diff --git a/src/core/config.ts b/src/core/config.ts index f64e2abf8..ddc32e5ee 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -104,6 +104,7 @@ export const ALERT_EVENTS = [ "device.recovery-failed", "device.stalled-transition-detected", "disk.pressure-detected", + "memory.pressure-changed", "component.install-failed", ] as const; export type AlertEventName = (typeof ALERT_EVENTS)[number]; diff --git a/website/src/content/docs/docs/gateway/alerts.mdx b/website/src/content/docs/docs/gateway/alerts.mdx index 8e2ec1bfc..6b68cf787 100644 --- a/website/src/content/docs/docs/gateway/alerts.mdx +++ b/website/src/content/docs/docs/gateway/alerts.mdx @@ -23,6 +23,7 @@ Only a gateway sends alerts. A worker on its own sends none; to watch a single w | `device.recovery-failed` | A device crashed during a lease and could not be brought back. | | `device.stalled-transition-detected` | A device has been booting or being cleaned for far longer than expected. | | `disk.pressure-detected` | A worker's free disk space fell below its `diskPressure.freeBytesThreshold`. | +| `memory.pressure-changed` | A worker's memory pressure step changed: it paused warming, paused new devices, or is no longer under pressure. | | `component.install-failed` | Installing a runtime or system image on a worker failed. | When the gateway itself stops, it sends no `worker.disconnected` for its workers. diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index 7eb86900e..526859f82 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -287,7 +287,7 @@ Each destination: | `name` | yes | Lowercase letters, digits and dashes, starting with a letter, at most 32 characters. Unique. | | `format` | yes | `generic` (signed JSON) or `slack` (a message for a Slack incoming webhook). | | `url` | yes | `https://`, or `http://` to `localhost`, `127.0.0.1` or `[::1]`. No user name or password in it. | -| `events` | yes | Non-empty list, each event once, from: `worker.connected`, `worker.disconnected`, `worker.rejected`, `worker.drain-started`, `worker.drain-ended`, `device.quarantine-abandoned`, `device.quarantine-stranded`, `device.recovery-failed`, `device.stalled-transition-detected`, `disk.pressure-detected`, `component.install-failed`. | +| `events` | yes | Non-empty list, each event once, from: `worker.connected`, `worker.disconnected`, `worker.rejected`, `worker.drain-started`, `worker.drain-ended`, `device.quarantine-abandoned`, `device.quarantine-stranded`, `device.recovery-failed`, `device.stalled-transition-detected`, `disk.pressure-detected`, `memory.pressure-changed`, `component.install-failed`. | | `secret` | `generic`: yes; `slack`: not allowed | The key the gateway signs each `generic` message with. | ```json title="~/.simlock/gateway/config.json" From 81063762b5dc27a04c1f433dac2d5dc4c3967170 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:22:14 +0100 Subject: [PATCH 22/26] feat(core): createCore takes the worker's memory pressure reader (#1361) --- src/core/core-ports.ts | 20 ++++++++++++++++++++ src/core/create-core.ts | 10 ++++++++++ src/daemon/worker-composition.ts | 1 + src/host-load/memory-pressure.ts | 9 +++++++++ 4 files changed, 40 insertions(+) diff --git a/src/core/core-ports.ts b/src/core/core-ports.ts index c4ab5ba8e..7d57d1ebf 100644 --- a/src/core/core-ports.ts +++ b/src/core/core-ports.ts @@ -21,6 +21,26 @@ export interface CapacityReader { atRamBudget(platform: CapacityPlatform): boolean; } +/** why: ADR 0068 §2: what core reads of a worker's memory pressure step, so it never names host-load. */ +export interface MemoryPressureReader { + /** why: the step with when and why it began, and when the latest reading came; `undefined` while host load is off or before its first reading. */ + current(): + | { + readonly step: "none" | "warming-paused" | "new-devices-paused"; + readonly since?: number; + readonly cause?: { + readonly trigger: "level" | "floor"; + readonly availablePercent: number; + readonly level?: "normal" | "warn" | "critical"; + readonly floorPercent?: number; + }; + readonly readingAt: number; + } + | undefined; + /** why: calls the listener after each reading, once the step is updated; returns the way to stop. */ + onReading(listener: () => void): () => void; +} + /** Read-only view of the warm pool, used by daemon status and doctor. */ export interface WarmPoolReader { /** The pool as its last pass left it. */ diff --git a/src/core/create-core.ts b/src/core/create-core.ts index 91f570b9f..75f296091 100644 --- a/src/core/create-core.ts +++ b/src/core/create-core.ts @@ -17,6 +17,7 @@ import type { WarmPoolReader, CatalogReader, LeaseExpirer, + MemoryPressureReader, PassthroughResolver, } from "./core-ports.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; @@ -47,6 +48,8 @@ export type CoreConfig = DoctorConfig & Pick undefined, + onReading: () => () => undefined, +}; + export function createCore(options: CoreOptions): Core { const { decisions, registry } = options; let ports: CorePorts | undefined; @@ -391,6 +400,7 @@ export function createCore(options: CoreOptions): Core { return { capacity, capacityReader, + memoryPressure: options.memoryPressure ?? NO_MEMORY_PRESSURE, warmPoolReader: warmPool, warmKinds: { forget: (match) => warmPool.forgetKinds(match) }, baselines, diff --git a/src/daemon/worker-composition.ts b/src/daemon/worker-composition.ts index 7cbe04eaa..eac463f49 100644 --- a/src/daemon/worker-composition.ts +++ b/src/daemon/worker-composition.ts @@ -267,6 +267,7 @@ export async function composeWorker( }); const modelPreferences = modelPreferenceWiring(config, drivers); const core = createCore({ + ...(memoryPressure === undefined ? {} : { memoryPressure }), clock, components, config, diff --git a/src/host-load/memory-pressure.ts b/src/host-load/memory-pressure.ts index 8aab5784f..1a0677ff5 100644 --- a/src/host-load/memory-pressure.ts +++ b/src/host-load/memory-pressure.ts @@ -60,6 +60,7 @@ export class MemoryPressureTracker { }; #readingAt: number | undefined; #staleTimer: TimerHandle | undefined; + readonly #listeners = new Set<() => void>(); constructor(private readonly options: MemoryPressureOptions) {} @@ -77,6 +78,7 @@ export class MemoryPressureTracker { this.#hold("warming", config.pauseWarming, memory, now); this.#hold("newDevices", config.pauseNewDevices, memory, now); }); + for (const listener of this.#listeners) listener(); } current(): MemoryPressureState | undefined { @@ -88,7 +90,14 @@ export class MemoryPressureTracker { return { readingAt: this.#readingAt, step: "none" }; } + /** why: a reader acts once per reading, after the step has been updated and its event sent. */ + onReading(listener: () => void): () => void { + this.#listeners.add(listener); + return () => this.#listeners.delete(listener); + } + dispose(): void { + this.#listeners.clear(); if (this.#staleTimer !== undefined) this.options.clock.cancel(this.#staleTimer); this.#staleTimer = undefined; this.#dropAll(); From 1fdee6b89c118593173a4751791e11dab2213528 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:22:46 +0100 Subject: [PATCH 23/26] docs(memory-pressure): the status line, the full reasons and the host-load manual (#1361) --- src/host-load/AGENTS.md | 2 ++ website/src/content/docs/docs/reference/errors.mdx | 2 +- website/src/content/docs/docs/worker/capacity.mdx | 1 + website/src/content/docs/docs/worker/console.mdx | 1 + website/src/content/docs/docs/worker/monitoring.mdx | 1 + 5 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/host-load/AGENTS.md b/src/host-load/AGENTS.md index 416c0edfb..4fa64b9b3 100644 --- a/src/host-load/AGENTS.md +++ b/src/host-load/AGENTS.md @@ -10,3 +10,5 @@ Does: samples this host's CPU, memory and disk on a fixed interval and keeps the - `firstReading()` settles at the first recorded read, whatever it found, or at dispose. A worker dials its gateway only after it, so the first `status.get` the gateway reads has a load. - `hostLoadProbe: null` turns sampling off: no sampler, no `load` field. - Readers fit the reading to the contract with `fitHostLoad`. +- `MemoryPressureTracker` works out the memory pressure step from each recorded reading (ADR 0068). A step comes on at the first reading that meets it and lifts `clearAfterMs` after the first reading that does not, unless one meets it again. A reading with no memory part, `enabled: false`, or no reading for 60 s is `none` at once. +- The tracker emits `memory.pressure-changed` once per change of step, after the step is stored; `dispose` emits nothing. diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 0c5e3471d..32de67421 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -37,7 +37,7 @@ In a script, check `code`, not the message: the wording of a message can change, | Code | Exit | HTTP | Meaning | What to do | | --- | --- | --- | --- | --- | -| `NO_CAPACITY` | 11 | 503 | No device can start now, and the request was told not to wait (`--no-wait`). Through a gateway: no worker that takes requests can serve it. | Try again later, or drop `--no-wait` to queue. Over HTTP the answer carries `Retry-After: 5`. | +| `NO_CAPACITY` | 11 | 503 | No device can start now, and the request was told not to wait (`--no-wait`). Through a gateway: no worker that takes requests can serve it. | Try again later, or drop `--no-wait` to queue. Over HTTP the answer carries `Retry-After: 5`. The details name a `capacityReason`: `device-limit`, `ram-budget`, `memory-pressure`, `global-running-limit` or `platform-running-limit`. | | `DAEMON_UPDATING` | 1 | 503 | The daemon is updating (`simlock update`) and takes no new leases. A request that was waiting when the update began gets it too. A lease you already hold renews and releases as usual. | Run the command again once the daemon is back, or lease from another worker. | | `QUEUE_TIMEOUT` | 10 | 500 | The request waited in the queue for its whole `--timeout` and got no device. | Raise `--timeout`, or check `simlock list --requests` for why requests wait. | | `REQUESTER_ALREADY_LEASED` | 13 | 409 | Your requester identity already holds or waits for its limit of leases (`lease.maxPerRequester`, 1 by default, counted per platform when the operator sets a limit for each), or, with a limit per platform, has a request waiting on that platform. The message names your lease. | Release that lease first, or give each agent session its own identity. | diff --git a/website/src/content/docs/docs/worker/capacity.mdx b/website/src/content/docs/docs/worker/capacity.mdx index 95a18b3ec..a3887fe42 100644 --- a/website/src/content/docs/docs/worker/capacity.mdx +++ b/website/src/content/docs/docs/worker/capacity.mdx @@ -224,5 +224,6 @@ warm pool: enabled, reserve ios 1 android 0 | `device-limit` | The platform is at its device limit. | | `reserve` | The slot is held back by `warmPool.reserveRunning`. | | `ram-budget` | The device would not fit in the RAM budget. | +| `memory-pressure` | The host is short of memory and warming is paused (`memoryPressure.*`). | A line that is filling, or waiting behind a queued lease, shows no reason. `simlock doctor` warns when your targets add up to more devices than the running limit allows. diff --git a/website/src/content/docs/docs/worker/console.mdx b/website/src/content/docs/docs/worker/console.mdx index ecf6d6da8..c3a83a384 100644 --- a/website/src/content/docs/docs/worker/console.mdx +++ b/website/src/content/docs/docs/worker/console.mdx @@ -173,6 +173,7 @@ Select a request to see when it was made, its place, its stage and, for a `queue | Full: running limit | The worker runs as many devices as it may. | | Full: running limit for iOS | The worker runs as many iOS devices as it may (or Android). | | Full: RAM budget | Booting another device would go over the worker's RAM budget. | +| Full: host memory pressure | The worker's host is short of memory and has paused new devices (`memoryPressure.*`). | | A matching device is starting | A device that fits is booting and will serve it. | | Every matching device is leased or absent | The request names physical devices that are all in use or unplugged. | diff --git a/website/src/content/docs/docs/worker/monitoring.mdx b/website/src/content/docs/docs/worker/monitoring.mdx index dc5bcacb5..0e5893c21 100644 --- a/website/src/content/docs/docs/worker/monitoring.mdx +++ b/website/src/content/docs/docs/worker/monitoring.mdx @@ -44,6 +44,7 @@ What each line means: | `Console` | The web console's address. Shown only when HTTP is on. | | `Host` | The operating system, the CPU architecture, and the Xcode version the iOS tools report. | | `Load` | CPU, memory, swap and free disk, and how many seconds ago they were read. A part that could not be read says `unavailable`. | +| `Memory pressure` | Shown only while the worker has paused warming or new devices because the host is short of memory: the step, when it began (local time) and why, either `pressure warn` or the available memory against its floor. See `memoryPressure.*` in the [configuration reference](/simlock/docs/reference/configuration). | | `History` | Shown only when something is wrong with the event history. See [Troubleshooting](/simlock/docs/worker/troubleshooting#the-event-history-is-not-written). | | `Running global` | Devices running now, plus slots held for devices that are booting, out of the most that may run at once, and how many of the running ones are warm. | | `Capacity ios` / `Capacity android` | Per platform: `managed` is devices that exist out of the device limit; `running` is as above. `(over limit)` means more devices exist than the limit allows, for example after you lowered it. `(at RAM budget)` means no more devices fit in the memory set aside for them. | From c25c888dd4266723549645b923a30d5f48d72f8b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:23:59 +0100 Subject: [PATCH 24/26] refactor(host-load): export only what is used (#1361) --- src/contract/status-schemas.ts | 2 +- src/daemon/worker-composition.ts | 9 ++++++++- src/host-load/index.ts | 12 ++---------- src/host-load/memory-pressure.ts | 4 ++-- 4 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/contract/status-schemas.ts b/src/contract/status-schemas.ts index c3bebba57..94fce5c9c 100644 --- a/src/contract/status-schemas.ts +++ b/src/contract/status-schemas.ts @@ -36,7 +36,7 @@ const memoryPressureCauseSchema = z.object({ floorPercent: z.number().min(0).max(100).optional(), }); -export const statusMemoryPressureSchema = z.object({ +const statusMemoryPressureSchema = z.object({ step: memoryPressureStepSchema, since: z.number().finite().nonnegative().optional(), cause: memoryPressureCauseSchema.optional(), diff --git a/src/daemon/worker-composition.ts b/src/daemon/worker-composition.ts index eac463f49..d936b43dd 100644 --- a/src/daemon/worker-composition.ts +++ b/src/daemon/worker-composition.ts @@ -267,7 +267,14 @@ export async function composeWorker( }); const modelPreferences = modelPreferenceWiring(config, drivers); const core = createCore({ - ...(memoryPressure === undefined ? {} : { memoryPressure }), + ...(memoryPressure === undefined + ? {} + : { + memoryPressure: { + current: () => memoryPressure.current(), + onReading: (listener: () => void) => memoryPressure.onReading(listener), + }, + }), clock, components, config, diff --git a/src/host-load/index.ts b/src/host-load/index.ts index 444f36daa..9109a5b9b 100644 --- a/src/host-load/index.ts +++ b/src/host-load/index.ts @@ -1,10 +1,2 @@ -export { HostLoadSampler, type HostLoadReading } from "./sampler.js"; -export { - MemoryPressureTracker, - type MemoryPressureCause, - type MemoryPressureConfig, - type MemoryPressureLevel, - type MemoryPressureRule, - type MemoryPressureState, - type MemoryPressureStep, -} from "./memory-pressure.js"; +export { HostLoadSampler } from "./sampler.js"; +export { MemoryPressureTracker } from "./memory-pressure.js"; diff --git a/src/host-load/memory-pressure.ts b/src/host-load/memory-pressure.ts index 1a0677ff5..fa1fc92e9 100644 --- a/src/host-load/memory-pressure.ts +++ b/src/host-load/memory-pressure.ts @@ -4,12 +4,12 @@ import type { Clock, MemoryCounters, TimerHandle } from "../ports/index.js"; export type MemoryPressureLevel = "normal" | "warn" | "critical"; export type MemoryPressureStep = "none" | "warming-paused" | "new-devices-paused"; -export interface MemoryPressureRule { +interface MemoryPressureRule { readonly level: MemoryPressureLevel | "off"; readonly minAvailablePercent: number; } -export interface MemoryPressureConfig { +interface MemoryPressureConfig { readonly enabled: boolean; readonly pauseWarming: MemoryPressureRule; readonly pauseNewDevices: MemoryPressureRule; From ea85a2e645c8a452c6b57f40a03c53d9a7c37a77 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:32:00 +0100 Subject: [PATCH 25/26] test: audit probes for memory pressure (planner row, wire bounds, stale-drop event, hold restart) (#1361) Protocol-bump: none (tests and a docs line only) --- src/contract/operations.test.ts | 59 +++++++++++++++++++ src/daemon/main-host-load.test.ts | 1 + src/host-load/memory-pressure.test.ts | 20 +++++-- src/leasing/acquisition-planner.test.ts | 26 ++++++++ .../content/docs/docs/worker/monitoring.mdx | 2 +- 5 files changed, 102 insertions(+), 6 deletions(-) diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 2a4996bbd..9d5064d9b 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -638,6 +638,65 @@ describe("operation input/output round trips", () => { expect(OPERATIONS["status.get"].output.parse(status)).toBeDefined(); }); + describe("status.get memoryPressure", () => { + const host = { os: "macOS", osVersion: "15.5", arch: "arm64", tools: [] }; + const entry = { + atRamBudget: false, + limit: 1, + maxRunning: 1, + overLimit: false, + reserved: 0, + running: 0, + used: 0, + warm: 0, + }; + const parse = (memoryPressure: unknown) => + OPERATIONS["status.get"].output.safeParse({ + capacity: { + android: entry, + global: { maxRunning: 2, overLimit: false, reserved: 0, running: 0, warm: 0 }, + ios: entry, + memoryPressure, + }, + daemon: { + health: "running", + lastUpdateFailure: null, + latestVersion: null, + mode: "worker", + update: null, + version: "0.0.0-test", + }, + devices: [], + host, + leases: [], + queueDepth: 0, + }).success; + const floor = { availablePercent: 8, floorPercent: 10, trigger: "floor" }; + + it("a worker's block is bounded: the percent a whole number from 0 to 100, the floor 0 to 100, the time not negative", () => { + expect(parse({ step: "none" })).toBe(true); + expect(parse({ cause: floor, since: 0, step: "new-devices-paused" })).toBe(true); + expect( + parse({ cause: { ...floor, availablePercent: 100 }, since: 1, step: "warming-paused" }), + ).toBe(true); + for (const cause of [ + { ...floor, availablePercent: 101 }, + { ...floor, availablePercent: -1 }, + { ...floor, availablePercent: 8.5 }, + { ...floor, floorPercent: 101 }, + { ...floor, floorPercent: -1 }, + { ...floor, level: "bogus" }, + { ...floor, trigger: "other" }, + ]) { + expect(parse({ cause, since: 1, step: "warming-paused" })).toBe(false); + } + for (const since of [-1, Number.POSITIVE_INFINITY, Number.NaN]) { + expect(parse({ cause: floor, since, step: "warming-paused" })).toBe(false); + } + expect(parse({ step: "paused" })).toBe(false); + }); + }); + describe("status.get warmPool", () => { const host = { os: "macOS", osVersion: "15.5", arch: "arm64", tools: [] }; const warmPool = { diff --git a/src/daemon/main-host-load.test.ts b/src/daemon/main-host-load.test.ts index 0a3d7b655..42e8d5018 100644 --- a/src/daemon/main-host-load.test.ts +++ b/src/daemon/main-host-load.test.ts @@ -496,6 +496,7 @@ describe("startDaemon memory pressure hold", () => { readings: [ { reading: memoryReading("warn", 34), expected: warming(1_000) }, { reading: calm, expected: warming(1_000) }, + { reading: calm, expected: warming(1_000) }, { reading: memoryReading("warn", 30), expected: warming(1_000) }, { reading: calm, expected: warming(1_000) }, { reading: calm, expected: warming(1_000) }, diff --git a/src/host-load/memory-pressure.test.ts b/src/host-load/memory-pressure.test.ts index fac7cd7d4..f33230986 100644 --- a/src/host-load/memory-pressure.test.ts +++ b/src/host-load/memory-pressure.test.ts @@ -22,11 +22,8 @@ const memory = (pressure: "normal" | "warn" | "critical") => ({ describe("MemoryPressureTracker", () => { it("drops the step at once when no reading arrives for 60 s", () => { const clock = new FakeClock(1_000); - const tracker = new MemoryPressureTracker({ - clock, - config: CONFIG, - eventBus: new EventBus(clock), - }); + const eventBus = new EventBus(clock); + const tracker = new MemoryPressureTracker({ clock, config: CONFIG, eventBus }); tracker.observe({ memory: memory("warn") }); expect(tracker.current()).toMatchObject({ since: 1_000, step: "warming-paused" }); @@ -38,5 +35,18 @@ describe("MemoryPressureTracker", () => { expect(dropped?.step).toBe("none"); expect(dropped).not.toHaveProperty("since"); expect(dropped).not.toHaveProperty("cause"); + expect( + eventBus + .replay() + .filter((event) => event.event === "memory.pressure-changed") + .map((event) => event.payload), + ).toEqual([ + { + cause: { availablePercent: 34, level: "warn", trigger: "level" }, + from: "none", + to: "warming-paused", + }, + { from: "warming-paused", to: "none" }, + ]); }); }); diff --git a/src/leasing/acquisition-planner.test.ts b/src/leasing/acquisition-planner.test.ts index 2f70ecef9..f090b4c00 100644 --- a/src/leasing/acquisition-planner.test.ts +++ b/src/leasing/acquisition-planner.test.ts @@ -155,6 +155,32 @@ describe("AcquisitionPlanner", () => { claim.release(); }); + it("waits or rejects with memory-pressure when capacity refuses a new device for it", () => { + const real = createCapacityStrategy( + config.capacity, + new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ); + const claims = new DeviceOperationClaims(); + const refusing = new AcquisitionPlanner( + new CapacityCoordinator({ + canBoot: (target, devices) => real.canBoot(target, devices), + canProvision: () => ({ ok: false, reason: "memory-pressure" }), + canReserveRunning: (platform, devices, reservations) => + real.canReserveRunning(platform, devices, reservations), + deviceLimit: (platform) => real.deviceLimit(platform), + ramBudget: (devices) => real.ramBudget(devices), + runningCapacity: (devices, reservations) => real.runningCapacity(devices, reservations), + }), + claims, + ); + + expect(plan(refusing, [])).toEqual({ kind: "wait", reason: "memory-pressure" }); + expect(plan(refusing, [], { noWait: true })).toEqual({ + kind: "no-capacity", + reason: "memory-pressure", + }); + }); + it("waits or rejects when policy cannot reserve capacity", () => { const { planner: acquisitionPlanner } = planner(); const leased = device("leased", "leased"); diff --git a/website/src/content/docs/docs/worker/monitoring.mdx b/website/src/content/docs/docs/worker/monitoring.mdx index 0e5893c21..2f1beec62 100644 --- a/website/src/content/docs/docs/worker/monitoring.mdx +++ b/website/src/content/docs/docs/worker/monitoring.mdx @@ -73,7 +73,7 @@ simlock list --requests Request req_3c8e1f52-9a4d-4b7e-8f20-6d1a5c9e3b74: codex:7a1d4e9b-2c3f-4e8a-b6d0-1f5c8a3e9d27, ios iPhone 16 18.4, queued at 1, waiting 42s — full: running limit for iOS ``` -Each waiting request shows who asked, the device it asked for, its place in the queue and the reason it waits: `full: device limit`, `full: running limit`, `full: running limit for iOS`, `full: RAM budget`, `behind an earlier request`, `a matching device is starting`, or `every matching device is leased or absent` for a physical device. +Each waiting request shows who asked, the device it asked for, its place in the queue and the reason it waits: `full: device limit`, `full: running limit`, `full: running limit for iOS`, `full: RAM budget`, `full: host memory pressure`, `behind an earlier request`, `a matching device is starting`, or `every matching device is leased or absent` for a physical device. ## Read the event stream From 8932aaba0b84137f87de7872bb841c5d7b1c0e6f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 18:43:20 +0100 Subject: [PATCH 26/26] fix(host-load): a floor cause on macOS carries the level; CLI test covers the floor; trim manual (#1361) --- docs/internal/EVENTS.md | 2 +- src/cli/index.test.ts | 59 +++++++++---------- src/daemon/main-host-load.test.ts | 7 ++- src/host-load/AGENTS.md | 3 +- src/host-load/memory-pressure.ts | 7 ++- src/source-hygiene.test.ts | 2 +- .../content/docs/docs/reference/events.mdx | 2 +- 7 files changed, 42 insertions(+), 40 deletions(-) diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 7fd94c1ec..cedb99f1d 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -157,7 +157,7 @@ left behind (#79), each when there is one. | `daemon.update-started` | from, to, forced | an update began: `daemon.update` resolved the version and entered `waiting` or `installing` (ADR 0042 §11); `forced` is whether it was asked with `force` at the start | UpdateCoordinator | implemented | | `daemon.update-failed` | stage (`installing` or `restarting`), from, to, message (at most 2000 characters) | an update ended without a new daemon: the updater reported a failed line or exited non-zero while this daemon runs (it serves again), or a rolled back update's result file was read at start (ADR 0042 §7, §8) | UpdateCoordinator | implemented | | `disk.pressure-detected` | free bytes, threshold | free disk crossed under the configured threshold (edge-triggered: once per crossing, not once per tick while it persists) | CleanupReaper | implemented | -| `memory.pressure-changed` | from, to (`none`, `warming-paused`, `new-devices-paused`), cause (the new step's reading: trigger `level` or `floor`, availablePercent, level or floorPercent; absent to `none`) | a worker's memory pressure step changed: once per change, never per reading; no usable reading drops the step at once (ADR 0068 §5) | MemoryPressureTracker | implemented | +| `memory.pressure-changed` | from, to (`none`, `warming-paused`, `new-devices-paused`), cause (the new step's reading: trigger `level` or `floor`, availablePercent, level on macOS, floorPercent for a floor trigger; absent to `none`) | a worker's memory pressure step changed: once per change, never per reading; no usable reading drops the step at once (ADR 0068 §5) | MemoryPressureTracker | implemented | | `cleanup.executed` | rule name, action, target, reason | cleanup executor committed a proposed action | CleanupExecutor | implemented | | `doctor.reconciled` | drift findings | daemon reconciliation completed | Doctor | implemented | | `driver.root-rejected` | platform, root path, reason (not-absolute/missing-marker/invalid-marker/wrong-instance/symlink/wrong-owner/wrong-permissions/non-empty-unowned-root/unreadable/invalid-device-set/device-set-changed) | a driver's device root failed ownership validation at startup, or (iOS) `drivers.ios.deviceSet` was not `simlock` or `default`, conflicted with `drivers.ios.deviceRoot` or with `ios.simulator.headless: false`, or was switched with simulators left in the set being given up (ADR 0048; `root` is then the configured value or the set holding them), so that platform's driver did not start | DaemonServer | implemented | diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 8a12b8a31..b82cd41ce 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6100,43 +6100,40 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = }); it("simlock status prints the Memory pressure line with the step, when it began and why, and none when there is no step", async () => { - const at = (hours: number, minutes: number) => - new Date(2026, 10, 6, hours, minutes).getTime(); - const memoryLine = async (memoryPressure: unknown) => { - const stdout = await print({ - ...EMPTY_STATUS, - capacity: { ...EMPTY_STATUS.capacity, memoryPressure }, - load: LOAD, - } as StatusGetOutput); - return stdout.split("\n").find((line) => line.startsWith("Memory pressure:")); - }; - - expect( - await memoryLine({ - cause: { availablePercent: 34, level: "warn", trigger: "level" }, - since: at(9, 12), - step: "warming-paused", - }), - ).toBe("Memory pressure: warming paused since 09:12 (pressure warn)"); - expect( - await memoryLine({ - cause: { availablePercent: 8, floorPercent: 10, trigger: "floor" }, - since: at(9, 40), + const line = async (memoryPressure: unknown) => + ( + await print({ + ...EMPTY_STATUS, + capacity: { ...EMPTY_STATUS.capacity, memoryPressure }, + load: LOAD, + } as StatusGetOutput) + ) + .split("\n") + .find((row) => row.startsWith("Memory pressure:")); + const since = new Date(2026, 10, 6, 9, 12).getTime(); + const warn = { availablePercent: 34, level: "warn", trigger: "level" }; + const floor = (availablePercent: number, extra = {}) => + line({ + cause: { availablePercent, floorPercent: 10, trigger: "floor", ...extra }, + since, step: "new-devices-paused", - }), - ).toBe("Memory pressure: new devices paused since 09:40 (8% available, floor 10%)"); - expect(await memoryLine({ step: "none" })).toBeUndefined(); - expect(await memoryLine(undefined)).toBeUndefined(); + }); + + expect(await line({ cause: warn, since, step: "warming-paused" })).toBe( + "Memory pressure: warming paused since 09:12 (pressure warn)", + ); + const floored = "Memory pressure: new devices paused since 09:12 (8% available, floor 10%)"; + expect(await floor(8)).toBe(floored); + expect(await floor(8, { level: "warn" })).toBe(floored); + expect(await floor(9)).toBe(floored.replace("8%", "9%")); + expect(await line({ step: "none" })).toBeUndefined(); + expect(await line(undefined)).toBeUndefined(); const stdout = await print({ ...EMPTY_STATUS, capacity: { ...EMPTY_STATUS.capacity, - memoryPressure: { - cause: { availablePercent: 34, level: "warn", trigger: "level" }, - since: at(9, 12), - step: "warming-paused", - }, + memoryPressure: { cause: warn, since, step: "warming-paused" }, }, load: LOAD, } as StatusGetOutput); diff --git a/src/daemon/main-host-load.test.ts b/src/daemon/main-host-load.test.ts index 42e8d5018..593445d68 100644 --- a/src/daemon/main-host-load.test.ts +++ b/src/daemon/main-host-load.test.ts @@ -390,9 +390,10 @@ describe("startDaemon memory pressure", () => { level: name, trigger: "level", }); - const floor = (availablePercent: number, floorPercent: number) => ({ + const floor = (availablePercent: number, floorPercent: number, name?: "normal" | "warn") => ({ availablePercent, floorPercent, + ...(name === undefined ? {} : { level: name }), trigger: "floor", }); const cases: readonly { @@ -411,7 +412,7 @@ describe("startDaemon memory pressure", () => { }, { reading: memoryReading("warn", 8), - expected: { cause: floor(8, 10), since: 1_000, step: "new-devices-paused" }, + expected: { cause: floor(8, 10, "warn"), since: 1_000, step: "new-devices-paused" }, }, { reading: memoryReading("critical", 8), @@ -419,7 +420,7 @@ describe("startDaemon memory pressure", () => { }, { reading: memoryReading("normal", 8), - expected: { cause: floor(8, 10), since: 1_000, step: "new-devices-paused" }, + expected: { cause: floor(8, 10, "normal"), since: 1_000, step: "new-devices-paused" }, }, { reading: memoryReading(undefined, 25), expected: { step: "none" } }, { diff --git a/src/host-load/AGENTS.md b/src/host-load/AGENTS.md index 4fa64b9b3..272fc33bb 100644 --- a/src/host-load/AGENTS.md +++ b/src/host-load/AGENTS.md @@ -10,5 +10,4 @@ Does: samples this host's CPU, memory and disk on a fixed interval and keeps the - `firstReading()` settles at the first recorded read, whatever it found, or at dispose. A worker dials its gateway only after it, so the first `status.get` the gateway reads has a load. - `hostLoadProbe: null` turns sampling off: no sampler, no `load` field. - Readers fit the reading to the contract with `fitHostLoad`. -- `MemoryPressureTracker` works out the memory pressure step from each recorded reading (ADR 0068). A step comes on at the first reading that meets it and lifts `clearAfterMs` after the first reading that does not, unless one meets it again. A reading with no memory part, `enabled: false`, or no reading for 60 s is `none` at once. -- The tracker emits `memory.pressure-changed` once per change of step, after the step is stored; `dispose` emits nothing. +- `MemoryPressureTracker` works out the memory pressure step from each recorded reading (ADR 0068). diff --git a/src/host-load/memory-pressure.ts b/src/host-load/memory-pressure.ts index fa1fc92e9..22718753d 100644 --- a/src/host-load/memory-pressure.ts +++ b/src/host-load/memory-pressure.ts @@ -173,7 +173,12 @@ function meets(rule: MemoryPressureRule, memory: MemoryCounters): MemoryPressure return { availablePercent, level: memory.pressure, trigger: "level" }; } if (exactPercent < rule.minAvailablePercent) { - return { availablePercent, floorPercent: rule.minAvailablePercent, trigger: "floor" }; + return { + availablePercent, + floorPercent: rule.minAvailablePercent, + ...(memory.pressure === undefined ? {} : { level: memory.pressure }), + trigger: "floor", + }; } return undefined; } diff --git a/src/source-hygiene.test.ts b/src/source-hygiene.test.ts index 8ac4712d6..5804a214d 100644 --- a/src/source-hygiene.test.ts +++ b/src/source-hygiene.test.ts @@ -27,7 +27,7 @@ type SizedFile = { path: string; lines: number }; * only shrink. A PR that has to grow one raises its number here, as a visible line of its diff. */ const SHRINK_ONLY: Record = { - "src/cli/index.test.ts": 11610, + "src/cli/index.test.ts": 11637, "src/drivers/ios/index.test.ts": 5996, "src/drivers/ios/index.ts": 2700, "src/leasing/create-leasing.test.ts": 5276, diff --git a/website/src/content/docs/docs/reference/events.mdx b/website/src/content/docs/docs/reference/events.mdx index 7b11cdc21..07727ce54 100644 --- a/website/src/content/docs/docs/reference/events.mdx +++ b/website/src/content/docs/docs/reference/events.mdx @@ -195,7 +195,7 @@ as `incompatible` in `simlock --gateway worker list`. | `doctor.reconciled` | Simlock compared its records with the devices that exist (at start and on `simlock doctor`). | `driftFindings` | Relayed | | `cleanup.executed` | Cleanup shut down or deleted an idle device. | `ruleName` (`idle-shutdown` or `idle-destroy`), `action` (`shutdown` or `destroy`), `target`, `reason` | Relayed | | `disk.pressure-detected` | Free disk space fell below `diskPressure.freeBytesThreshold`. Once per crossing. | `freeBytes`, `threshold` | Relayed | -| `memory.pressure-changed` | A worker's memory pressure step changed, from `none`, `warming-paused` or `new-devices-paused` to another. Once per change, never per reading. See `memoryPressure.*`. | `from`, `to`, `cause` (`trigger` `level` or `floor`, `availablePercent`, `level` or `floorPercent`; absent when `to` is `none`) | Relayed | +| `memory.pressure-changed` | A worker's memory pressure step changed, from `none`, `warming-paused` or `new-devices-paused` to another. Once per change, never per reading. See `memoryPressure.*`. | `from`, `to`, `cause` (`trigger` `level` or `floor`, `availablePercent`, `level` on macOS, `floorPercent` for a floor trigger; absent when `to` is `none`) | Relayed | | `driver.root-rejected` | A platform did not start because of its device folder: the folder failed its ownership check, or (iOS) `drivers.ios.deviceSet` was invalid, conflicted with `ios.simulator.headless: false`, or was switched while simulators were left in the old set. `simlock doctor` says what to fix. Reasons include `invalid-device-set` and `device-set-changed`; `root` is then the configured value or the set that holds the leftovers. | `platform`, `root`, `reason` | Relayed | | `driver.adb-server-rejected` | The adb server Simlock runs for its emulators could not start (see `drivers.android.adbServerPort`), so Android did not start. | `port`, `reason` (`occupied`, `start-failed`, `invalid-port`) | Relayed |