Lightpanda: the headless browser designed for AI and automation
mem: Return freed malloc memory to the OS when a connection closes
Lucien Coffe87a69181e667
diff --git a/src/malloc_tuning.zig b/src/malloc_tuning.zigindex fe38cd580..f2917f926 100644--- a/src/malloc_tuning.zig+++ b/src/malloc_tuning.zig@@ -27,6 +27,13 @@//!//! glibc's own `MALLOC_MMAP_THRESHOLD_` / `GLIBC_TUNABLES` remain the override://! when either sets the threshold, it is left alone.+//!+//! glibc also gives a heap's free memory back only from its top: free memory+//! below a chunk that is still live stays resident. A connection's allocations+//! (on its own thread and on V8's platform worker threads) are freed when it+//! closes, but the few chunks that outlive it keep that memory in the process,+//! so the idle footprint climbs to the largest page served so far. `trim`+//! returns it: the server calls it when a connection's worker is done.const std = @import("std");const builtin = @import("builtin");@@ -36,12 +43,15 @@ const log = lp.log;const MMAP_THRESHOLD = 128 * 1024;+const is_glibc = builtin.target.os.tag == .linux and builtin.target.abi.isGnu();+// malloc.hconst M_MMAP_THRESHOLD: c_int = -3;extern "c" fn mallopt(param: c_int, value: c_int) c_int;+extern "c" fn malloc_trim(pad: usize) c_int;pub fn apply() void {- if (comptime (builtin.target.os.tag != .linux or builtin.target.abi.isGnu() == false)) {+ if (comptime !is_glibc) {return;}if (userConfigured()) {@@ -52,6 +62,15 @@ pub fn apply() void {}}+/// Returns the free memory of every malloc arena to the OS, including the+/// free pages below live chunks that free() never returns.+pub fn trim() void {+ if (comptime !is_glibc) {+ return;+ }+ _ = malloc_trim(0);+}+fn userConfigured() bool {if (std.c.getenv("MALLOC_MMAP_THRESHOLD_") != null) {return true;@@ -81,3 +100,60 @@ test "malloc_tuning: glibc env overrides" {defer _ = unsetenv(@constCast("MALLOC_MMAP_THRESHOLD_"));try testing.expectEqual(true, userConfigured());}++test "malloc_tuning: trim returns the free memory below a live chunk" {+ if (comptime !is_glibc) {+ return error.SkipZigTest;+ }++ const Retained = struct {+ baseline: usize = 0,+ before: usize = 0,+ after: usize = 0,++ // On its own thread, so it works in a thread arena like a+ // connection's worker, away from the other tests' allocations.+ fn run(r: *@This()) void {+ // blocks under the mmap threshold, so they come from the arena+ const block = 16 * 1024;+ const count = 2048; // 32MB, within one 64MB thread heap+ var blocks: [count]?*anyopaque = undefined;++ r.baseline = residentBytes();+ for (&blocks) |*b| {+ b.* = std.c.malloc(block);+ @memset(@as([*]u8, @ptrCast(b.*.?))[0..block], 0xaa);+ }+ // a chunk that outlives the others, above them+ const live = std.c.malloc(64);+ for (blocks) |b| {+ std.c.free(b);+ }+ r.before = residentBytes();+ trim();+ r.after = residentBytes();+ std.c.free(live);+ }++ // the resident set of the process, from /proc/self/statm (in pages)+ fn residentBytes() usize {+ var buf: [128]u8 = undefined;+ const fd = std.c.open("/proc/self/statm", .{ .ACCMODE = .RDONLY, .CLOEXEC = true });+ if (fd < 0) return 0;+ defer _ = std.c.close(fd);+ const n = std.c.read(fd, &buf, buf.len);+ if (n <= 0) return 0;+ var it = std.mem.tokenizeScalar(u8, buf[0..@intCast(n)], ' ');+ _ = it.next(); // size+ const resident = std.fmt.parseInt(usize, it.next() orelse return 0, 10) catch return 0;+ return resident * std.heap.pageSize();+ }+ };++ var r: Retained = .{};+ const t = try std.Thread.spawn(.{}, Retained.run, .{&r});+ t.join();+ // free() kept the blocks resident, trim() gave them back+ try testing.expect(r.before -| r.baseline >= 24 * 1024 * 1024);+ try testing.expect(r.before -| r.after >= 24 * 1024 * 1024);+}diff --git a/src/server/Server.zig b/src/server/Server.zigindex f331ef3e2..1b83edfa8 100644--- a/src/server/Server.zig+++ b/src/server/Server.zig@@ -1336,6 +1336,9 @@ pub const Worker = struct {log.err(.serve, "worker init", .{ .err = err });self.releaseConnection();};+ // The connection's browser, pages and isolate are freed: hand that+ // memory back, or the process keeps its largest page's footprint.+ lp.malloc_tuning.trim();}fn _start(self: *Worker, origin: Origin) !void {