SmpAllocator does not reuse freed small allocations when threads are created and destroyed frequently, causing unbounded RSS growth #36969

Open
opened 2026-09-26 10:21:51 +02:00 by tokju · 3 comments

Zig Version

0.17.0-dev.2294+71403f299

Steps to Reproduce, Observed Behavior, and Expected Behavior

Possible Related: #36533

Reproduce

run zig run repro.zig on linux x86_64

const std = @import("std");

var n_alloc: std.atomic.Value(u64) = .init(0);
var n_free: std.atomic.Value(u64) = .init(0);
var bytes_alloc: std.atomic.Value(u64) = .init(0);
var bytes_free: std.atomic.Value(u64) = .init(0);

const Proxy = struct {
    fn alloc(_: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 {
        const p = std.heap.smp_allocator.vtable.alloc(undefined, len, a, ra);
        if (p != null) {
            _ = n_alloc.fetchAdd(1, .monotonic);
            _ = bytes_alloc.fetchAdd(len, .monotonic);
        }
        return p;
    }
    fn resize(_: *anyopaque, m: []u8, a: std.mem.Alignment, new_len: usize, ra: usize) bool {
        const ok = std.heap.smp_allocator.vtable.resize(undefined, m, a, new_len, ra);
        if (ok) {
            if (new_len > m.len) _ = bytes_alloc.fetchAdd(new_len - m.len, .monotonic)
            else _ = bytes_free.fetchAdd(m.len - new_len, .monotonic);
        }
        return ok;
    }
    fn remap(_: *anyopaque, m: []u8, a: std.mem.Alignment, new_len: usize, ra: usize) ?[*]u8 {
        const p = std.heap.smp_allocator.vtable.remap(undefined, m, a, new_len, ra);
        if (p != null) {
            if (new_len > m.len) _ = bytes_alloc.fetchAdd(new_len - m.len, .monotonic)
            else _ = bytes_free.fetchAdd(m.len - new_len, .monotonic);
        }
        return p;
    }
    fn free(_: *anyopaque, m: []u8, a: std.mem.Alignment, ra: usize) void {
        _ = n_free.fetchAdd(1, .monotonic);
        _ = bytes_free.fetchAdd(m.len, .monotonic);
        std.heap.smp_allocator.vtable.free(undefined, m, a, ra);
    }
};
const proxy: std.mem.Allocator = .{ .ptr = undefined, .vtable = &.{
    .alloc = Proxy.alloc, .resize = Proxy.resize, .remap = Proxy.remap, .free = Proxy.free,
} };

fn rssKb() u64 {
    var buf: [256]u8 = undefined;
    const fd = std.posix.openat(std.posix.AT.FDCWD, "/proc/self/statm", .{ .ACCMODE = .RDONLY }, 0) catch return 0;
    defer _ = std.os.linux.close(fd);
    const n = std.posix.read(fd, &buf) catch return 0;
    var it = std.mem.tokenizeScalar(u8, buf[0..n], ' ');
    _ = it.next();
    const resident = it.next() orelse return 0;
    return (std.fmt.parseInt(u64, resident, 10) catch 0) * 4;
}

const Ctx = struct {
    go: std.atomic.Value(bool) = .init(false),
    blocks: [3][]u8 = .{ &.{}, &.{}, &.{} },
};

fn worker(ctx: *Ctx, idx: usize) void {
    var list: std.ArrayList(u8) = .empty;
    var i: usize = 0;
    while (i < 8) : (i += 1) list.appendSlice(proxy, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ) catch {};
    ctx.blocks[idx] = proxy.alloc(u8, 128 + idx * 64) catch &.{};
    while (!ctx.go.load(.acquire)) std.Thread.yield() catch {};
    if (ctx.blocks[idx].len > 0) proxy.free(ctx.blocks[idx]);
    list.deinit(proxy);
}

pub fn main() !void {
    const iters: u32 = 30_000;
    var i: u32 = 0;
    while (i < iters) : (i += 1) {
        var ctx = Ctx{};
        var arena_state = std.heap.ArenaAllocator.init(proxy);
        var a0: usize = 0;
        while (a0 < 6) : (a0 += 1) {
            const buf = try arena_state.allocator().alloc(u8, @as(usize, 4096) << @intCast(a0));
            @memset(buf, 0xAB);
        }
        var threads: [3]std.Thread = undefined;
        for (&threads, 0..) |*t, idx| t.* = try std.Thread.spawn(.{}, worker, .{ &ctx, idx });
        ctx.go.store(true, .release);
        for (threads) |t| t.join();
        arena_state.deinit();

        if (i % 5000 == 0 or i == iters - 1) {
            std.debug.print("iter {d:>6}  rss {d:>6} kB  alloc={d} free={d} BalloB={d} BfreeB={d}\n", .{
                i, rssKb(), n_alloc.load(.monotonic), n_free.load(.monotonic),
                bytes_alloc.load(.monotonic) / 1024, bytes_free.load(.monotonic) / 1024,
            });
        }
    }
}

It output on my computer(8 core cpu, archlinux)

iter      0  rss   1708 kB  alloc=14 free=14 BalloB=726 BfreeB=726
iter   5000  rss   8216 kB  alloc=70014 free=70014 BalloB=3633441 BfreeB=3633441
iter  10000  rss  14472 kB  alloc=140014 free=140014 BalloB=7266156 BfreeB=7266156
iter  15000  rss  20720 kB  alloc=210014 free=210014 BalloB=10898871 BfreeB=10898871
iter  20000  rss  26976 kB  alloc=280014 free=280014 BalloB=14531585 BfreeB=14531585
iter  25000  rss  33224 kB  alloc=350014 free=350014 BalloB=18164300 BfreeB=18164300
iter  29999  rss  39472 kB  alloc=420000 free=420000 BalloB=21796289 BfreeB=21796289

The Rss is increasing!!The 0.16.0 also

If replace the smp_allocator with page_allocator,the rss is flat。

After discovering this issue, I delved into the source code to investigate it further.

I change the std/heap/SmpAllocator.zig on the struct Thread to count(On zig 0.16.0 lib)

pushes: [size_class_count]u64 = @splat(0),
pops:   [size_class_count]u64 = @splat(0),
bumps:  [size_class_count]u64 = @splat(0),
slot_maps: u64 = 0,

and write a export function:

export fn smpDumpStats() void {
    var buf: [1 << 14]u8 = undefined;
    var w = std.Io.Writer.fixed(&buf);
    var total_push: [size_class_count]u64 = @splat(0);
    var total_pop: [size_class_count]u64 = @splat(0);
    for (&global.threads) |*t| {
        for (0..size_class_count) |c| {
            total_push[c] += t.pushes[c];
            total_pop[c] += t.pops[c];
        }
    }
    for (0..size_class_count) |c| {
        w.print("class {d:>2} (slot {d:>5}B): push {d:>8} pop {d:>8}\n", .{ c, slotSize(c), total_push[c], total_pop[c] }) catch {};
    }
    var retained: [size_class_count]u64 = @splat(0);
    for (&global.threads) |*t| {
        for (0..size_class_count) |c| {
            var p = t.frees[c];
            while (p != 0) : (p = @as(*usize, @ptrFromInt(p)).*) retained[c] += 1;
        }
    }
    var bytes: u64 = 0;
    var total: u64 = 0;
    for (0..size_class_count) |c| {
        bytes += retained[c] * slotSize(c);
        total += retained[c];
        if (retained[c] != 0)
            w.print("  class {d:>2}: retained {d}\n", .{ c, retained[c] }) catch {};
    }
    w.print("retained-in-freelist: {d} blocks, {d} bytes\n", .{ total, bytes }) catch {};
    const out = w.buffered();
    _ = std.os.linux.write(2, out.ptr, out.len);
}

And then run the repro.zig, new output

== SmpAllocator debug ==
slabs mapped: 590, large maps: 90000, large unmaps: 90000
class  0 (slot     8B): push        0 pop        0 bump        0
class  1 (slot    16B): push        0 pop        0 bump        0
class  2 (slot    32B): push        0 pop        0 bump        0
class  3 (slot    64B): push        0 pop        0 bump        0
class  4 (slot   128B): push    30000 pop    29999 bump        0
class  5 (slot   256B): push   150000 pop    60000 bump    89648
class  6 (slot   512B): push    90000 pop    59996 bump    29769
class  7 (slot  1024B): push        0 pop        0 bump        0
class  8 (slot  2048B): push        0 pop        0 bump        0
class  9 (slot  4096B): push        0 pop        0 bump        0
class 10 (slot  8192B): push    30000 pop    29999 bump        0
class 11 (slot 16384B): push        0 pop        0 bump        0
class 12 (slot 32768B): push    30000 pop    29999 bump        0
retained-in-freelist: 120007 blocks, 38443136 bytes
  class  4 (slot   128B): retained 1
  class  5 (slot   256B): retained 90000
  class  6 (slot   512B): retained 30004
  class 10 (slot  8192B): retained 1
  class 12 (slot 32768B): retained 1
slot   1: push 0 pop 0 bump 89648 slabmaps 353
slot   2: push 269985 pop 179988 bump 29769 slabmaps 236
slot   3: push 60015 pop 30005 bump 0 slabmaps 1
slot   4: push 3 pop 0 bump 0 slabmaps 0

The allocation thread is stuck on slot 1, performing “bump” operations (mapping 353 new slabs), while the released blocks are piling up in slots 2 and 3 and are virtually ignored. Meanwhile, large blocks (in the PageAllocator path) show a strict 1:1 ratio of maps to unmaps (90,000 each)—the issue occurs on small block

### Zig Version 0.17.0-dev.2294+71403f299 ### Steps to Reproduce, Observed Behavior, and Expected Behavior Possible Related: https://codeberg.org/ziglang/zig/issues/36533 ## Reproduce run `zig run repro.zig` on linux x86_64 ```zig const std = @import("std"); var n_alloc: std.atomic.Value(u64) = .init(0); var n_free: std.atomic.Value(u64) = .init(0); var bytes_alloc: std.atomic.Value(u64) = .init(0); var bytes_free: std.atomic.Value(u64) = .init(0); const Proxy = struct { fn alloc(_: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 { const p = std.heap.smp_allocator.vtable.alloc(undefined, len, a, ra); if (p != null) { _ = n_alloc.fetchAdd(1, .monotonic); _ = bytes_alloc.fetchAdd(len, .monotonic); } return p; } fn resize(_: *anyopaque, m: []u8, a: std.mem.Alignment, new_len: usize, ra: usize) bool { const ok = std.heap.smp_allocator.vtable.resize(undefined, m, a, new_len, ra); if (ok) { if (new_len > m.len) _ = bytes_alloc.fetchAdd(new_len - m.len, .monotonic) else _ = bytes_free.fetchAdd(m.len - new_len, .monotonic); } return ok; } fn remap(_: *anyopaque, m: []u8, a: std.mem.Alignment, new_len: usize, ra: usize) ?[*]u8 { const p = std.heap.smp_allocator.vtable.remap(undefined, m, a, new_len, ra); if (p != null) { if (new_len > m.len) _ = bytes_alloc.fetchAdd(new_len - m.len, .monotonic) else _ = bytes_free.fetchAdd(m.len - new_len, .monotonic); } return p; } fn free(_: *anyopaque, m: []u8, a: std.mem.Alignment, ra: usize) void { _ = n_free.fetchAdd(1, .monotonic); _ = bytes_free.fetchAdd(m.len, .monotonic); std.heap.smp_allocator.vtable.free(undefined, m, a, ra); } }; const proxy: std.mem.Allocator = .{ .ptr = undefined, .vtable = &.{ .alloc = Proxy.alloc, .resize = Proxy.resize, .remap = Proxy.remap, .free = Proxy.free, } }; fn rssKb() u64 { var buf: [256]u8 = undefined; const fd = std.posix.openat(std.posix.AT.FDCWD, "/proc/self/statm", .{ .ACCMODE = .RDONLY }, 0) catch return 0; defer _ = std.os.linux.close(fd); const n = std.posix.read(fd, &buf) catch return 0; var it = std.mem.tokenizeScalar(u8, buf[0..n], ' '); _ = it.next(); const resident = it.next() orelse return 0; return (std.fmt.parseInt(u64, resident, 10) catch 0) * 4; } const Ctx = struct { go: std.atomic.Value(bool) = .init(false), blocks: [3][]u8 = .{ &.{}, &.{}, &.{} }, }; fn worker(ctx: *Ctx, idx: usize) void { var list: std.ArrayList(u8) = .empty; var i: usize = 0; while (i < 8) : (i += 1) list.appendSlice(proxy, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ) catch {}; ctx.blocks[idx] = proxy.alloc(u8, 128 + idx * 64) catch &.{}; while (!ctx.go.load(.acquire)) std.Thread.yield() catch {}; if (ctx.blocks[idx].len > 0) proxy.free(ctx.blocks[idx]); list.deinit(proxy); } pub fn main() !void { const iters: u32 = 30_000; var i: u32 = 0; while (i < iters) : (i += 1) { var ctx = Ctx{}; var arena_state = std.heap.ArenaAllocator.init(proxy); var a0: usize = 0; while (a0 < 6) : (a0 += 1) { const buf = try arena_state.allocator().alloc(u8, @as(usize, 4096) << @intCast(a0)); @memset(buf, 0xAB); } var threads: [3]std.Thread = undefined; for (&threads, 0..) |*t, idx| t.* = try std.Thread.spawn(.{}, worker, .{ &ctx, idx }); ctx.go.store(true, .release); for (threads) |t| t.join(); arena_state.deinit(); if (i % 5000 == 0 or i == iters - 1) { std.debug.print("iter {d:>6} rss {d:>6} kB alloc={d} free={d} BalloB={d} BfreeB={d}\n", .{ i, rssKb(), n_alloc.load(.monotonic), n_free.load(.monotonic), bytes_alloc.load(.monotonic) / 1024, bytes_free.load(.monotonic) / 1024, }); } } } ``` It output on my computer(8 core cpu, archlinux) ``` iter 0 rss 1708 kB alloc=14 free=14 BalloB=726 BfreeB=726 iter 5000 rss 8216 kB alloc=70014 free=70014 BalloB=3633441 BfreeB=3633441 iter 10000 rss 14472 kB alloc=140014 free=140014 BalloB=7266156 BfreeB=7266156 iter 15000 rss 20720 kB alloc=210014 free=210014 BalloB=10898871 BfreeB=10898871 iter 20000 rss 26976 kB alloc=280014 free=280014 BalloB=14531585 BfreeB=14531585 iter 25000 rss 33224 kB alloc=350014 free=350014 BalloB=18164300 BfreeB=18164300 iter 29999 rss 39472 kB alloc=420000 free=420000 BalloB=21796289 BfreeB=21796289 ``` The Rss is increasing!!The `0.16.0` also If replace the `smp_allocator` with `page_allocator`,the rss is flat。 After discovering this issue, I delved into the source code to investigate it further. I change the `std/heap/SmpAllocator.zig` on the struct `Thread` to count(On zig `0.16.0` lib) ```zig pushes: [size_class_count]u64 = @splat(0), pops: [size_class_count]u64 = @splat(0), bumps: [size_class_count]u64 = @splat(0), slot_maps: u64 = 0, ``` and write a export function: ```zig export fn smpDumpStats() void { var buf: [1 << 14]u8 = undefined; var w = std.Io.Writer.fixed(&buf); var total_push: [size_class_count]u64 = @splat(0); var total_pop: [size_class_count]u64 = @splat(0); for (&global.threads) |*t| { for (0..size_class_count) |c| { total_push[c] += t.pushes[c]; total_pop[c] += t.pops[c]; } } for (0..size_class_count) |c| { w.print("class {d:>2} (slot {d:>5}B): push {d:>8} pop {d:>8}\n", .{ c, slotSize(c), total_push[c], total_pop[c] }) catch {}; } var retained: [size_class_count]u64 = @splat(0); for (&global.threads) |*t| { for (0..size_class_count) |c| { var p = t.frees[c]; while (p != 0) : (p = @as(*usize, @ptrFromInt(p)).*) retained[c] += 1; } } var bytes: u64 = 0; var total: u64 = 0; for (0..size_class_count) |c| { bytes += retained[c] * slotSize(c); total += retained[c]; if (retained[c] != 0) w.print(" class {d:>2}: retained {d}\n", .{ c, retained[c] }) catch {}; } w.print("retained-in-freelist: {d} blocks, {d} bytes\n", .{ total, bytes }) catch {}; const out = w.buffered(); _ = std.os.linux.write(2, out.ptr, out.len); } ``` And then run the `repro.zig`, new output ``` == SmpAllocator debug == slabs mapped: 590, large maps: 90000, large unmaps: 90000 class 0 (slot 8B): push 0 pop 0 bump 0 class 1 (slot 16B): push 0 pop 0 bump 0 class 2 (slot 32B): push 0 pop 0 bump 0 class 3 (slot 64B): push 0 pop 0 bump 0 class 4 (slot 128B): push 30000 pop 29999 bump 0 class 5 (slot 256B): push 150000 pop 60000 bump 89648 class 6 (slot 512B): push 90000 pop 59996 bump 29769 class 7 (slot 1024B): push 0 pop 0 bump 0 class 8 (slot 2048B): push 0 pop 0 bump 0 class 9 (slot 4096B): push 0 pop 0 bump 0 class 10 (slot 8192B): push 30000 pop 29999 bump 0 class 11 (slot 16384B): push 0 pop 0 bump 0 class 12 (slot 32768B): push 30000 pop 29999 bump 0 retained-in-freelist: 120007 blocks, 38443136 bytes class 4 (slot 128B): retained 1 class 5 (slot 256B): retained 90000 class 6 (slot 512B): retained 30004 class 10 (slot 8192B): retained 1 class 12 (slot 32768B): retained 1 slot 1: push 0 pop 0 bump 89648 slabmaps 353 slot 2: push 269985 pop 179988 bump 29769 slabmaps 236 slot 3: push 60015 pop 30005 bump 0 slabmaps 1 slot 4: push 3 pop 0 bump 0 slabmaps 0 ``` The allocation thread is stuck on slot 1, performing “bump” operations (mapping 353 new slabs), while the released blocks are piling up in slots 2 and 3 and are virtually ignored. Meanwhile, large blocks (in the PageAllocator path) show a strict 1:1 ratio of maps to unmaps (90,000 each)—the issue occurs on small block
alexrp added this to the Urgent milestone 2026-09-26 12:18:55 +02:00
Contributor

looks like #36294 fixes this
before

iter      0  rss    616 kB  alloc=14 free=14 BalloB=726 BfreeB=726
iter   5000  rss   7064 kB  alloc=70014 free=70014 BalloB=3633441 BfreeB=3633441
iter  10000  rss  13316 kB  alloc=140014 free=140014 BalloB=7266156 BfreeB=7266156
iter  15000  rss  19564 kB  alloc=210014 free=210014 BalloB=10898871 BfreeB=10898871
iter  20000  rss  25816 kB  alloc=280014 free=280014 BalloB=14531585 BfreeB=14531585
iter  25000  rss  32064 kB  alloc=350014 free=350014 BalloB=18164300 BfreeB=18164300
iter  29999  rss  38312 kB  alloc=420000 free=420000 BalloB=21796289 BfreeB=21796289

after

iter      0  rss   2612 kB  alloc=14 free=14 BalloB=726 BfreeB=726
iter   5000  rss   6976 kB  alloc=70014 free=70014 BalloB=3633441 BfreeB=3633441
iter  10000  rss   6976 kB  alloc=140014 free=140014 BalloB=7266156 BfreeB=7266156
iter  15000  rss   6976 kB  alloc=210014 free=210014 BalloB=10898871 BfreeB=10898871
iter  20000  rss   6976 kB  alloc=280014 free=280014 BalloB=14531585 BfreeB=14531585
iter  25000  rss   6976 kB  alloc=350014 free=350014 BalloB=18164300 BfreeB=18164300
iter  29999  rss   6976 kB  alloc=420000 free=420000 BalloB=21796289 BfreeB=21796289
looks like https://codeberg.org/ziglang/zig/pulls/36294 fixes this before ``` iter 0 rss 616 kB alloc=14 free=14 BalloB=726 BfreeB=726 iter 5000 rss 7064 kB alloc=70014 free=70014 BalloB=3633441 BfreeB=3633441 iter 10000 rss 13316 kB alloc=140014 free=140014 BalloB=7266156 BfreeB=7266156 iter 15000 rss 19564 kB alloc=210014 free=210014 BalloB=10898871 BfreeB=10898871 iter 20000 rss 25816 kB alloc=280014 free=280014 BalloB=14531585 BfreeB=14531585 iter 25000 rss 32064 kB alloc=350014 free=350014 BalloB=18164300 BfreeB=18164300 iter 29999 rss 38312 kB alloc=420000 free=420000 BalloB=21796289 BfreeB=21796289 ``` after ``` iter 0 rss 2612 kB alloc=14 free=14 BalloB=726 BfreeB=726 iter 5000 rss 6976 kB alloc=70014 free=70014 BalloB=3633441 BfreeB=3633441 iter 10000 rss 6976 kB alloc=140014 free=140014 BalloB=7266156 BfreeB=7266156 iter 15000 rss 6976 kB alloc=210014 free=210014 BalloB=10898871 BfreeB=10898871 iter 20000 rss 6976 kB alloc=280014 free=280014 BalloB=14531585 BfreeB=14531585 iter 25000 rss 6976 kB alloc=350014 free=350014 BalloB=18164300 BfreeB=18164300 iter 29999 rss 6976 kB alloc=420000 free=420000 BalloB=21796289 BfreeB=21796289 ```

Another trigger for the same root cause, one that does not need thread churn: long-lived threads (e.g. a tokio multi-threaded runtime) where blocks are allocated on one thread and freed on another. We hit this with Rust binaries built via cargo-zigbuild for x86_64-unknown-linux-musl with Zig 0.16.0, where libc malloc is SmpAllocator (lib/c/malloc.zig).
▎
▎ Observed on a long-running service on a 2-vCPU host: bytes in use stayed flat over ~65 h while anonymous RSS grew linearly (~2–2.5 MB/h, not converging). Walking the allocator's global state showed essentially all of the growth sitting in free lists (mostly small size classes), piled up on slot 1 while slot 0 kept mapping new slabs. The same binary on a 1-vCPU host stays flat for 10+ days, and the same workload linked with jemalloc stays flat.
▎
▎ Mechanism, as far as I can read lib/std/heap/SmpAllocator.zig at 0.16.0:
▎
▎ 1. free (~L200–215) pushes the block onto the free list of whichever slot the freeing thread holds, never back to the slot it was allocated from.
▎ 2. In alloc, once the own free list is empty and the bump region is exhausted, it unlocks and tryLocks (index + 1) % cpu_count (~L160–172). With cpu_count == 2, if that slot is busy (often exactly the thread that is freeing into it), the loop wraps back to its own slot with search_count == 1, and max_alloc_search = 1 sends it straight to PageAllocator.map for a new 64 KiB slab (~L151–157), while the other slot's list holds plenty of free blocks of that class.
▎ 3. Small-class slabs are never unmapped and nothing rebalances between slots, so a steady producer/consumer pattern makes the consumer's free list grow without bound.
▎
▎ With cpu_count == 1, (index + 1) % 1 == 0: every thread shares one set of free lists, frees are always reused, and the growth disappears. That matches the 1-vCPU observation above.
▎
▎ Since SmpAllocator is the default libc malloc on multi-threaded non-wasm targets, this silently affects programs linked through zig cc, e.g. cargo-zigbuild users who picked up 0.16 (https://github.com/ZingerLittleBee/ServerBee/pull/180 pinned 0.15.2 for the same symptom). Routing frees back to the owning slot, as in #36294, looks like it would cover this pattern too.

Another trigger for the same root cause, one that does not need thread churn: long-lived threads (e.g. a tokio multi-threaded runtime) where blocks are allocated on one thread and freed on another. We hit this with Rust binaries built via cargo-zigbuild for x86_64-unknown-linux-musl with Zig 0.16.0, where libc malloc is SmpAllocator (lib/c/malloc.zig). ▎ ▎ Observed on a long-running service on a 2-vCPU host: bytes in use stayed flat over ~65 h while anonymous RSS grew linearly (~2–2.5 MB/h, not converging). Walking the allocator's global state showed essentially all of the growth sitting in free lists (mostly small size classes), piled up on slot 1 while slot 0 kept mapping new slabs. The same binary on a 1-vCPU host stays flat for 10+ days, and the same workload linked with jemalloc stays flat. ▎ ▎ Mechanism, as far as I can read lib/std/heap/SmpAllocator.zig at 0.16.0: ▎ ▎ 1. free (~L200–215) pushes the block onto the free list of whichever slot the freeing thread holds, never back to the slot it was allocated from. ▎ 2. In alloc, once the own free list is empty and the bump region is exhausted, it unlocks and tryLocks (index + 1) % cpu_count (~L160–172). With cpu_count == 2, if that slot is busy (often exactly the thread that is freeing into it), the loop wraps back to its own slot with search_count == 1, and max_alloc_search = 1 sends it straight to PageAllocator.map for a new 64 KiB slab (~L151–157), while the other slot's list holds plenty of free blocks of that class. ▎ 3. Small-class slabs are never unmapped and nothing rebalances between slots, so a steady producer/consumer pattern makes the consumer's free list grow without bound. ▎ ▎ With cpu_count == 1, (index + 1) % 1 == 0: every thread shares one set of free lists, frees are always reused, and the growth disappears. That matches the 1-vCPU observation above. ▎ ▎ Since SmpAllocator is the default libc malloc on multi-threaded non-wasm targets, this silently affects programs linked through zig cc, e.g. cargo-zigbuild users who picked up 0.16 (https://github.com/ZingerLittleBee/ServerBee/pull/180 pinned 0.15.2 for the same symptom). Routing frees back to the owning slot, as in #36294, looks like it would cover this pattern too.

Another data point for this issue, with a smaller repro: there's no thread churn, just two long-lived threads.

One thread allocates and the other frees. It also goes through libc malloc when building C with zig cc for static musl, because lib/c/malloc.zig wraps SmpAllocator. I hit this in a production daemon, an ADS-B receiver built -target aarch64-linux-musl -static. RSS grew without bound on Raspberry Pi 4/5 boxes, while a glibc build of the same code stayed at a 1–4 MB peak heap under heaptrack.

Repro (std only, no libc)

const std = @import("std");

const gpa = std.heap.smp_allocator;
const block_len = 400;
const ring_len = 1024;

var ring: [ring_len]?[]u8 = @splat(null);
var head: std.atomic.Value(usize) = .init(0);
var tail: std.atomic.Value(usize) = .init(0);

fn producer() void {
    while (true) {
        const h = head.load(.monotonic);
        if (h - tail.load(.acquire) == ring_len) {
            std.atomic.spinLoopHint();
            continue;
        }
        ring[h % ring_len] = gpa.alloc(u8, block_len) catch @panic("OOM");
        head.store(h + 1, .release);
    }
}

fn consumer() void {
    while (true) {
        const t = tail.load(.monotonic);
        if (t == head.load(.acquire)) {
            std.atomic.spinLoopHint();
            continue;
        }
        gpa.free(ring[t % ring_len].?);
        ring[t % ring_len] = null;
        tail.store(t + 1, .release);
    }
}

pub fn main() !void {
    const p = try std.Thread.spawn(.{}, producer, .{});
    const c = try std.Thread.spawn(.{}, consumer, .{});
    p.join();
    c.join();
}

At most 1024 × 400 B (~400 KiB) is ever live.

zig build-exe repro.zig -O ReleaseFast
./repro & while sleep 6; do grep VmRSS /proc/$!/status; done

The C equivalent (same ring, malloc/free, two pthreads) built with
zig cc -target aarch64-linux-musl -static -O2 repro.c -lpthread behaves the same way.

Results, Zig 0.17.0

aarch64 Fedora 44 VM with 4 vCPUs (Apple M-series host), RSS after 30 s:

4 CPUs taskset -c 0
repro.zig (smp_allocator) 1.0 MB → 609 MB 1.5 MB, flat
repro.c, zig cc static musl 0.6 MB → 866 MB 0.6 MB, flat
repro.c, glibc malloc 5.1 MB, flat —
repro.zig + #36294 applied to 0.17.0 1.5 MB, flat —
repro.c + #36294 applied to 0.17.0 0.6 MB, flat —

The same repro.zig on macOS 27 (aarch64, 14 cores) reaches 4 GB in 40 s.

SmpAllocator.zig and lib/c/malloc.zig on master (0.18.0-dev.253+16d31ceed) are byte-identical to 0.17.0's, so master is affected too.

Mechanism

This matches tokju's instrumentation:

  • free pushes onto the free list of whichever slot the freeing thread currently holds.
  • Once contention has moved the two threads onto different slots, the producer's slot never sees those blocks. It looks at only one neighbour (max_alloc_search = 1) before mapping a fresh slab.
  • Small-allocation slabs are never unmapped, so the growth is permanent.
  • With one CPU there is one slot, which is why taskset -c 0 is flat.

Impact

zig cc static musl binaries get this through plain malloc, so C/C++ projects (and cargo-zigbuild users, as in BlackLuny's comment) are exposed without using any Zig code. The only workaround I've found short of replacing malloc is pinning the process to one CPU. #36294 fixes this repro for me.

Another data point for this issue, with a smaller repro: there's **no thread churn**, just two long-lived threads. One thread allocates and the other frees. It also goes through libc `malloc` when building C with `zig cc` for static musl, because `lib/c/malloc.zig` wraps `SmpAllocator`. I hit this in a production daemon, an ADS-B receiver built `-target aarch64-linux-musl -static`. RSS grew without bound on Raspberry Pi 4/5 boxes, while a glibc build of the same code stayed at a 1–4 MB peak heap under heaptrack. ### Repro (`std` only, no libc) ```zig const std = @import("std"); const gpa = std.heap.smp_allocator; const block_len = 400; const ring_len = 1024; var ring: [ring_len]?[]u8 = @splat(null); var head: std.atomic.Value(usize) = .init(0); var tail: std.atomic.Value(usize) = .init(0); fn producer() void { while (true) { const h = head.load(.monotonic); if (h - tail.load(.acquire) == ring_len) { std.atomic.spinLoopHint(); continue; } ring[h % ring_len] = gpa.alloc(u8, block_len) catch @panic("OOM"); head.store(h + 1, .release); } } fn consumer() void { while (true) { const t = tail.load(.monotonic); if (t == head.load(.acquire)) { std.atomic.spinLoopHint(); continue; } gpa.free(ring[t % ring_len].?); ring[t % ring_len] = null; tail.store(t + 1, .release); } } pub fn main() !void { const p = try std.Thread.spawn(.{}, producer, .{}); const c = try std.Thread.spawn(.{}, consumer, .{}); p.join(); c.join(); } ``` At most 1024 × 400 B (~400 KiB) is ever live. ```sh zig build-exe repro.zig -O ReleaseFast ./repro & while sleep 6; do grep VmRSS /proc/$!/status; done ``` The C equivalent (same ring, `malloc`/`free`, two pthreads) built with `zig cc -target aarch64-linux-musl -static -O2 repro.c -lpthread` behaves the same way. ### Results, Zig 0.17.0 aarch64 Fedora 44 VM with 4 vCPUs (Apple M-series host), RSS after 30 s: | | 4 CPUs | `taskset -c 0` | |---|---|---| | `repro.zig` (`smp_allocator`) | 1.0 MB → **609 MB** | 1.5 MB, flat | | `repro.c`, `zig cc` static musl | 0.6 MB → **866 MB** | 0.6 MB, flat | | `repro.c`, glibc `malloc` | 5.1 MB, flat | — | | `repro.zig` + #36294 applied to 0.17.0 | **1.5 MB, flat** | — | | `repro.c` + #36294 applied to 0.17.0 | **0.6 MB, flat** | — | The same `repro.zig` on macOS 27 (aarch64, 14 cores) reaches **4 GB in 40 s**. `SmpAllocator.zig` and `lib/c/malloc.zig` on master (`0.18.0-dev.253+16d31ceed`) are byte-identical to 0.17.0's, so master is affected too. ### Mechanism This matches tokju's instrumentation: - `free` pushes onto the free list of whichever slot the freeing thread currently holds. - Once contention has moved the two threads onto different slots, the producer's slot never sees those blocks. It looks at only one neighbour (`max_alloc_search = 1`) before mapping a fresh slab. - Small-allocation slabs are never unmapped, so the growth is permanent. - With one CPU there is one slot, which is why `taskset -c 0` is flat. ### Impact `zig cc` static musl binaries get this through plain `malloc`, so C/C++ projects (and cargo-zigbuild users, as in BlackLuny's comment) are exposed without using any Zig code. The only workaround I've found short of replacing `malloc` is pinning the process to one CPU. #36294 fixes this repro for me.
Sign in to join this conversation.
No milestone
No assignees
4 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
ziglang/zig#36969
No description provided.