//! What a heavy job costs, what a Mac may promise, and whether the one fits in//! the other.//!//! **Hardware is budgeted by Cotton itself**//! ([build-runners-simulators-and-sessions-are-budgeted-by-cotton-its]): every//! Mac reports what it has, every job declares what it costs, and a Mac takes//! work up to a known point and never past it. This module holds both halves —//! the COST table ([`cost`], one entry per kind of heavy job) and the BUDGET//! arithmetic ([`budget_gb`], [`free_gb`]) — because a cost and a budget//! written in two places are a cost and a budget that stop meaning the same//! thing. The ADMISSION is [`super::dispatch::pick_device`], which is the only//! caller that puts them together.//!//! **The build lock is a COST, not a throttle.** `/tmp/tinmen-build.lock`//! serialises the heavy builds a person starts by hand, and it used to refuse//! every session outright while it was held — a Mac with 48 GB in it turned//! away a 0.6 GB agent because somebody was compiling. What the lock holder is//! really costing is measured and added to the Mac's committed total; whether//! anything else fits is then the same arithmetic as everything else.//!//! **A guess is a starting point, not the answer.** Every default here is a//! number somebody measured once, on one Mac, and it is wrong on the next one://! an M4 Pro's `claude` is not an M1 Air's. So a Mac that has watched a kind of//! job [`MEASURED_MINIMUM_SAMPLES`] times uses its OWN peak instead//! ([`mem_gb`]) — the table is where a Mac starts, not where it stays.//!//! No clock, no database, no `Ctx`: every function is of its arguments, which//! is what lets `budget_tests.rs` state the whole table as arithmetic./// A kind of heavy job a Mac can be asked to take.////// **Adding a variant is a compile error until it has a cost** — [`cost`] is an/// exhaustive `match`, not a lookup that can miss — and a runtime guard holds/// [`JOB_KINDS`] to the same list, so a kind that exists but is never offered/// to the budget cannot hide either.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pubenumJobKind {/// One coding agent in its own pseudo-terminal — `claude` or `codex`.CodingSession,/// One MCP server a session opens. Counted from the session's settings,/// because a session with eight of them is a different job from one with/// none.McpServer,/// One booted iOS simulator.IosSimulator,/// An `xcodebuild archive` — the heaviest thing this repo does.XcodebuildArchive,/// One `cargo build` job. The COUNT is `CARGO_BUILD_JOBS`, because cargo's/// memory is per compiler process and nothing else about the build moves.CargoBuild,/// One booted Android emulator.AndroidEmulator,}/// Every [`JobKind`], in the order a person would read them.////// Held equal to the enum by `budget_tests.rs`. It exists so the table can/// be swept — a `match` proves each kind HAS a cost, and only a list can prove/// the costs are sane as a set (no duplicate label, no zero, no negative).pubconst JOB_KINDS: &[JobKind] = &[JobKind::CodingSession,JobKind::McpServer,JobKind::IosSimulator,JobKind::XcodebuildArchive,JobKind::CargoBuild,JobKind::AndroidEmulator,];/// How many cores one unit of a job wants.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumCores {/// A fixed number, whatever the Mac is.Fixed(i64),/// Every core the Mac has. `xcodebuild` and a linker do not leave one.All,}implCores {/// The number, on a Mac with `cpu_count` cores. #[must_use]pubfn on(self, cpu_count: i64) -> i64 {matchself {Cores::Fixed(n) => n,Cores::All => cpu_count, } }}/// What ONE unit of a job kind costs.#[derive(Debug, Clone, Copy, PartialEq)]pubstructJobCost {/// The line a refusal calls it by — `dispatch.jobs.<label>`, "a coding/// session needs 0.6 GB" — a key, never the words.pub label: &'static str,/// Resident memory, in gigabytes, at the job's PEAK — not its average. A/// budget built on averages is a budget that swaps at exactly the moment/// two jobs both peak, which is the failure this whole system exists to/// prevent.pub mem_gb: f64,pub cores: Cores,}/// What one unit of `kind` costs, before a Mac's own measurements correct it.////// The numbers, and where each came from:////// - **coding session, 0.6 GB, 1 core** — measured on this household's Macs/// in September 2026: `claude` held 365–582 MB resident across a working/// day. The agent is not the compiler; what it SPAWNS is, and that arrives/// as its own job./// - **MCP server, 0.3 GB, no core of its own** — a handful of node or Rust/// processes waiting on stdio. They are counted because a session with/// eight of them costs more than twice one with none, and they are given no/// core because a server blocked on a pipe is not running./// - **iOS simulator, 2 GB, 1 core** — a booted simulator with an app in it./// - **`xcodebuild archive`, 8 GB, every core** — the heaviest job in the/// repo, and the one the machine-wide build lock was invented for./// - **`cargo build`, 3 GB and 1 core PER JOB** — `rustc` peaks per compiler/// process, so the cost is `3 × CARGO_BUILD_JOBS`; the count is the/// caller's, because only the caller knows what it set./// - **Android emulator, 5 GB, 4 cores** — the emulator plus its qemu.#[must_use]pubfn cost(kind: JobKind) -> JobCost {match kind {JobKind::CodingSession => JobCost { label: "coding_session", mem_gb: 0.6, cores: Cores::Fixed(1), },JobKind::McpServer => JobCost { label: "mcp_server", mem_gb: 0.3, cores: Cores::Fixed(0), },JobKind::IosSimulator => JobCost { label: "ios_simulator", mem_gb: 2.0, cores: Cores::Fixed(1), },JobKind::XcodebuildArchive => JobCost { label: "build", mem_gb: 8.0, cores: Cores::All, },JobKind::CargoBuild => JobCost { label: "cargo_build", mem_gb: 3.0, cores: Cores::Fixed(1), },JobKind::AndroidEmulator => JobCost { label: "android_emulator", mem_gb: 5.0, cores: Cores::Fixed(4), }, }}/// How many times a Mac must have WATCHED a kind of job before its own peak/// replaces the table's guess.////// **Three.** One reading is an anecdote — a session that was asked a question/// and never compiled anything reports a peak that would let four more onto a/// Mac that cannot hold them. Three readings of the same kind on the same Mac/// is the smallest number where the peak is a peak and not a coincidence, and/// it is reached within an hour at the fifteen-minute sample cadence/// ([`super::samples::SAMPLE_INTERVAL_MINUTES`]).pubconst MEASURED_MINIMUM_SAMPLES: i64 = 3;/// What a Mac has actually watched a kind of job cost, on that Mac.////// The session host records it; the device row carries it; this module is where/// it beats the guess. `peak_gb` is the largest resident total the sampler has/// ever summed over one job's process tree — which is why it is compared to a/// PEAK default and not to an average.#[derive(Debug, Clone, Copy, PartialEq)]pubstructMeasured {pub peak_gb: f64,pub samples: i64,}/// What `count` units of `kind` cost in memory on this Mac, in gigabytes.////// `measured` is this Mac's own reading for that kind, when it has one. It wins/// from [`MEASURED_MINIMUM_SAMPLES`] readings on, **in both directions**: a Mac/// whose sessions really do hold 1.4 GB must admit fewer of them, and a Mac/// whose sessions hold 0.3 GB must not be refused work on the strength of a/// number measured on somebody else's machine. A measurement under three/// samples is ignored rather than blended — an average of a guess and an/// anecdote is a third number nobody can point at.////// A negative or zero `count` is zero cost: asking what no jobs cost is a/// question with an answer, not an error.#[must_use]pubfn mem_gb(kind: JobKind, count: i64, measured: Option<Measured>) -> f64 {if count <= 0 {return0.0; }let each = match measured {Some(measured) if measured.samples >= MEASURED_MINIMUM_SAMPLES => measured.peak_gb, _ => cost(kind).mem_gb, }; each * count as f64}/// How many cores `count` units of `kind` want on a Mac with `cpu_count`.////// Capped at `cpu_count`: a job cannot want more cores than the Mac has, and a/// number above the count would refuse every Mac forever rather than say/// anything true. Measurement does not correct this one — cores are what the/// job is CONFIGURED to use, not what it was seen using, and a build that/// happened to idle on one core is still a build that will take them all.#[must_use]pubfn cores(kind: JobKind, count: i64, cpu_count: i64) -> i64 {if count <= 0 {return0; }let wanted = cost(kind).cores.on(cpu_count).saturating_mul(count); wanted.min(cpu_count.max(0))}/// The label a refusal puts in its sentence — "a **coding session** needs 0.6 GB".#[must_use]pubfn label(kind: JobKind) -> &'static str { cost(kind).label}// ─── what is being asked for ────────────────────────────────────────────────/// One kind of job, and how many of it.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructPart {pub kind: JobKind,pub count: i64,}/// A job and everything it brings with it.////// A coding session is never only a coding session: it opens its MCP servers/// the moment it starts, and a Mac admitted on the agent's own 0.6 GB and then/// handed eight servers beside it was admitted on a number that was never the/// real one. So the thing the dispatcher weighs is the WHOLE ask, and the first/// part is what a refusal names — nobody reads "a coding session and three MCP/// servers need 1.5 GB" and acts differently from "a coding session needs 1.5".#[derive(Debug, Clone, PartialEq, Eq)]pubstructAsk {pub parts: Vec<Part>,}implAsk {/// One coding agent, with the MCP servers it opens beside it. #[must_use]pubfn coding_session(mcp_servers: i64) -> Ask {Ask { parts: vec![Part { kind: JobKind::CodingSession, count: 1, },Part { kind: JobKind::McpServer, count: mcp_servers.max(0), }, ], } }/// One of anything else — a simulator to boot, an archive to run. #[must_use]pubfn one(kind: JobKind) -> Ask {Ask { parts: vec![Part { kind, count: 1 }], } }/// What the whole ask costs in memory on a Mac, in gigabytes.////// `session_peak` is that Mac's own measured peak for a CODING SESSION,/// which is the only kind the session host watches — it owns those/// pseudo-terminals and nothing else's. It corrects the session part only,/// and it already contains the servers the session opened, which is why a/// measured Mac's MCP parts fall away rather than being added twice. #[must_use]pubfn mem_gb(&self, session_peak: Option<Measured>) -> f64 {let measured = session_peak .is_some_and(|peak| peak.samples >= MEASURED_MINIMUM_SAMPLES);self.parts .iter() .map(|part| match part.kind {JobKind::CodingSession => mem_gb(part.kind, part.count, session_peak),// Already inside the measured peak: the servers run in the// session's own process tree, and the sampler sums the tree.JobKind::McpServerif measured => 0.0, kind => mem_gb(kind, part.count, None), }) .sum() }/// What a refusal calls this ask — the FIRST part's label. #[must_use]pubfn label(&self) -> &'static str {self.parts .first() .map_or("job", |part| label(part.kind)) }}// ─── what a Mac may promise ─────────────────────────────────────────────────/// Memory held back from the budget on an ordinary Mac.////// **Two gigabytes.** Not for the system — the free-memory reading already/// accounts for what the OS is using — but for the PERSON: this is somebody's/// desk, and a Mac budgeted to its last byte is one where opening a browser/// tab is what starts the swapping.pubconst RESERVE_GB: f64 = 2.0;/// Memory held back on the Mac whose server holds the served file.////// **Four gigabytes.** That Mac is answering every other device's reads and/// writes, and it is the one running the workers; a Mac that swaps while/// serving does not slow one session down, it slows the household's whole/// database down. Its reserve is decided by a FACT, not by configuration — the/// serving Mac is the one whose registry has no `server_url` for the workspace/// — so a household that moves its file moves the reserve with it and nobody/// has to remember.pubconst SERVING_RESERVE_GB: f64 = 4.0;/// What is held back on this Mac.#[must_use]pubfn reserve_gb(holds_served_file: bool) -> f64 {if holds_served_file { SERVING_RESERVE_GB } else { RESERVE_GB }}/// What a Mac with `mem_total_gb` of memory may promise in total.////// Never negative: a Mac smaller than its own reserve promises NOTHING, which/// is a true sentence, where a negative budget would be an arithmetic result/// nobody could read on a card.#[must_use]pubfn budget_gb(mem_total_gb: f64, holds_served_file: bool) -> f64 { (mem_total_gb - reserve_gb(holds_served_file)).max(0.0)}/// What is left of a Mac's budget once what it has already promised is taken/// off.////// Never negative, for the same reason: a Mac that is over its budget has zero/// free, and "zero free" is what a refusal should say about it.#[must_use]pubfn free_gb(budget_gb: f64, committed_gb: f64) -> f64 { (budget_gb - committed_gb).max(0.0)}/// The slack on every comparison here, in gigabytes.////// **One megabyte.** Every number in this module is arithmetic over MEASURED/// gigabytes, and `14.0 - 13.4` is not `0.6` in binary floating point — it is/// a fraction of a billionth under it. A session refused because a subtraction/// landed short in the sixteenth decimal place would be a queue stuck on/// something no person could see and no sentence could explain. A megabyte is/// far below what any job in the table costs and far above anything the/// arithmetic can drift.pubconst SLACK_GB: f64 = 0.001;/// Does `cost_gb` fit in what is left?////// `<=`, so a job that exactly fills the remaining budget is admitted: the/// budget already holds a reserve back, and refusing on the boundary would mean/// a Mac could never be used up to the point it was budgeted to.#[must_use]pubfn admits(free_gb: f64, cost_gb: f64) -> bool { cost_gb <= free_gb + SLACK_GB}/// A measured gigabyte figure, as a REFUSAL says it — one decimal, and never/// rounded in the direction that would make the sentence a lie.////// A refusal reads *"mac-a has 0.5 GB free; a coding session needs 0.6"*, and the/// two numbers in it are rounded in OPPOSITE directions on purpose. Round both/// to nearest and a Mac with 0.55 free, refused for a 0.6 job, prints "has 0.6/// GB free; a coding session needs 0.6" — a sentence that says the job fits/// beside the news that it did not. So what is free rounds DOWN and what is/// wanted rounds UP: the sentence understates the room and overstates the cost,/// which are the two errors a person reading it can act on.////// [`SLACK_GB`] is absorbed before the rounding for the same reason it exists/// at all — without it, a true 0.2 that arrived as 0.19999999999999993 would/// print as 0.1.#[must_use]pubfn free_as_said(gb: f64) -> f64 { ((gb + SLACK_GB) * 10.0).floor() / 10.0}/// A cost, as a refusal says it — one decimal, rounded UP. See/// [`free_as_said`].#[must_use]pubfn cost_as_said(gb: f64) -> f64 { ((gb - SLACK_GB) * 10.0).ceil() / 10.0}#[cfg(test)]#[path = "budget_tests.rs"]mod tests;/// What a new lane is taken to need on disk, in GB: its worktree, its target/// and its build data. A session is placed only where this fits over the/// reserve.pubconst LANE_DISK_GB: f64 = 25.0;/// The device's core disk policy, in scheduler units.#[must_use]pubfn disk_reserve_gb(total_gb: f64, raised_bytes: Option<u64>) -> f64 {crate::device::disk::keep_free_gb(total_gb, raised_bytes)}