| 1 | # HANDOFF: no page-retention hysteresis in `Allocator.UintptrFree` |
| 2 | |
| 3 | **Status:** resolved 2026-08-06. Retention is now unconditional and bounded to |
| 4 | one empty page per size class — design option 1 below — combined with the |
| 5 | explicit flush of option 3, `(*Allocator).Trim`. The tests keep their full |
| 6 | `Allocs`/`Mmaps`/`Bytes`/`regs` assertions by calling `Trim` first; moving them |
| 7 | after `Close` would have made them vacuous, since `Close` ends with |
| 8 | `*a = Allocator{}`. Two corrections to what follows: the invariant is asserted |
| 9 | at 16 sites, not 8 (`TestFree` and `TestMalloc` were missed, and 6 of the 16 are |
| 10 | benchmarks using `b`), and retention is per size class, since a global pool |
| 11 | would need the per-page capacity that the `memory.go` TODO still tracks. |
| 12 | |
| 13 | Everything below is the original diagnosis, kept for its measurements and |
| 14 | rationale. It describes the code as of `0a6f754`. |
| 15 | |
| 16 | ## The ask |
| 17 | |
| 18 | `UintptrFree` returns a shared page to the OS the moment its last live slot is |
| 19 | freed. There is no hysteresis, so an allocation pattern whose live count for a |
| 20 | size class repeatedly crosses zero pays a full `mmap`/`munmap` round trip per |
| 21 | turnover — in the degenerate case, **one `mmap` + three `munmap`s per single |
| 22 | alloc/free pair**. Decide whether this allocator should retain empty pages, and |
| 23 | under what policy. |
| 24 | |
| 25 | ## Root cause |
| 26 | |
| 27 | `memory.go:222-241`, the tail of `UintptrFree`: |
| 28 | |
| 29 | ```go |
| 30 | (*page)(unsafe.Pointer(pg)).used-- |
| 31 | if (*page)(unsafe.Pointer(pg)).used != 0 { |
| 32 | return nil |
| 33 | } |
| 34 | ... unlink every node of this page from a.lists[log] ... |
| 35 | if a.pages[log] == pg { |
| 36 | a.pages[log] = 0 |
| 37 | } |
| 38 | ... |
| 39 | return a.unmap(pg) // <-- unconditional, immediate |
| 40 | ``` |
| 41 | |
| 42 | `used == 0` means "no live slots", which is treated as "give the page back". |
| 43 | `a.pages[log]` (the current carve target) is cleared too, so the next allocation |
| 44 | of that size class must `newSharedPage` → `mmap` again. |
| 45 | |
| 46 | Two amplifiers make each turnover cost more than one syscall pair: |
| 47 | |
| 48 | - `mmap(size)` (`mmap_unix.go:29`) asks the kernel for `size + pageSize` so it |
| 49 | can align the result, then unmaps the misaligned head and the tail — up to |
| 50 | **two trim `munmap`s per `mmap`**, on top of the one that releases the page. |
| 51 | A 64 KiB page therefore costs a 128 KiB kernel request. Measured totals below |
| 52 | show all three `munmap`s in the synthetic case and an average of two under the |
| 53 | real workload. |
| 54 | - With `pageSizeLog = 16` and `maxSlotSizeLog = pageSizeLog - 2`, every size |
| 55 | class up to **16 KiB** uses shared pages (`memory.go:262`), so this covers the |
| 56 | whole small/medium range, not just tiny allocations. |
| 57 | |
| 58 | ## Why it has not bitten before |
| 59 | |
| 60 | Long-lived consumers (sqlite et al.) keep a working set alive, so `used` rarely |
| 61 | reaches 0 for a hot size class — the page stays mapped and the free list does its |
| 62 | job. The pathology needs a consumer that repeatedly *drains* a size class. |
| 63 | |
| 64 | ## Standalone reproducer |
| 65 | |
| 66 | No other module needed. Allocate one slot and free it, in a loop: |
| 67 | |
| 68 | ```go |
| 69 | a := &memory.Allocator{} |
| 70 | defer a.Close() |
| 71 | for i := 0; i < n; i++ { |
| 72 | p, _ := a.UintptrMalloc(size) |
| 73 | a.UintptrFree(p) |
| 74 | } |
| 75 | ``` |
| 76 | |
| 77 | `n` = 200000, `strace -c -f -e trace=mmap,munmap`, AMD Ryzen 9 3900X, go1.26.5: |
| 78 | |
| 79 | | size | build | `mmap` | `munmap` | syscall time | end state | |
| 80 | |---|---|---|---|---|---| |
| 81 | | 64 B | v1.11.0 | 200,022 | 600,000 | 4.33 s | `Mmaps=0 Bytes=0` | |
| 82 | | 64 B | + retention | 25 | 3 | 0.0002 s | `Mmaps=1 Bytes=65536` | |
| 83 | | 4096 B | v1.11.0 | 200,024 | 600,000 | 4.49 s | `Mmaps=0 Bytes=0` | |
| 84 | | 4096 B | + retention | 24 | 2 | ~0 | `Mmaps=1 Bytes=65536` | |
| 85 | |
| 86 | That is ~21.6 µs of kernel time per alloc/free pair, and it is size-independent |
| 87 | across the shared-page range. |
| 88 | |
| 89 | ## The consumer that hit it |
| 90 | |
| 91 | `modernc.org/libquickjs` v0.13.1, which tracks QuickJS release 2026-06-04 |
| 92 | (`bellard/quickjs` `3d5e064`). That release added a small-block arena allocator: |
| 93 | 31 size classes from 16 to 512 bytes, carved out of `JS_MALLOC_ARENA_SIZE` |
| 94 | = **4096**-byte arenas, and it **frees an arena as soon as its last block is |
| 95 | freed**. QuickJS's free-on-empty policy sits directly on top of this package's |
| 96 | free-on-empty policy and the two resonate: 4096 → `log` 12 → shared page path, |
| 97 | 15 arenas per 64 KiB page, cycling constantly. |
| 98 | |
| 99 | V8 `v8-v7` benchmark scores (throughput, higher is better), medians of 3 |
| 100 | interleaved rounds on a quiet host, go1.26.5, libc v1.74.4: |
| 101 | |
| 102 | | bench | libquickjs v0.12.10<br>(QuickJS 2025-09-13) | libquickjs v0.13.1<br>(QuickJS 2026-06-04) | v0.13.1 + retention | |
| 103 | |---|---|---|---| |
| 104 | | Richards | 175.5 | 243.5 | 243 | |
| 105 | | DeltaBlue | 208.5 | **16** | 265.5 | |
| 106 | | Crypto | 118.5 | 157.5 | 166 | |
| 107 | | RayTrace | 285.5 | **195.5** | 464.5 | |
| 108 | | EarleyBoyer | 465.5 | 618.5 | 622.5 | |
| 109 | | RegExp | 99.5 | 189 | 190 | |
| 110 | | Splay | 911.5 | **340.5** | 1149 | |
| 111 | | NavierStokes | 208.5 | 322 | 323 | |
| 112 | | **Score** | **240** | **187.5** | **348.5** | |
| 113 | |
| 114 | Retention moves *only* the three allocation-bound benchmarks and leaves the other |
| 115 | five within noise (243.5→243, 189→190, 322→323), which is what makes the |
| 116 | attribution airtight. |
| 117 | |
| 118 | Syscall counts and profile for DeltaBlue alone: |
| 119 | |
| 120 | | build | `mmap` | `munmap` | syscall time | |
| 121 | |---|---|---|---| |
| 122 | | v0.12.10 (no arena allocator) | 302 | 532 | 0.0001 s | |
| 123 | | v0.13.1 | **1,345,702** | **2,691,328** | **21.1 s** | |
| 124 | | v0.13.1 + retention | 72 | 62 | 0.0008 s | |
| 125 | |
| 126 | ``` |
| 127 | 10.43s 71.73% internal/runtime/syscall/linux.Syscall6 |
| 128 | 2.22s 15.27% modernc.org/memory.(*Allocator).mmap (62.79% cum) |
| 129 | 0.03s 0.21% golang.org/x/sys/unix.munmap (58.94% cum) |
| 130 | ``` |
| 131 | |
| 132 | 72% of a JavaScript benchmark's runtime in `mmap`/`munmap`. Note the third |
| 133 | column of the score table: with retention the *new* QuickJS overtakes the old one |
| 134 | everywhere, which is the expected outcome — the arena allocator is a win once it |
| 135 | stops thrashing. |
| 136 | |
| 137 | ## The experiment (proof of diagnosis, NOT a shippable patch) |
| 138 | |
| 139 | Retain one empty page per size class by recycling it as the carve target instead |
| 140 | of unmapping it: |
| 141 | |
| 142 | ```diff |
| 143 | if a.pages[log] == pg { |
| 144 | a.pages[log] = 0 |
| 145 | } |
| 146 | + if a.pages[log] == 0 { |
| 147 | + (*page)(unsafe.Pointer(pg)).brk = 0 |
| 148 | + (*page)(unsafe.Pointer(pg)).used = 0 |
| 149 | + a.pages[log] = pg |
| 150 | + return nil |
| 151 | + } |
| 152 | if counters { |
| 153 | a.Bytes -= (*page)(unsafe.Pointer(pg)).size |
| 154 | } |
| 155 | return a.unmap(pg) |
| 156 | ``` |
| 157 | |
| 158 | That is the whole change behind every "+ retention" number above. Its bound is |
| 159 | one 64 KiB page per size class per allocator (≤ 64 classes → ≤ 4 MiB worst case, |
| 160 | in practice only for classes actually used). |
| 161 | |
| 162 | ### Why it cannot be merged as written |
| 163 | |
| 164 | `all_test.go` asserts, after freeing everything, at 8 sites (`:137`, `:203`, |
| 165 | `:285`, `:307`, `:331`, `:401`, `:466`, `:544`): |
| 166 | |
| 167 | ```go |
| 168 | if alloc.Allocs != 0 || alloc.Mmaps != 0 || alloc.Bytes != 0 || len(alloc.regs) != 0 { |
| 169 | ``` |
| 170 | |
| 171 | Retention breaks `Mmaps`, `Bytes` and `len(regs)` by construction — visible in |
| 172 | the reproducer's end-state column, and `go test ./...` fails with the patch |
| 173 | applied. **This is a policy conflict, not a leak**: `Close()` still walks |
| 174 | `a.regs` and unmaps everything, so nothing escapes the allocator's lifetime. But |
| 175 | the invariant "every byte is back with the OS after the last `Free`" is real, |
| 176 | is asserted by those tests, and consumers may rely on it. Changing it is your |
| 177 | call. |
| 178 | |
| 179 | ## Design options |
| 180 | |
| 181 | 1. **Unconditional bounded retention** (the diff above). Simplest, helps every |
| 182 | consumer automatically, no API change. Costs the invariant; the tests would |
| 183 | need to assert after `Close`, or a flush would need exposing. |
| 184 | 2. **Opt-in.** An `Allocator` field or constructor knob, default off, leaving |
| 185 | existing behaviour and tests untouched so `libquickjs`/`libc` can turn it on. |
| 186 | Safest, but each consumer has to know to ask. |
| 187 | 3. **Explicit flush.** Always retain; add `(*Allocator).Trim()` and let callers |
| 188 | decide when to give pages back. |
| 189 | 4. **Bounded hysteresis, documented.** As (1), but with the retention count an |
| 190 | explicit, documented parameter rather than incidentally "one". |
| 191 | |
| 192 | Open questions worth settling at the same time: |
| 193 | |
| 194 | - Per size class (as prototyped) or one global pool of empty pages? The latter |
| 195 | caps total retention regardless of how many classes are hot. |
| 196 | - Is the align-by-overallocating in `mmap` worth revisiting? It doubles the |
| 197 | syscall cost of every page acquisition, so it amplifies exactly this problem. |
| 198 | |
| 199 | ## Provenance |
| 200 | |
| 201 | Found while investigating why `modernc.org/libquickjs` did not show the +42% that |
| 202 | QuickJS 2026-06-04 advertises. Native C on the same host gains +60.8% on v8-v7 |
| 203 | (+43.5% with `DIRECT_DISPATCH 0`, the configuration the ccgo build corresponds |
| 204 | to); the Go build instead *regressed* 21.7%. This allocator interaction was the |
| 205 | sole cause: with retention the Go build gains +45.2%, matching the native +43.5%, |
| 206 | and five of the eight benchmarks had been gaining 32–91% all along. |