Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,24 @@ and listed with their assets on the

## [Unreleased]

### Changed

- **A service's memory is what its processes own** (ADR-0119). Shared
pages, such as the .NET runtime's, no longer count again with every
process of a tree: Linux takes the proportional set (`Pss`) instead of the
resident set, and a cgroup's `memory.current` without the file cache the
kernel may drop; Windows the private working set; macOS the physical
footprint. The numbers in the dashboard, `devstack top` and a lane's
need for the pool are lower, for a .NET stack by about a third.
- **The dashboard names the builds' memory** (ADR-0119). The lane card says
"of it builds …", and the overview lists *Builds* below the groups: the
build servers stay after a build so the next one is fast, and were in the
lane's number but in no group.
- **main is stopped when only what serves its lanes runs** (ADR-0119). A
`singleton` the stop of main keeps for running lanes no longer shows main
as running with a Stop button; the stop says what keeps running, and for
which lanes.

### Fixed

- **A stopped stack no longer shows the memory of its containers.** When
Expand Down
6 changes: 4 additions & 2 deletions crates/devstack-proc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,10 @@ pub struct Usage {
/// cgroup (and on macOS) it is the sum over the live processes and may
/// drop.
pub cpu_us: u64,
/// Bytes: the summed working sets (Windows), `memory.current` of the
/// cgroup, else the summed resident sets (Linux, macOS).
/// Bytes, each process's own and its share of what it shares (ADR-0119):
/// the summed private working sets (Windows), `memory.current` of the
/// cgroup less its inactive file cache, else the summed proportional
/// sets (Linux), the summed physical footprints (macOS).
pub memory: u64,
pub processes: u32,
}
Expand Down
72 changes: 67 additions & 5 deletions crates/devstack-proc/src/linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ pub(crate) fn memory_available() -> Option<u64> {
}

fn meminfo(key: &str) -> Option<u64> {
let text = fs::read_to_string("/proc/meminfo").ok()?;
kb_field(&fs::read_to_string("/proc/meminfo").ok()?, key)
}

/// A `<key> <n> kB` line of `/proc` (meminfo, smaps_rollup), in bytes.
fn kb_field(text: &str, key: &str) -> Option<u64> {
let kb: u64 = text
.lines()
.find_map(|l| l.strip_prefix(key))?
Expand Down Expand Up @@ -102,10 +106,34 @@ fn live(pid: i32) -> bool {
})
}

/// CPU time (user plus kernel, microseconds) and resident set (bytes) of
/// one process; zero for what cannot be read.
/// CPU time (user plus kernel, microseconds) and memory (bytes) of one
/// process; zero for what cannot be read.
pub(crate) fn process_usage(pid: u32) -> (u64, u64) {
(proc_cpu_us(pid), proc_rss(pid))
(
proc_cpu_us(pid),
proc_pss(pid).unwrap_or_else(|| proc_rss(pid)),
)
}

/// Its proportional set: each page it shares with others counted by its
/// share, so a tree's sum counts the .NET runtime's pages once, not with
/// every process (as the resident set does). `None` where the kernel does
/// not let us read it (another user's process): then the resident set.
fn proc_pss(pid: u32) -> Option<u64> {
kb_field(
&fs::read_to_string(format!("/proc/{pid}/smaps_rollup")).ok()?,
"Pss:",
)
}

/// `inactive_file` of a cgroup's `memory.stat`, in bytes.
fn inactive_file(memory_stat: &str) -> Option<u64> {
memory_stat
.lines()
.find_map(|l| l.strip_prefix("inactive_file "))?
.trim()
.parse()
.ok()
}

fn proc_cpu_us(pid: u32) -> u64 {
Expand Down Expand Up @@ -227,7 +255,17 @@ impl Cgroup {
.find_map(|l| l.strip_prefix("usage_usec "))
.and_then(|v| v.trim().parse().ok())
});
let memory = read("memory.current").and_then(|s| s.trim().parse().ok());
// Without the file cache the kernel may drop at once, as `docker
// stats` counts a container.
let memory = read("memory.current")
.and_then(|s| s.trim().parse::<u64>().ok())
.map(|m| {
m.saturating_sub(
read("memory.stat")
.and_then(|s| inactive_file(&s))
.unwrap_or(0),
)
});
let summed = || crate::posix::summed_usage(pids);
Usage {
cpu_us: cpu_us.unwrap_or_else(|| summed().cpu_us),
Expand Down Expand Up @@ -265,3 +303,27 @@ fn join_cgroup(procs: &std::ffi::CStr) -> std::io::Result<()> {
}
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn a_process_counts_its_share_of_what_it_shares() {
let rollup = "55e0-7ffd ---p 00000000 00:00 0 [rollup]\nRss: 4096 kB\nPss: 1536 kB\nPss_Anon: 1024 kB\n";
assert_eq!(kb_field(rollup, "Pss:"), Some(1536 * 1024), "not Pss_Anon");
let me = std::process::id();
let (pss, rss) = (proc_pss(me).unwrap(), proc_rss(me));
assert!(pss > 0 && pss <= rss, "pss {pss}, rss {rss}");
// Read again: the process lives, its pages change by a few.
let used = process_usage(me).1;
assert!(used.abs_diff(pss) < pss / 4, "used {used}, pss {pss}");
}

#[test]
fn a_cgroup_does_not_count_the_cache_it_can_drop() {
let stat = "anon 1000\nfile 9000\nactive_file 3000\ninactive_file 6000\n";
assert_eq!(inactive_file(stat), Some(6000));
assert_eq!(inactive_file("anon 1\n"), None);
}
}
36 changes: 29 additions & 7 deletions crates/devstack-proc/src/macos.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! macOS: what the POSIX backend needs from the OS, from libproc (process
//! lists, start times, CPU time and resident sets), and the machine's memory
//! lists, start times, CPU time and physical footprints), and the machine's memory
//! and CPU time from `sysctl` and the Mach host statistics (ADR-0054).
//! There are no cgroups: a tree is its process group, and the shim notices
//! the supervisor's death by polling `getppid()`.
Expand Down Expand Up @@ -200,8 +200,8 @@ pub(crate) fn group(pgid: i32) -> Option<Vec<i32>> {
)
}

/// CPU time (user plus kernel, microseconds) and resident set (bytes) of
/// one process; zero for what cannot be read.
/// CPU time (user plus kernel, microseconds) and memory (bytes) of one
/// process; zero for what cannot be read.
pub(crate) fn process_usage(pid: u32) -> (u64, u64) {
let Ok(pid) = i32::try_from(pid) else {
return (0, 0);
Expand All @@ -210,12 +210,29 @@ pub(crate) fn process_usage(pid: u32) -> (u64, u64) {
// The times are Mach absolute time units, not nanoseconds.
Some(t) => (
mach_to_ns(t.pti_total_user.saturating_add(t.pti_total_system)) / 1000,
t.pti_resident_size,
phys_footprint(pid).unwrap_or(t.pti_resident_size),
),
None => (0, 0),
}
}

/// Its physical footprint, what Activity Monitor shows as its memory: its
/// own pages, without the shared libraries the resident set counts again
/// with every process of a tree.
fn phys_footprint(pid: c_int) -> Option<u64> {
// SAFETY: a zeroed plain-data struct, passed for the flavor that fills
// exactly one.
unsafe {
let mut info: libc::rusage_info_v2 = mem::zeroed();
let ok = libc::proc_pid_rusage(
pid,
libc::RUSAGE_INFO_V2,
(&raw mut info).cast::<libc::rusage_info_t>(),
);
(ok == 0).then_some(info.ri_phys_footprint)
}
}

/// macOS has no parent-death signal: a thread asks `getppid()` every 500 ms
/// and sends `signal` to this process once the parent changed (the shim
/// then belongs to launchd).
Expand Down Expand Up @@ -346,10 +363,15 @@ mod tests {
/// Apple silicon. Other tests run in this process meanwhile: only the
/// lower bound is tight.
#[test]
fn cpu_time_and_resident_set_are_in_microseconds_and_bytes() {
fn cpu_time_and_footprint_are_in_microseconds_and_bytes() {
let me = std::process::id();
let (before, rss) = process_usage(me);
assert!(rss >= 1 << 20, "{rss}");
let (before, footprint) = process_usage(me);
assert!(footprint >= 1 << 20, "{footprint}");
assert_eq!(
phys_footprint(me as i32),
Some(footprint),
"not the resident set"
);
let t0 = Instant::now();
let mut x = 0u64;
while t0.elapsed() < Duration::from_millis(300) {
Expand Down
56 changes: 49 additions & 7 deletions crates/devstack-proc/src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ impl Job {
}

/// Job accounting for CPU time (it includes exited processes), the summed
/// working sets of the live ones for memory.
/// private working sets of the live ones for memory.
pub(crate) fn usage(&self) -> Usage {
// SAFETY: valid job handle, correctly sized out struct.
let cpu_us = unsafe {
Expand Down Expand Up @@ -327,24 +327,42 @@ impl Tree {
}
}

/// The part of a process's working set no other process shares (what Task
/// Manager shows as memory): the shared pages, such as the .NET runtime's,
/// would count again with every process of a tree. A Windows without the
/// private figure (before Windows 10 21H2) gives the whole working set.
fn working_set(pid: u32) -> u64 {
use windows_sys::Win32::System::ProcessStatus::{
K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, PROCESS_MEMORY_COUNTERS_EX2,
};
use windows_sys::Win32::System::Threading::{
OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_VM_READ,
};
// SAFETY: plain Win32 calls; handle checked and closed.
// SAFETY: plain Win32 calls; handle checked and closed; each struct is
// passed with its own size, which tells the call how much it may fill.
unsafe {
let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, 0, pid);
if h.is_null() {
return 0;
}
let mut c: PROCESS_MEMORY_COUNTERS = mem::zeroed();
c.cb = mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
let ok = K32GetProcessMemoryInfo(h, &mut c, c.cb);
let mut x: PROCESS_MEMORY_COUNTERS_EX2 = mem::zeroed();
x.cb = mem::size_of::<PROCESS_MEMORY_COUNTERS_EX2>() as u32;
let bytes =
if K32GetProcessMemoryInfo(h, &mut x as *mut _ as *mut PROCESS_MEMORY_COUNTERS, x.cb)
!= 0
{
x.PrivateWorkingSetSize as u64
} else {
let mut c: PROCESS_MEMORY_COUNTERS = mem::zeroed();
c.cb = mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
if K32GetProcessMemoryInfo(h, &mut c, c.cb) == 0 {
0
} else {
c.WorkingSetSize as u64
}
};
CloseHandle(h);
if ok == 0 { 0 } else { c.WorkingSetSize as u64 }
bytes
}
}

Expand Down Expand Up @@ -630,6 +648,30 @@ pub(crate) fn cpu_times() -> Option<(u64, u64)> {

#[cfg(test)]
mod tests {
#[test]
fn a_process_counts_its_private_working_set() {
use windows_sys::Win32::System::ProcessStatus::{
K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let private = super::working_set(std::process::id());
// SAFETY: the pseudo handle of this process, a struct of the size given.
let whole = unsafe {
let mut c: PROCESS_MEMORY_COUNTERS = std::mem::zeroed();
c.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
assert_ne!(
K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb),
0
);
c.WorkingSetSize as u64
};
// Its DLLs are shared with every other process: the private part is less.
assert!(
private > 0 && private < whole,
"private {private}, whole {whole}"
);
}

#[test]
fn a_job_with_more_processes_than_room_lists_them_all() {
let job = super::Job::new().unwrap();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# ADR-0119: A lane's memory counts what it owns and names its builds; main is stopped when only what serves its lanes runs

- **Status:** Accepted (card in the pull request); points 1, 2 and 4 built, point 3 follows
- **Date:** 2026-11-24
- **Deciders:** project owner
- **Related:** [ADR-0009](0009-the-daemon-owns-every-process-tree.md) (process trees), [ADR-0020](0020-builds-share-one-long-lived-build-job.md) (the build job, its servers stay warm), [ADR-0049](0049-a-lanes-need-is-measured-disk-included.md) (a lane's need), [ADR-0080](0080-the-main-tree-answers-as-a-lane-shared-is-deprecated.md) (`singleton`), [ADR-0095](0095-the-daemon-ends-with-the-last-tree.md) (main stops alone), [ADR-0070](0070-a-review-card-comes-before-the-code-an-adr-records-what-was-built.md)

## Context

A lane of a .NET and Angular stack on a pool node showed 21.2 GB in the
dashboard. Its groups added up to 11.6 GB. The rest was the build job: 51
MSBuild worker nodes from three rounds of parallel builds on a 24-core node,
kept warm on purpose (ADR-0020), counted in the lane but in no group. The
numbers were also too high: on Linux without a cgroup per service the daemon
summed each process's resident set, so the .NET runtime's shared pages
counted once per process (the build servers: 9.3 GB resident, 5.8 GB
proportional). The pool took the same numbers as the lane's need (25.4 GB).

Stopping the main working tree while that lane ran looked as if it did
nothing: the stop kept `companion` (a `singleton`) for the lane, as it
should, but the dashboard still showed main as running, with its Stop
button, so it was pressed three times.

## Decision

The owner approved the points in the conversation on **2026-11-24**, all
four:

| # | Category | Point | Beats | Reversing costs |
|---|---|---|---|---|
| 1 | contract | A native service's memory is what its processes own: Linux the proportional set (`Pss` of `smaps_rollup`) instead of the resident set, Windows the private working set instead of the whole, macOS `phys_footprint` instead of `resident_size` (untested here: CI only). | The sum counting shared pages, such as the .NET runtime's, again with every process. | Low; the numbers in telemetry and the stored needs drop once, the old ones leave after five runs. |
| 2 | term | "Builds" is a part of its own: the lane card says "of it builds X", the overview lists *Builds* beside the groups, so the sum adds up. | 10 GB in no group, the lane's number not explained. | Low, dashboard only. |
| 3 | contract | The need a lane reports to the pool names its builds apart (services and containers plus builds); placement still takes the sum, the log names the builds' part. | Needs like 25.4 GB nobody can explain; the build servers stay in the need, they take the node's memory until MSBuild ends them. | Medium: a field through node, coordinator and hub; older nodes leave it out. |
| 4 | term | Main counts as stopped when only what it keeps for running lanes runs: its state says so, the button is Start again, the stop's message names what keeps running. | A stop that looks as if it did nothing. | Low: one rule in the dashboard, which reads `kept`. |

Decided while building, not on the card: with a cgroup per service (Linux,
delegated) the memory is `memory.current` less the cgroup's `inactive_file`,
as `docker stats` counts a container; a process whose `smaps_rollup` cannot
be read (another user's) falls back to its resident set, a Windows without
the private figure (before Windows 10 21H2) to the whole working set; a
container a kept `singleton` comes `after` still counts as main running;
point 3 comes in a pull request of its own, since the node measures a lane
as one container and has to ask the lane's daemon for its builds.

As built (points 1, 2 and 4):

1. **The measurement.** `devstack-proc`: `linux.rs` reads `Pss:` through
`kb_field` (shared with `meminfo`) and subtracts `inactive_file` from a
cgroup's `memory.current`; `windows.rs` asks `K32GetProcessMemoryInfo`
for `PROCESS_MEMORY_COUNTERS_EX2` and takes `PrivateWorkingSetSize`;
`macos.rs` takes `ri_phys_footprint` of `proc_pid_rusage`. Tests per
platform: the private part is below the whole and above zero.
2. **Builds in the dashboard.** `LaneUsage` takes `builds` (the report's
build job) and says "of it builds"; the overview shows a *Builds* row
with its processes and load below the groups while it takes memory. The
mock hub keeps its build servers warm after a build, as the daemon does.
3. **Main stopped.** The store's `mainActive` and `mainIdle` leave out a
`singleton` while a lane runs; the stop's toast reads `kept`,
`containers` and `lanes` of the daemon's `200`; the stack page's
"main stopped" names what keeps running.

## Consequences

- The memory devstack shows falls for every stack with several processes
per service, most for .NET; a pool's stored needs follow after five runs.
- The build servers are still counted, now where one sees them; ending them
sooner (fewer MSBuild nodes per build) is the user's build command's
choice, not devstack's.
1 change: 1 addition & 0 deletions docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,3 +201,4 @@ stay.
| [0116](0116-admins-see-a-machine-that-asks-to-run-lanes.md) | Admins see a machine that asks to run lanes, and are told when one starts | Accepted (card in the pull request); built |
| [0117](0117-the-dashboard-pushes-a-branch-that-is-ahead-of-its-upstream.md) | The dashboard pushes a branch that is ahead of its upstream, and the start page shows how far each stack is | Accepted (card in the pull request); built |
| [0118](0118-lane-list-says-which-lanes-are-done.md) | `lane list` says which lanes are done, and devstack removes none of them | Accepted (card in the pull request); built; amended 2026-11-23 (`new`, no command for a name a shell reads) |
| [0119](0119-a-lanes-memory-counts-what-it-owns-and-names-its-builds.md) | A lane's memory counts what it owns and names its builds; main is stopped when only what serves its lanes runs | Accepted (card in the pull request); points 1, 2, 4 built, point 3 follows |
6 changes: 3 additions & 3 deletions docs/plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -1286,7 +1286,7 @@ second worktree runs.
| Measure | Native processes | Containers |
|---|---|---|
| CPU (% of one core, and total CPU time) | Windows: job accounting of the service's job; Linux: the service's cgroup (`cpu.stat`), else the sum over its process group | `docker stats` of the Compose services |
| Memory (working set / RSS) | Windows: sum over the job's processes; Linux: cgroup `memory.current`, else sum over the process group | `docker stats` |
| Memory (what a process does not share, ADR-0119) | Windows: the private working sets summed over the job's processes; Linux: cgroup `memory.current` less `inactive_file`, else the proportional sets (`Pss`) summed over the process group; macOS: the physical footprints summed | `docker stats` |
| Processes | job / cgroup membership (ADR-0009) | — |
| Disk | per lane: snapshot, artifacts, logs under `.devstack/` | named volumes of the Compose project (`docker system df -v`), sampled rarely |

Expand All @@ -1306,8 +1306,8 @@ second worktree runs.
per native sample, `devstack top [--watch]`; the dashboard follows in phase 2.
Known limits of the numbers:

- Windows memory is the summed working set, so pages shared between the tree's
processes count more than once.
- Windows memory was the summed working set, so pages shared between the tree's
processes counted more than once; since ADR-0119 it is the private part.
- Linux without a writable cgroup sums CPU time over the live processes; it can
drop when a process exits, which the sampler reads as "no rate this round".
Builds on such a host are not measured (they have no common cgroup).
Expand Down
Loading
Loading