Skip to content
Closed
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
server: add Linux resident memory gauges from /proc/self/status
On Linux, /metrics now reports VmRSS, RssAnon, RssFile, RssShmem and
VmHWM as five process_resident_* gauges, in live and parked scrapes.
The reader uses a 4 KiB stack buffer and doesn't allocate. A count the
kernel doesn't report is left out, never sent as zero. The macOS
footprint gauges don't change.
  • Loading branch information
nuk3s committed Oct 26, 2026
commit 462e50dedbc4b1cf16fd4cb300b8375ef8cc2e88
8 changes: 8 additions & 0 deletions docs/memory-diagnostics.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ unified memory: do not add them. RSS, allocator peaks and physical footprint are
The Darwin structure follows Apple's `sys/resource.h` `rusage_info_v4` layout; host tests check its size
and both footprint offsets, and exercise the kernel reader on macOS.

Linux has no physical footprint count, so the footprint gauges stay macOS only. On Linux, `/metrics` reads
`/proc/self/status` at scrape time and reports the resident set: `tensorfold:process_resident_bytes` (`VmRSS`),
its parts `tensorfold:process_resident_anon_bytes` (`RssAnon`), `tensorfold:process_resident_file_bytes`
(`RssFile`) and `tensorfold:process_resident_shmem_bytes` (`RssShmem`), and
`tensorfold:process_resident_peak_bytes` (`VmHWM`, the kernel's lifetime peak, never reset by TensorFold).
A count the kernel does not report is omitted. The resident set holds no device or driver memory, so it is
not a physical footprint.

Route/auth regression checks use the CPU-only fake engine:

```sh
Expand Down
64 changes: 64 additions & 0 deletions zig/src/server/metrics.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Prometheus text for GET /metrics, family for family as the Python server writes it.
const std = @import("std");
const process = @import("process_memory.zig");
const resident = @import("process_resident.zig");
const api = @import("engine_api");

const prefix = "tensorfold:";
Expand Down Expand Up @@ -122,6 +123,7 @@ pub const Metrics = struct {
try gauge(w, "decode_rounds_total", "counter", "Decode rounds used by finished requests.", snap.rounds);
try histogram(w, "request_prefill_seconds", "Seconds a finished request's prompt pass took.", snap.prefill);
try processGauges(w, process.read());
try residentGauges(w, resident.read(io));
try gauge(w, "num_requests_running", "gauge", "Requests in prefill or decode. A mirror of tensorfold:requests_running.", 0);
try gauge(w, "num_requests_waiting", "gauge", "Requests queued or held until a lane is free. A mirror of tensorfold:requests_waiting.", 0);
try histogram(w, "e2e_request_latency_seconds", "Seconds from arrival to the reply leaving, under vLLM's name.", snap.latency);
Expand Down Expand Up @@ -178,6 +180,7 @@ pub const Metrics = struct {
try gauge(w, "decode_rounds_total", "counter", "Decode rounds used by finished requests.", snap.rounds);
try histogram(w, "request_prefill_seconds", "Seconds a finished request's prompt pass took.", snap.prefill);
try processGauges(w, process.read());
try residentGauges(w, resident.read(io));
if (memory) |mem| {
try gauge(w, "device_memory_bytes", "gauge", "Device memory the engine holds now: weights, caches and live streams; only where the backend counts it (CUDA).", mem.active);
try gauge(w, "device_memory_peak_bytes", "gauge", "The most device memory the engine has held since start or the last /health?reset_peak=1.", mem.peak);
Expand Down Expand Up @@ -216,6 +219,15 @@ fn processGauges(w: *std.Io.Writer, sample: ?process.Snapshot) !void {
try gauge(w, "process_footprint_peak_bytes", "gauge", "Kernel lifetime peak physical footprint including Metal buffers; never reset by health (macOS).", p.lifetime_peak_physical_footprint_bytes);
}

fn residentGauges(w: *std.Io.Writer, sample: ?resident.Snapshot) !void {
const r = sample orelse return;
if (r.resident_bytes) |b| try gauge(w, "process_resident_bytes", "gauge", "Current resident set (VmRSS); device memory is not in it, so it is not a physical footprint (Linux).", b);
if (r.anon_bytes) |b| try gauge(w, "process_resident_anon_bytes", "gauge", "Current resident anonymous memory (RssAnon): heap, stacks and private maps (Linux).", b);
if (r.file_bytes) |b| try gauge(w, "process_resident_file_bytes", "gauge", "Current resident file-backed memory (RssFile): the binary, libraries and mapped files (Linux).", b);
if (r.shmem_bytes) |b| try gauge(w, "process_resident_shmem_bytes", "gauge", "Current resident shared memory (RssShmem): System V shared memory, tmpfs maps and shared anonymous maps (Linux).", b);
if (r.peak_bytes) |b| try gauge(w, "process_resident_peak_bytes", "gauge", "Kernel lifetime peak resident set (VmHWM); never reset by health (Linux).", b);
}

test "process gauges omit unknown samples and keep current and lifetime peak distinct" {
var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
defer out.deinit();
Expand All @@ -226,6 +238,58 @@ test "process gauges omit unknown samples and keep current and lifetime peak dis
try std.testing.expect(std.mem.indexOf(u8, out.written(), "tensorfold:process_footprint_peak_bytes 12\n") != null);
}

test "resident gauges render each count the kernel reports, and only those" {
var all: std.Io.Writer.Allocating = .init(std.testing.allocator);
defer all.deinit();
try residentGauges(&all.writer, .{ .resident_bytes = 4 << 30, .anon_bytes = 3 << 30, .file_bytes = 768 << 20, .shmem_bytes = 256 << 20, .peak_bytes = 5 << 30 });
const body = all.written();
try std.testing.expect(std.mem.indexOf(u8, body, "# TYPE tensorfold:process_resident_bytes gauge\ntensorfold:process_resident_bytes 4294967296\n") != null);
try std.testing.expect(std.mem.indexOf(u8, body, "tensorfold:process_resident_anon_bytes 3221225472\n") != null);
try std.testing.expect(std.mem.indexOf(u8, body, "tensorfold:process_resident_file_bytes 805306368\n") != null);
try std.testing.expect(std.mem.indexOf(u8, body, "tensorfold:process_resident_shmem_bytes 268435456\n") != null);
try std.testing.expect(std.mem.indexOf(u8, body, "tensorfold:process_resident_peak_bytes 5368709120\n") != null);
try std.testing.expect(std.mem.indexOf(u8, body, "process_footprint") == null); // not a footprint
var old: std.Io.Writer.Allocating = .init(std.testing.allocator);
defer old.deinit();
try residentGauges(&old.writer, null);
try std.testing.expectEqual(@as(usize, 0), old.written().len);
try residentGauges(&old.writer, .{ .resident_bytes = 1 << 20, .peak_bytes = 2 << 20 }); // a kernel before 4.5
try std.testing.expect(std.mem.indexOf(u8, old.written(), "tensorfold:process_resident_bytes 1048576\n") != null);
try std.testing.expect(std.mem.indexOf(u8, old.written(), "process_resident_anon_bytes") == null);
try std.testing.expect(std.mem.indexOf(u8, old.written(), "process_resident_shmem_bytes") == null);
try std.testing.expect(std.mem.indexOf(u8, old.written(), "tensorfold:process_resident_peak_bytes 2097152\n") != null);
}

test "only a Linux scrape reports the resident set, parked or not, and never as the footprint" {
const gpa = std.testing.allocator;
var m: Metrics = .{ .gpa = gpa };
const stub: RenderStub = .{};
var live: std.Io.Writer.Allocating = .init(gpa);
defer live.deinit();
try m.render(std.testing.io, &live.writer, stub.status_value, &.{}, stub.info_value, stub.memory_value, 4096);
var parked: std.Io.Writer.Allocating = .init(gpa);
defer parked.deinit();
try m.renderParked(std.testing.io, &parked.writer, 4096);
for ([_][]const u8{ live.written(), parked.written() }) |body| {
if (@import("builtin").os.tag != .linux) {
try std.testing.expect(std.mem.indexOf(u8, body, "process_resident_") == null);
continue;
}
try std.testing.expect(std.mem.indexOf(u8, body, "process_footprint_bytes") == null);
const rss = try scraped(body, "\ntensorfold:process_resident_bytes ");
try std.testing.expect(rss > 0);
try std.testing.expect(try scraped(body, "\ntensorfold:process_resident_peak_bytes ") >= rss);
try std.testing.expect(std.mem.indexOf(u8, body, "\ntensorfold:process_resident_anon_bytes ") != null);
}
}

/// The number after `head` in a rendered body.
fn scraped(body: []const u8, head: []const u8) !u64 {
const at = std.mem.indexOf(u8, body, head) orelse return error.NoGauge;
const rest = body[at + head.len ..];
return std.fmt.parseUnsigned(u64, rest[0 .. std.mem.indexOfScalar(u8, rest, '\n') orelse rest.len], 10);
}

fn pools(w: *std.Io.Writer, name: []const u8, label: []const u8, lengths: []const u32, window: u32) !void {
if (lengths.len == 0) return w.print("{s}{s}{{{s}=\"0\"}} 0\n", .{ prefix, name, label });
for (lengths, 0..) |n, i| {
Expand Down
119 changes: 119 additions & 0 deletions zig/src/server/process_resident.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
//! Linux resident set readings from /proc/self/status; neither a physical footprint nor device memory.
const std = @import("std");
const builtin = @import("builtin");

/// Bytes, each null when the file has no such line or its value does not read as kB.
pub const Snapshot = struct {
resident_bytes: ?u64 = null, // VmRSS
anon_bytes: ?u64 = null, // RssAnon: heap, stacks and private maps
file_bytes: ?u64 = null, // RssFile: the binary, libraries and mapped files
shmem_bytes: ?u64 = null, // RssShmem: System V shared memory, tmpfs maps and shared anonymous maps
peak_bytes: ?u64 = null, // VmHWM: the kernel's lifetime peak of VmRSS
};

const fields = [_]struct { key: []const u8, name: []const u8 }{
.{ .key = "VmRSS", .name = "resident_bytes" },
.{ .key = "RssAnon", .name = "anon_bytes" },
.{ .key = "RssFile", .name = "file_bytes" },
.{ .key = "RssShmem", .name = "shmem_bytes" },
.{ .key = "VmHWM", .name = "peak_bytes" },
};

/// The five counts in `text`; null when it has none of them. A repeated line keeps its first value.
pub fn parse(text: []const u8) ?Snapshot {
var out: Snapshot = .{};
var found = false;
var lines = std.mem.splitScalar(u8, text, '\n');
while (lines.next()) |line| {
const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue;
inline for (fields) |f| if (std.mem.eql(u8, line[0..colon], f.key) and @field(out, f.name) == null) {
@field(out, f.name) = kib(line[colon + 1 ..]);
found = found or @field(out, f.name) != null;
};
}
return if (found) out else null;
}

/// " 2032 kB" in bytes; any other unit, a missing number or an overflow is null.
fn kib(value: []const u8) ?u64 {
var words = std.mem.tokenizeAny(u8, value, " \t");
const number = words.next() orelse return null;
const unit = words.next() orelse return null;
if (!std.mem.eql(u8, unit, "kB") or words.next() != null) return null;
const n = std.fmt.parseUnsigned(u64, number, 10) catch return null;
return std.math.mul(u64, n, 1024) catch null;
}

/// The longest /proc/self/status read; the five lines sit in its first kilobyte.
const max_bytes = 4096;

/// One kernel sample into a stack buffer; null off Linux or when the file does not read. Procfs reports size 0.
pub fn read(io: std.Io) ?Snapshot {
if (builtin.os.tag != .linux) return null;
var file = std.Io.Dir.cwd().openFile(io, "/proc/self/status", .{}) catch return null;
defer file.close(io);
var text: [max_bytes]u8 = undefined;
var n: usize = 0;
while (n < text.len) {
const got = file.readStreaming(io, &.{text[n..]}) catch |err| switch (err) {
error.EndOfStream => break,
else => return null,
};
if (got == 0) break;
n += got;
}
// a read cut at max_bytes ends inside a line: parse only whole lines
const whole = if (n < text.len) n else (std.mem.lastIndexOfScalar(u8, &text, '\n') orelse return null) + 1;
return parse(text[0..whole]);
}

test "status lines parse to bytes" {
const text = "Name:\ttensorfold\nVmPeak:\t 9437184 kB\nVmHWM:\t 4508876 kB\nVmRSS:\t 4194304 kB\n" ++
"RssAnon:\t 3145728 kB\nRssFile:\t 786432 kB\nRssShmem:\t 262144 kB\nVmData:\t 3500000 kB\nThreads:\t42\n";
const s = parse(text).?;
try std.testing.expectEqual(@as(?u64, 4194304 * 1024), s.resident_bytes);
try std.testing.expectEqual(@as(?u64, 3145728 * 1024), s.anon_bytes);
try std.testing.expectEqual(@as(?u64, 786432 * 1024), s.file_bytes);
try std.testing.expectEqual(@as(?u64, 262144 * 1024), s.shmem_bytes);
try std.testing.expectEqual(@as(?u64, 4508876 * 1024), s.peak_bytes);
}

test "a 64 KiB-page kernel still counts in kB" {
const s = parse("VmHWM:\t 131136 kB\nVmRSS:\t 131072 kB\nRssAnon:\t 65536 kB\nRssFile:\t 65472 kB\nRssShmem:\t 64 kB\n").?;
try std.testing.expectEqual(@as(?u64, 131072 << 10), s.resident_bytes);
try std.testing.expectEqual(@as(?u64, 64 << 10), s.shmem_bytes);
try std.testing.expectEqual(@as(?u64, 131136 << 10), s.peak_bytes);
}

test "missing lines, other units and bad numbers are unknown, not zero" {
// kernels before 4.5 have no RssAnon, RssFile or RssShmem
const old = parse("VmHWM:\t 2048 kB\nVmRSS:\t 1024 kB\nVmData:\t 9 kB\n").?;
try std.testing.expectEqual(@as(?u64, 1024 << 10), old.resident_bytes);
try std.testing.expectEqual(@as(?u64, 2048 << 10), old.peak_bytes);
try std.testing.expectEqual(@as(?u64, null), old.anon_bytes);
try std.testing.expectEqual(@as(?u64, null), old.file_bytes);
try std.testing.expectEqual(@as(?u64, null), old.shmem_bytes);
const bad = parse("VmRSS:\t 1024 MB\nRssAnon:\t kB\nRssFile:\t 12x kB\nRssShmem:\t 99999999999999999999 kB\nVmHWM:\t 4 kB extra\n");
try std.testing.expectEqual(@as(?Snapshot, null), bad);
const overflow = parse("VmRSS:\t 18014398509481984 kB\nRssAnon:\t 1 kB\n").?; // 2^54 kB is 2^64 bytes
try std.testing.expectEqual(@as(?u64, null), overflow.resident_bytes);
try std.testing.expectEqual(@as(?u64, 1024), overflow.anon_bytes);
try std.testing.expectEqual(@as(?Snapshot, null), parse(""));
try std.testing.expectEqual(@as(?Snapshot, null), parse("MemTotal:\t 1 kB\nVmRSSX:\t 1 kB\n"));
}

test "a repeated line keeps its first value" {
const s = parse("VmRSS:\t 1 kB\nVmRSS:\t 2 kB\n").?;
try std.testing.expectEqual(@as(?u64, 1024), s.resident_bytes);
}

test "this process's status reads whole and parses (Linux)" {
if (builtin.os.tag != .linux) {
try std.testing.expect(read(std.testing.io) == null);
return;
}
const s = read(std.testing.io) orelse return error.Unreadable;
try std.testing.expect(s.resident_bytes.? > 0);
try std.testing.expect(s.peak_bytes.? >= s.resident_bytes.?);
if (s.anon_bytes) |anon| try std.testing.expect(anon > 0 and anon <= s.peak_bytes.?); // Linux 4.5 and later
}
1 change: 1 addition & 0 deletions zig/src/server/root.zig
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ test {
_ = @import("health_test.zig");
_ = @import("memory_routes.zig");
_ = @import("process_memory.zig");
_ = @import("process_resident.zig");
_ = @import("log.zig");
_ = @import("request_log.zig");
_ = @import("messages.zig");
Expand Down