diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 608f92ffa..cedb99f1d 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 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/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/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/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/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, diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 629dd450e..b82cd41ce 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6098,6 +6098,49 @@ 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 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", + }); + + 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: warn, since, 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 () => { @@ -9524,6 +9567,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"], @@ -9640,6 +9684,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"], 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/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..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 = { @@ -1322,6 +1381,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 +1467,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/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..94fce5c9c 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(), +}); + +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. */ @@ -61,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/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); diff --git a/src/core/config.ts b/src/core/config.ts index 6bcfd3bdc..ddc32e5ee 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -28,6 +28,7 @@ import { booleanValue, ConfigError, integerInRange, + numberInRange, invalidValue, nonNegativeNumber, numberAtLeast, @@ -103,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]; @@ -256,6 +258,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 +346,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 +1008,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: { @@ -1145,6 +1165,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({ @@ -1188,6 +1214,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/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/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 ( 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 27fa24358..593445d68 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 () => { @@ -360,3 +361,246 @@ 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 level = (availablePercent: number, name: "warn" | "critical") => ({ + availablePercent, + level: name, + trigger: "level", + }); + const floor = (availablePercent: number, floorPercent: number, name?: "normal" | "warn") => ({ + availablePercent, + floorPercent, + ...(name === undefined ? {} : { level: name }), + 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: 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, "warn"), 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, "normal"), 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, 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); + } + }); +}); + +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: 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, + ); + } + } + }); + + 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"); + }); + + 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" }, + ]); + }); +}); diff --git a/src/daemon/server.ts b/src/daemon/server.ts index a9aafabb8..f2c4ed545 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; dispose(): void }; 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 }), @@ -653,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 7703aa7c9..d936b43dd 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, eventBus }); 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, @@ -258,6 +267,14 @@ export async function composeWorker( }); const modelPreferences = modelPreferenceWiring(config, drivers); const core = createCore({ + ...(memoryPressure === undefined + ? {} + : { + memoryPressure: { + current: () => memoryPressure.current(), + onReading: (listener: () => void) => memoryPressure.onReading(listener), + }, + }), clock, components, config, @@ -499,6 +516,19 @@ export async function composeWorker( physicalDeviceWatcher: leasing.physicalDeviceWatcher, hostFacts: () => fitHostFacts(hostFacts.current()), ...(hostLoad === undefined ? {} : { hostLoad, load: () => fitHostLoad(hostLoad.current()) }), + ...(memoryPressure === undefined + ? {} + : { + memoryPressure: { + dispose: () => memoryPressure.dispose(), + 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/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/host-load/AGENTS.md b/src/host-load/AGENTS.md index 416c0edfb..272fc33bb 100644 --- a/src/host-load/AGENTS.md +++ b/src/host-load/AGENTS.md @@ -10,3 +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). diff --git a/src/host-load/index.ts b/src/host-load/index.ts index c3e1e3723..9109a5b9b 100644 --- a/src/host-load/index.ts +++ b/src/host-load/index.ts @@ -1 +1,2 @@ export { HostLoadSampler } from "./sampler.js"; +export { MemoryPressureTracker } from "./memory-pressure.js"; diff --git a/src/host-load/memory-pressure.test.ts b/src/host-load/memory-pressure.test.ts new file mode 100644 index 000000000..f33230986 --- /dev/null +++ b/src/host-load/memory-pressure.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from "vitest"; + +import { EventBus } from "../bus/index.js"; +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 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" }); + + 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"); + 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/host-load/memory-pressure.ts b/src/host-load/memory-pressure.ts new file mode 100644 index 000000000..22718753d --- /dev/null +++ b/src/host-load/memory-pressure.ts @@ -0,0 +1,184 @@ +import type { EventBus } from "../bus/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"; + +interface MemoryPressureRule { + readonly level: MemoryPressureLevel | "off"; + readonly minAvailablePercent: number; +} + +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; + readonly eventBus: EventBus; +} + +interface HeldStep { + readonly since: number; + readonly cause: MemoryPressureCause; + clearTimer?: TimerHandle; +} + +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 }; + +/** + * 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 { + readonly #held: Record = { + newDevices: undefined, + warming: undefined, + }; + #readingAt: number | undefined; + #staleTimer: TimerHandle | undefined; + readonly #listeners = new Set<() => void>(); + + 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; + this.#changing(() => { + if (memory === undefined) { + this.#dropAll(); + return; + } + this.#hold("warming", config.pauseWarming, memory, now); + this.#hold("newDevices", config.pauseNewDevices, memory, now); + }); + for (const listener of this.#listeners) listener(); + } + + current(): MemoryPressureState | undefined { + if (this.#readingAt === undefined) return undefined; + 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" }; + } + + /** 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(); + } + + #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.#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]); + this.#held[key] = undefined; + } + } + + #hold(key: StepKey, rule: MemoryPressureRule, memory: MemoryCounters, now: number): void { + const held = this.#held[key]; + const cause = meets(rule, memory); + 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.#changing(() => { + 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 { + 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, + ...(memory.pressure === undefined ? {} : { level: memory.pressure }), + 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 { 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.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/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/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/ui/src/model/waiting.test.ts b/ui/src/model/waiting.test.ts index 1c9bd404b..5d6377654 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"], @@ -203,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(); @@ -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"], 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", }; 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 e72852e0a..526859f82 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 | @@ -281,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" 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/reference/events.mdx b/website/src/content/docs/docs/reference/events.mdx index 484268b0c..07727ce54 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` 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 | 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..2f1beec62 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. | @@ -72,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