1. The promise of fork, and the page table behind it
A preloading Python server makes a promise that sounds arithmetic: import the application once, allocate its heap once, then fork four workers that map the same pages. The sum of four workers is supposed to be one heap plus change. The change is what nobody budgets for, because the kernel does not copy memory at fork – it copies page tables and marks both processes’ pages read-only. The copy happens later, one page at a time, the first time either process writes to a page.
Python writes to pages for reasons the application never asked for. Reading an object increments its reference count; walking a container for the cyclic collector writes the collector’s own words into a header in front of the object. Neither changes a value a programmer would recognise, and both take a page out of the shared set for good. In the measurement below, a child forked from the 105.5 MiB heap paid 1.1 MiB for existing, 87.1 MiB for reading every record once, and 24.8 MiB for one full garbage collection that changed no application data at all.
TL;DR – the four numbers this page turns on
- A child forked from the 105.5 MiB a dense heap grew ended with 87.1 MiB of private memory after reading every record: 86.0 MiB copied, 81.5% of the heap, and the floor every forked child pays.
- The same 58.6 MiB of payload held by 15 objects of 4,096,000 B copied 92.0 KiB over the 0.98 MiB an idle child pays (0.09% of the same heap), because only the pages holding object headers move. The same bytes read from a read-only file mapping stayed at 1.2 MiB.
gc.freeze()cut a full collection from 24.8 MiB to 0.96 MiB and left the read at 87.2 MiB.- Four preloaded gunicorn workers summed 284.6 MiB of RSS but 83.4 MiB of PSS; each held 6.5 MiB after reading 5,000 of 40,000 records per request – 4.9 MiB over a 1.6 MiB idle floor, 3.7 MiB of it the heap’s own pages.
The page is written for the person who has to explain why four workers on a two-gigabyte node ran out of memory at night, and for the person deciding whether --preload is a saving or a trap. Every figure is a measurement taken on one host with ordinary user privileges – no root, no cgroup rewriting, no kernel tuning – because in most incidents that is all the operator has. Three columns carry the argument: RSS counts a shared page once per process, PSS divides it by the processes mapping it, and Private_Dirty counts the pages this process alone has written – the only one that tells a copy from a sharing arrangement.
| Column | This child | What the kernel means by it |
|---|---|---|
| Rss | 116.6 MiB | every mapped page, counted once for this process, shared or not |
| Pss | 100.6 MiB | the same pages divided by the number of processes mapping each one |
| Private_Dirty | 87.1 MiB | pages only this process has written since the fork |
| Still shared | 26.9 MiB | pages it maps with its parent, recovered as twice the gap between PSS and private |
| Minor faults | 22,076 | page faults that needed no disk read: one per copied page |
/proc/self/smaps_rollup. Four columns, four questions about the same heap.2. How this was measured
Every number here comes from a child process forked from a heap and asked to do one thing. The dense heap is 120,000 records of a dictionary with an id, a name, two tags and a 512 B payload – the shape of a row a template renders. Building it grew the process by 105.5 MiB; the parent then reported 113.1 MiB of private memory over 28,951 pages of 4 KiB – the heap’s 27,009 pages plus the interpreter’s own – 52% of it the payload bytes.
The arms differ only in what the child does after the fork, and each ran in 5 fresh children that recorded their own baseline before starting, so no arm pays for the fork itself:
- idle – sleeps, touches nothing: the cost of existing.
- read – reads every record’s payload, writes nothing: reference counts alone.
- collect – one full
gc.collect(): the collector’s pass. - collect after freeze – freeze in the parent, then the same pass.
- write – sets one key in every record: the worst case.
Three further experiments answer what the dense heap cannot. A sparse heap holds the same 58.6 MiB of payload in 15 objects instead of 120,000, which separates object headers from bytes; a file mapping holds the same bytes outside the Python heap; a gunicorn tree runs four sync workers with and without --preload on a 40,000-record heap and reads the whole process tree from /proc.
One denominator serves the whole page: the growth around building the heap, 105.5 MiB for the dense heap. A whole-process reading would charge the interpreter to the heap – the same 40,000-record heap measured 34.6 MiB of growth in the gunicorn probe but 47.9 MiB as a whole process, and the 4.6 MiB between them is gunicorn’s code, not the heap. Every share here divides by a growth figure, so a percentage always answers the same question.
A word about what a child’s baseline can see. The child is a copy of its parent at the instant of the fork, so any measurement taken after the fork includes whatever the measurement itself touches. Every arm therefore records Private_Dirty as its first action and reports the difference, and the idle arm prices that first action: 1.1 MiB with 7 minor faults.
How the fork and the clock were arranged
Each child is a real os.fork() from a process that already holds the heap. The parent waits for the child and closes its end of the pipe, so no probe leaves a process behind; the idle arm’s 1.1 MiB is what remains after that bookkeeping.
The collection arms call gc.collect() directly rather than waiting for a threshold, because the question is what a full pass costs. The host’s thresholds are 700, 10 and 10 – the defaults.
Wall times are the child’s own perf_counter() as medians with a range: the read arm’s five children copied 89,176 to 89,200 KiB and timed 69.9 ms to 402 ms around 74.6 ms. The copied bytes are stable and the clock is not.
The appendix prints the package, the fork test, the gunicorn runbook and the four probes the tables rest on (03_read.py, 08_gunicorn.py, 13_density.py, 15_sizes.py), so a reader can run those arms on their own heap. The other arms of the measurement tree are not reproduced.
3. An idle child costs almost nothing
An idle child is the cheapest thing a forking server can own, and the only arm that isolates the fork. It inherits the 105.5 MiB heap and writes almost none: its Private_Dirty is 1.1 MiB, 1.1% of it, over 7 minor faults. A page-table entry costs nothing to copy; the child pays for its own interpreter state and the stack it touches.
| What is measured | Resident (RSS) | Private (dirty) | Private pages |
|---|---|---|---|
| The parent, after building the heap | 119.8 MiB | 113.1 MiB | 28,951 |
| An idle forked child | 116.7 MiB | 1.1 MiB | 292 |
| The same child after a read | 116.6 MiB | 87.1 MiB | 22,296 |
Private_Dirty over the 4 KiB page.The same child after one pass over its records reports 76.4 times the private memory of the idle one, and the idle child’s PSS of 57.6 MiB against 116.7 MiB of RSS shows why: PSS gives it half of each page it shares with a parent that is still alive, and in production the master shares those pages with all four workers.
4. The read that copies pages
The read arm is the important one, because it looks free: it sums the length of every payload and stores nothing. In a language without reference counting it would copy no pages; in CPython the child ends with 87.1 MiB of private memory in 74.6 ms, 86.0 MiB of it the copy (81.5% of the heap) and the rest the floor an idle child already pays.
from __future__ import annotations
def read_every_record(heap: list[dict]) -> int:
"""Touch every record the way a template or a serializer would: read, never write."""
total = 0
for record in heap:
total += len(record["payload"])
return total
The loop reads a key from a dictionary and calls len() on the value. Each step is a Py_INCREF followed by a Py_DECREF: the dictionary hands out a borrowed reference to the record, the subscript hands out a new reference to the payload, and both are written into the object header before the expression ends. A reference count is a machine word at the start of the allocation, so a read of one object dirties the page that holds it – and every other object that happens to share the page.
The arithmetic closes. 22,077 minor faults times a 4 KiB page is 86.2 MiB of copied pages, and the child’s private memory minus its idle floor is 86.0 MiB: two ways of counting one copy, agreeing within 0.3 MiB. The 0.9 MiB between the fault count and the child’s total is the child’s own bookkeeping, which is why the idle arm is subtracted.
The collector writes through a second, separate word. CPython keeps its bookkeeping in a PyGC_Head immediately before every tracked container: two pointer words, 16 bytes, _gc_next and _gc_prev. _gc_next links the object into its generation list and marks it unreachable during a pass; _gc_prev links backwards and carries the collector’s private reference count while a pass runs. At the start of a collection CPython copies each object’s ob_refcnt into that count and sets the collecting bit; it never writes ob_refcnt itself.
| Action in the child | Private_Dirty | Copied over idle | Share of heap |
|---|---|---|---|
| Read every record | 87.1 MiB | 86.0 MiB | 81.5% |
| One full collection | 24.8 MiB | 23.7 MiB | 22.4% |
| One full collection after freeze | 0.96 MiB | 0.0 MiB | 0.0% |
| Write one key per record | 37.7 MiB | 36.6 MiB | 34.7% |
So a read and a collection dirty pages through two different words in two different structures – ob_refcnt at the start of the object, _gc_prev in the head that ends where the object begins. Both sit on the same 4 KiB page, and the kernel charges for the page, not the word. The head is also why a collection copies less than a read over the same heap: it walks the tracked containers and never touches the bytes of a payload, which is not tracked at all. This host’s collector listed 252,099 tracked objects against 120,000 records.
5. Object density decides the bill
The 81.5% in section 4 is a property of the heap being read, not of reading: a record is a handful of small objects, and their sizes decide what a page holds. sys.getsizeof reports a 184 B dictionary, a 72 B list, a 55 B name, a 28 B id and a 545 B payload object – 884 B for the five objects one record owns.
The heap the records were built into grew by 922 B per record, 4.3% more than that sizeof sum. The 38 B is not a hidden object, and this probe does not divide it: it is the sum of allocation costs getsizeof does not report – the outer list’s 8 B pointer slot per record, a glibc chunk header in front of the 545 B payload, and pymalloc rounding each of the four smaller requests up to its size class. The probe measures the growth and the sizeof sum; the split between those three is inference from how the two allocators work, not a fourth measurement. The two 46 B tag strings are interned literals every record only points at, so they belong to neither sum.
Those sizes divide the record between two allocators. pymalloc serves requests of 512 B or less from its own pools and hands anything larger to the C library, so the 545 B payload – 33 B over the threshold – is a malloc allocation, while the dictionary, the list, the name and the id are packed into pools. A pool is 16 KiB, four 4 KiB pages carved out of a 1.0 MiB arena – 64 pools to the arena on this build – and the interpreter reports that size itself in its allocator summary.
The packing is dense enough to measure: in a 20,000-record heap, one page held 21 of these dictionaries, 21 tag lists and 127 of the small ids, and 99.5% of the pages holding a dictionary held more than one. A reference count written into one dictionary takes the page away from the twenty objects beside it, and a read that wanted each payload’s length pays for every header on the page.
A second probe keeps the record shape and the payload total identical and changes only the object count: 15 records, each carrying a 4,096,000 B payload, the same 58.6 MiB as the dense heap. Reading it copies almost nothing, because each large payload is one allocation whose reference count shares a page with its own first bytes and no other object’s header. The child’s private memory after reading all 15 records is 1.07 MiB against an idle child’s 0.98 MiB: 92.0 KiB of copying (94,208 B, about 23 pages), 0.09% of the same heap, for 58.6 MiB of bytes read. Its 38 minor faults against the idle arm’s 25 say the same thing: reading does not fault what it never writes.
| Heap | Objects | Payload | Private after read | Idle floor | Copied over idle | Share of heap |
|---|---|---|---|---|---|---|
| dense: 120,000 records | 120,000 | 58.6 MiB | 87.1 MiB | 1.1 MiB | 86.0 MiB | 81.5% |
| sparse: 15 records | 15 | 58.6 MiB | 1.07 MiB | 0.98 MiB | 92.0 KiB | 0.09% |
A read does not copy a heap; it copies the pages holding the headers of the objects it touches, and payload pages only when they share a page with a header. In a dense heap of small containers that is most of the heap; in a heap of a few large buffers it is a rounding error. Most application heaps look like the first case – ORM rows, parsed JSON, template contexts – so a cache of large buffers does not need this recipe at all.
6. The collector’s pass, and what freeze removes
A full collection is the arm that surprises people, because nothing in it belongs to the application: the child walks the collector’s bookkeeping, marks what it finds and unmarks it, and collected no unreachable cycle on this heap. The bill is still 24.8 MiB – 23.7 MiB over the idle floor, 22.4% of the heap, 6,134 copied pages, 42.1 ms of wall time.
The same collection in a process that already owns every page it walks is cheaper: 18.8 ms in the parent that built the heap against 42.1 ms in a child forked from it. The gap is the copy: the parent has nothing to fault in, and that is why a staging benchmark that runs the collector in the master understates what workers pay.
Freezing removes the pass from the child entirely. gc.freeze() moves every object the collector tracks into a permanent generation, and the collector does not walk the permanent generation. The call is cheap because it relinks generation lists rather than visiting objects: here it moved 251,724 of 252,099 tracked objects (99.9%) in 15 µs.
| Arm | Private_Dirty (median) | Copied pages | Wall (median) |
|---|---|---|---|
| Collection, shared heap | 24.8 MiB | 6,134 | 42.1 ms |
| Collection, frozen heap | 0.96 MiB | 11 | 18 µs |
| Read, frozen heap | 87.2 MiB | 22,087 | 71 ms |
Table 5 also contains the limit of the fix. After the freeze a collection copies 0.96 MiB – the same as an idle child, nothing beyond the measurement itself – while a read copies 87.2 MiB, 91.0 times the frozen collection. Freezing keeps the collector out of the heap; it does not keep the application out of it.
Read this before you freeze everything: The collector is the smaller half and the easier half. It copies 24.8 MiB of the 87.1 MiB a read leaves private, so freezing buys back 22.4% of the heap and leaves the 81.5% a request costs.
from __future__ import annotations
import dataclasses
import gc
import time
@dataclasses.dataclass(frozen=True)
class FreezeResult:
"""How many objects the collector was told to stop tracking, and how long it took."""
frozen: int
total_frozen: int
elapsed_ms: float
@property
def moved(self) -> int:
return self.frozen
def freeze(collector=gc) -> FreezeResult:
"""Move every object the collector tracks into the permanent generation.
Objects the collector does not track - integers, strings, bytes - are not in its
lists and are not affected; they are still copied by the reference counts a worker's
own code writes. What the freeze removes is the collector's own pass.
The call is incremental: it moves what is tracked at that moment, so a second call
minutes later moves only what was allocated in between, and a hot loop that allocates
containers will keep offering the collector new objects to freeze.
"""
before = collector.get_freeze_count()
started = time.perf_counter()
collector.freeze()
elapsed_ms = (time.perf_counter() - started) * 1000
total = collector.get_freeze_count()
return FreezeResult(frozen=int(total - before), total_frozen=int(total),
elapsed_ms=round(elapsed_ms, 3))
The call returns nothing useful on this build, so the wrapper reads gc.get_freeze_count() before and after and reports the difference. Payloads are bytes and were never tracked, which is why the freeze covers 99.9% of the tracked objects and not every object in the heap.
Within the master, collect the garbage and then freeze what survives: freezing first would move the garbage into the permanent generation too. Around the fork the documentation gives the recipe – gc.disable() early, gc.freeze() right before fork(), gc.enable() in the child – and section 9 measures what each call buys.
7. The first pass is the expensive one
The last measurement of the fork is the one an operator feels: the first pass over the heap after the fork costs more than every pass after it. One child reads every record twice. The first took 71.6 ms and faulted 22,073 pages; the second took 8.1 ms and faulted none, 8.9 times faster because the pages are already private and reading them asks the kernel for nothing.
| Pass | Wall (median) | Range | Minor faults | Private after |
|---|---|---|---|---|
| First pass (copy) | 71.6 ms | 70.9 ms – 84.4 ms | 22,073 | 86.7 MiB |
| Second pass (warm) | 8.1 ms | 7.5 ms – 8.3 ms | 0 | 86.7 MiB |
The copy is not free even when it is fast: 63.5 ms at 2.9 µs per page, which on a warm page cache is a latency spike in the first requests after a deploy and invisible in a load test that ramps up slowly. The number to hold is not the total – it scales with the heap – but the rate: a page costs a few microseconds the first time a worker writes it, and nothing after.
The page arithmetic behind Table 6
Minor faults are pages the kernel mapped without reading from disk: the page was already in memory as part of the parent’s heap, so the fault is a copy, not I/O. The first pass faulted 22,073 pages, and that times 4 KiB is 86.2 MiB, 99.4% of the 86.7 MiB the child ended with. The second pass faulted none, so its 8.1 ms is the read loop itself.
The heap was built as 120,000 records of 512 B payloads, which is 58.6 MiB of payload inside 113.1 MiB of private memory: about 52% of it the bytes themselves. The rest is the dictionaries, names and tag lists whose headers a read writes.
A single run of any arm on a shared host can move by tens of percent; the ordering between arms does not. The five children of the cold pass ranged from 70.9 ms to 84.4 ms and every one faulted the same pages to within one page.
8. Four gunicorn workers, and what RSS hides
The fork arms are a laboratory; a server is not. This experiment runs four gunicorn sync workers with the same kind of heap (40,000 records of 512 B, 5,000 read per request), serves 24 requests to each configuration, and reads the whole process tree from /proc before stopping it. Nine configurations, 5 runs each:
- no_preload – each worker imports the application and builds its own heap. preload – the master builds the heap, the workers fork from it, and each request reads one slice.
- preload_ping / preload_collect – the same tree, first with every request answered as a fixed
okthat never looks at the heap (gunicorn’s request path alone), then with one full collection per worker after its first read. - preload_freeze_collect / preload_recipe –
gc.collect()andgc.freeze()in the master before the fork; then the three calls thegc.freeze()documentation names: disable in the master before the heap exists, collect and freeze before the fork, enable in each worker’spost_fork. - preload_churn / preload_churn_recipe – the same freeze with a quarter-million unreachable cycles allocated between the heap and the fork, first with the collector running (a real import’s automatic collections happen in that window) and then disabled from the start
- idle – the preloaded tree with four workers that have answered nothing: the floor the other rows are read against.
Each response carries the id of the worker that answered and that worker’s own collection count, the probe sends requests until all four have answered, and every worker collects exactly once after its first read. Across the 5 runs the request counts ranged from 3 to 8 per worker and the copied memory did not follow them: a worker that re-reads the same slice re-writes pages it already owns.
| Config | RSS | PSS | Private | Per worker | Over idle | Worker | Master |
|---|---|---|---|---|---|---|---|
| No requests | 281.5 MiB | 64.1 MiB | 11.9 MiB | 1.6 MiB | 0 | 0 | 160 |
| Pings only | 284.4 MiB | 68.7 MiB | 17.4 MiB | 2.8 MiB | 1.2 MiB | 0 | 160 |
| Slice reads | 284.6 MiB | 83.4 MiB | 35.8 MiB | 6.5 MiB | 4.9 MiB | 0 | 160 |
| Collect | 285.4 MiB | 127.3 MiB | 90.9 MiB | 17.7 MiB | 16.1 MiB | 1 | 160 |
| Freeze + collect | 285.9 MiB | 83.6 MiB | 35.8 MiB | 6.5 MiB | 4.9 MiB | 1 | 162 |
| Disable+freeze+enable | 285.9 MiB | 83.8 MiB | 35.9 MiB | 6.5 MiB | 5.0 MiB | 1 | 47 |
| Churn, collector on | 285.8 MiB | 83.4 MiB | 35.6 MiB | 6.5 MiB | 4.9 MiB | 1 | 482 |
| Churn, collector off | 292.2 MiB | 85.3 MiB | 36.0 MiB | 6.5 MiB | 5.0 MiB | 1 | 47 |
| No preload | 252.9 MiB | 199.2 MiB | 189.4 MiB | 44.5 MiB | own heap | 0 | 160 |
Worker is how many gc.collect() calls the worker that answered made: 0 in the arms that only read, 1 in the arms told to collect once after the first read, read back from the X-Collects response header. Master is the collections the setup window actually ran, from the report each run writes; in the No preload row the arbiter never imports the application, so that number is the workers’ own import and setup window (the last worker to import writes the report), not the arbiter’s.RSS cannot answer the question. Without preloading the tree’s RSS is 252.9 MiB and its PSS 199.2 MiB, the closest the two get because almost nothing is shared. With preloading RSS rises to 284.6 MiB, 113% of the no-preload tree, while PSS falls to 83.4 MiB, 42% of it: the shared heap is mapped 5 times, and an alert on RSS sees preloading as a regression on the day it is the fix.
Preloading saves the pages the workers do not write, and only those. PSS fell by 115.8 MiB while each worker still added 4.9 MiB over its idle floor, 3.7 MiB of it a copy of the 34.6 MiB heap (10.7% of it), re-reading the same 5,000 records without copying them again. A workload that reads more per request pays more; one that reads none pays almost nothing.
The collector’s bill in a real tree is the third result. A worker that runs one full collection after its first read adds 11.2 MiB of private memory – 32.4% of the heap – and across the tree that is 43.9 MiB of PSS for a pass that found no garbage. Freezing in the master before the fork brings the same arm within 0.2 MiB of the arm that never collected.
The recipe’s three calls are memory-neutral here, which is what makes them affordable: all three put each worker at 6,664 kB against 6,650 kB for the arm that only collects and freezes – 14.0 KiB apart, inside the 172.0 KiB spread across four workers of one run. What they change is the master’s window: 162 collections, 47 with the disable first.
The churn pair costs what honesty demands be said out loud. Put 250,000 unreachable cycles in that window and the disabled arm carries them to the fork: it sits 6.4 MiB of RSS and 1.9 MiB of PSS above the same arm with the collector running, because the automatic collections freed that garbage and the disable kept it. The worker medians barely move – 6,618 kB against 6,668 kB – while the collections do: 482 against 47, the same 250,780 objects freed by one explicit collect instead of 435 automatic passes. Every worker in those arms answered with its collector enabled and every master forked with it disabled.
Why the freeze belongs before the fork: The order of operations is the whole fix. If a worker collects before it serves, the pages the collector copies are pages the first request would have copied anyway, and the two costs hide inside each other. Freeze before the fork and the collection stops touching the heap; the first request still pays its 4.9 MiB over idle – 3.7 MiB of it the heap’s pages – and nothing can prevent that.
9. Two cheaper moves: recycle the workers, or move the bytes out
Freezing is the cheapest fix because it is one call in the master, but it removes only the collector’s contribution; it does not return the pages a worker has already copied. Two other levers do, and one has a well-documented precedent.
Both come from Instagram’s Django deployment behind uWSGI in pre-fork mode. In January 2017, Dismissing Python Garbage Collection at Instagram reported the symptom: within seconds of the fork only about two thirds of each worker’s memory was still shared, profiling pointed at the collector rather than at application code, and disabling the collection took each worker’s shared memory from 140 MB to 225 MB, cut 8 GB from every host, saved 25% of the fleet’s RAM and gave about 10% more capacity. December 2017 brought the follow-up: the disable did not hold, memory kept climbing, and the fix that became gc.freeze() – the master’s objects moved out of the collector’s reach, upstreamed as CPython pull request 3705 and released in 3.7 – took average memory growth per request down by about 50%.
The three calls are written down, in order, in the documentation for gc.freeze(): gc.disable() early in the parent, gc.freeze() right before fork(), gc.enable() early in the child. Disabling keeps automatic collections out of the window between building the heap and the fork, where a collection can free an object inside a page the workers are about to share, the next allocation can refill that hole, and every child inherits the written page. Freezing moves what the master built into a generation the collector no longer walks. Enabling in each child turns collection back on for the child’s own objects without visiting the parent’s, so a collection there cannot write gc_refs into a shared page.
What the disable is worth depends on what the master allocates in that window, and this workload sits at both ends of that question: it is the best case for the memory bill, because the workers read slices and put almost nothing back into the master’s freed space, and the weakest case for the mechanism, because with almost no holes to refill the experiment can only price the recipe as affordable – it cannot show that gc.disable() suppresses a cost. In the churn rows it cost 1.9 MiB of PSS instead of saving anything, because the garbage stayed in the master. A real import sits between the two: few unreachable cycles and a narrow window.
Recycle the worker before it stops sharing. Gunicorn’s --max-requests restarts a worker after that many requests, and --max-requests-jitter adds a random offset per worker so four do not restart together; both default to zero. The replacement forks from the master and starts shared again at 1.6 MiB of private memory – the idle gunicorn worker, not the 1.1 MiB a bare forked child costs – instead of the 6.5 MiB a working worker holds. The price is the restart itself, so set it from the copy rate: a worker copies its slice on the first request and nothing on the next thousand, so recycling helps a worker whose slice grows over time.
Move the bytes out of the heap. A reference count is written because the interpreter owns the object; bytes in a file mapping belong to the page cache, and reading them through a memoryview touches no reference count. The probe writes the dense heap’s payload total – 61,440,000 B, 120,000 records of 512 B – to a file and maps it read-only. It is a control for the mechanism, not a rerun of the workload: the arms scan raw bytes rather than objects.
from __future__ import annotations
def read_first_bytes(view: memoryview, records: int, stride: int) -> int:
"""Touch one byte per record: every page of the mapping, no Python object per record."""
total = 0
for offset in range(0, records * stride, stride):
total += view[offset]
return total
| Read | Private_Dirty | Minor faults | Wall (median) |
|---|---|---|---|
| Idle child, mapping open | 1.2 MiB | 7 | 6 µs |
| First byte of every record | 1.2 MiB | 947 | 18 ms |
| Every byte of every record | 1.2 MiB | 945 | 315.4 ms |
The private column does not move: an idle child and a child that read the whole mapping report the same memory to within a page. The faults are another story: 947 for a 61,440,000 B file is far fewer than one per page, because Linux maps neighbouring pages on a single fault (fault-around), and a fault here is not a copy – it is a page-cache page appearing in the address space, shared with every process that maps the file and reclaimable under pressure. The heap read paid 22,077 faults and ended with 87.1 MiB of private memory; the mapping paid 947 and ended with 1.2 MiB, 70.3 times less for the same bytes.
The trade is explicit: a mapping adds I/O on a cold cache, its pages can be evicted and faulted again, and the data has to be indexable without Python objects around it. It fits reference data that is read and never modified – dictionaries, model weights, lookup tables, serialized fixtures – and multiprocessing.shared_memory is the anonymous equivalent with the same requirement that the reader copy out rather than mutate in place.
The levers answer different parts of one bill: the freeze removes the collector, recycling returns the pages a worker has copied, and moving the bytes out means a worker never copies them. The budget that decides when to reach for one is a share of the heap – a quarter is 8.6 MiB per worker and 34.6 MiB across four.
10. A watcher that names the worker that stopped sharing
A preloading deployment needs one number in its logs that a memory graph does not give it: how much of each worker’s memory is its own. The package’s watcher reads Private_Dirty for every worker under a master, remembers what each worker had when it first appeared, and reports the difference against the heap the workers were forked from.
from __future__ import annotations
@staticmethod
def line(growth: Growth, heap_kb: int) -> str:
"""One worker as one line: the two numbers a deploy log should carry."""
return (f"worker {growth.pid}: {growth.delta_mib:,.1f} MiB copied of a "
f"{heap_kb / 1024:,.1f} MiB heap ({growth.share_of(heap_kb) * 100:,.1f}%)")
from __future__ import annotations
def over_budget(self, growths: list[Growth], heap_kb: int,
share: float = 0.25) -> list[Growth]:
"""The workers that have copied more than ``share`` of the heap."""
if not 0 < share <= 1:
raise ValueError("share must be inside (0, 1]")
return [growth for growth in growths if growth.share_of(heap_kb) > share]
It returns the workers rather than a boolean, because one worker past the line is a different incident from four past it. Both methods are printed as their file writes them: dedented, with the decorator and the imports they carry.
The watcher was measured beside the workers it watches, because a monitor that costs more than the thing it monitors is a different problem. Four children served 20 requests each while the parent sampled every worker every 20 ms. A sample of four workers took 1.4 ms, and the children’s own work took 211.6 ms with the sampler against 210.3 ms without it: 1.3 ms, 0.6% of the run.
| Measurement | Value | What it means |
|---|---|---|
| Growth per worker | 3.8 MiB | 11.0% of the 34.7 MiB heap, from reading 5,000 of 40,000 records |
| Cost of one sample | 1.4 ms | four /proc reads, one per worker |
| Work, sampled | 211.6 ms | 20 requests per child, 5 repeats |
| Work, unwatched | 210.3 ms | +1.3 ms when sampled |
| Samples per run | 12 | one every 20 ms while the children worked |
The detailed run shows why the interval has to be chosen against the workload: in the first sample, moments after the go signal, one worker was already at 2,560 KiB copied while another was at 0. A watcher that samples once a minute sees the end state and never the event.
11. What this does not measure
Every measurement was taken on one host, as a user, from /proc. That limits what can be claimed, and the limits are part of the result.
- Huge pages were not measurable here. The container does not expose
transparent_hugepage/enabled. Since Linux 5.8 a write fault on an anonymous huge page splits it and copies a 4 KiB page, where older kernels allocated a new 2 MiB page and copied all of it. - No cgroup accounting. This container has no
memory.current, so PSS and the per-process private dirty figure are the only numbers available; a cgroup is charged for private pages and owned page cache, which is close to PSS without being the same number. - One interpreter. CPython 3.12.16 with its default pymalloc and its 8-byte reference count; a free-threaded build, jemalloc or a different object layout changes which write dirties which page, so the mechanism stands and the megabytes do not transfer.
- A synthetic heap, no
MADV_DONTFORK, no manual page sharing, and the fork itself inside the idle arm. 52% of the private memory is payload by weight; a Django heap would move more at a collection and a NumPy heap none. The page-table copy and the child’s startup are in that 1.1 MiB, not separated from it.
Three claims are worth restating in measured form. A freeze removes the collector’s pass and nothing else: the frozen read arm copied 87.2 MiB against the unfrozen 87.1 MiB. A read copies headers, not payloads: the sparse heap copied 92.0 KiB over its idle floor (0.09% of the same heap) for 58.6 MiB of bytes. And a preloaded tree is not free: after the first request each worker had added 4.9 MiB over its 1.6 MiB idle floor, 3.7 MiB of it the heap’s own pages, so the tree sat at 83.4 MiB of PSS rather than at the 34.6 MiB a single shared copy would suggest.
12. Deploy checklist
The order below is the order the numbers support, for a preloading Python server – gunicorn, uWSGI, Celery’s prefork pool – and each step names its measurement.
- Measure the heap, not the worker. Build the application in the master, read
Private_Dirtybefore and after, and write the growth into the deploy log. The trees here started at 34.6 MiB. - Measure what one request copies. Serve one request per worker, read the workers again, and subtract one that has served nothing: here 4.9 MiB per worker over a 1.6 MiB floor, 3.7 MiB (10.7%) of it the heap’s pages and 1.2 MiB the HTTP path.
- Disable, collect, freeze, then fork; enable in each child. That is the documented order, and here it costs no memory: the arm with all three calls sat 14.0 KiB from the one that only collects and freezes, while the master’s window ran 47 collections instead of 162. Watch what the window allocates: garbage left there is what the disable keeps.
- Serve traffic and watch private dirty per worker. A worker past a quarter of the heap (8.6 MiB here) has stopped sharing, and the watcher’s line names it.
- Treat the first request as the bill. It added 4.9 MiB per worker here, 3.7 MiB of it a copy, and the dense measurement priced the mechanism at 63.5 ms across 22,073 pages, 2.9 µs a page. If that is too much, shrink the part of the heap a request touches, or recycle the worker before it grows.
- Move reference data out of the heap. A read-only mapping of the same payload kept 1.2 MiB private against 87.1 MiB for the heap copy; the mapping arms scan raw bytes with no object per record, so read that as the price of the mechanism.
- Only then add workers. A fifth worker on a heap that copies 81.5% per full read buys less than the arithmetic suggests, and the graph that would have told you so is RSS.
The one-line version: Disable collection early in the master, collect and freeze right before the fork, enable it in each child, and put one line per worker in the deploy log with its private dirty share. The freeze is worth 22.4% of the heap on this workload; the log line is worth every argument about whether preloading helped.
Frequently asked questions
The questions below are the ones this measurement changed the answer to.
Why does the title say 86 MiB when each worker copies a few?
Because the title prices one full read of the heap, not the tree. 87.1 MiB is what a child ends with after reading every record of the 105.5 MiB heap, 86.0 MiB of it (81.5% of the heap) the pages the read copied. Each gunicorn worker read 5,000 of 40,000 records and held 6.5 MiB: the first number prices the mechanism, the second the tree.
Does --preload always save memory?
No. It saves the pages the workers never write. Here PSS fell by 115.8 MiB while each worker still dirtied 4.9 MiB over idle, 3.7 MiB of it a copy of the heap, so a heap that requests read in full would save almost nothing.
Why does RSS go up when I add --preload?
Because RSS counts a shared page once per process. With preload the master and all four workers map the same heap, so RSS summed 284.6 MiB against 252.9 MiB without it, while PSS fell from 199.2 MiB to 83.4 MiB. Read PSS for memory, RSS for mapping.
Does gc.freeze() stop copy-on-write?
No. It stops the collector from walking the heap, which was 24.8 MiB of copying here; the reference counts a read writes are untouched, and the frozen read arm copied 87.2 MiB.
Should the freeze run in the master or in the worker?
Before the fork, in the master, with collection off around it: gc.disable() early, gc.freeze() right before the fork, gc.enable() at the start of each child. Done that way it runs once and costs 15 µs; what must not happen is a full collection in a worker while the heap is still shared.
Is disabling the collector on its own simpler?
No. gc.disable() leaves reference cycles to accumulate – the reason Instagram’s memory grew again after their first fix – and the flag is process-wide. In the documented recipe it is the first step rather than the answer: the freeze keeps a child’s collections off the shared heap, and gc.enable() gives the child its collector back for its own objects, which copied 0.96 MiB while still collecting.
How do I tell which worker stopped sharing the heap?
Read the private dirty memory of each worker and compare it with the heap each worker was forked from. In the watcher run each worker copied 3.8 MiB, 11.0% of the heap; the line names the worker and the share.
Why was the first request after the fork slower?
Because it copied the pages it wrote. The first pass took 71.6 ms and faulted 22,073 pages; the second pass took 8.1 ms and faulted none.
Do large objects avoid the copy-on-read bill?
Largely, yes. 15 objects of 4,096,000 B copied 92.0 KiB over the idle floor (0.09% of the same heap) against 86.0 MiB for the same payload in 120,000 records: only the pages holding object headers move. The same payload in a read-only mapping kept 1.2 MiB, as an idle child does.
Does --max-requests help?
It bounds the growth instead of preventing it. A restarted worker forks from the master and starts shared again at 1.6 MiB – the idle gunicorn worker, not the 1.1 MiB a bare forked child costs – instead of the 6.5 MiB a working worker holds; --max-requests-jitter staggers the restarts.
Why did one experiment report 6.5 MiB per worker and another 3.8 MiB?
Because the larger number is a worker’s whole private memory and the smaller one is a copy. An idle preloaded worker holds 1.6 MiB; 24 fixed replies take it to 2.8 MiB, so the request path costs 1.2 MiB; requests that read the slice take it to 6.5 MiB, which leaves 3.7 MiB for the heap read. The watcher forks plain children with no HTTP in the way and measured 3.8 MiB for the same slice, 98.0 KiB (100,352 B) apart.
Appendix: the code this article ran
The package, the test file that forks a real heap, the harness, the two files that run gunicorn and the four probes the numbers rest on are printed whole below, in the order a reader would run them. Nothing is elided and no file is linked from an external repository.
The /proc readers: rollup columns, children, tree, totals mem.py
"""What a process tree costs, read from /proc rather than from ps.
``Rss`` counts a shared page once per process, so four forked workers that share one
heap each report it in full. ``Pss`` divides a shared page by the number of processes
that map it, so the sum of ``Pss`` over the tree is the memory the tree really uses.
``Private_Dirty`` is the column that tells a copy apart: a child that has written a
page of the heap owns it, and from then on that page is paid for twice.
"""
from __future__ import annotations
import dataclasses
import pathlib
FIELDS = {
"Rss": "rss_kb",
"Pss": "pss_kb",
"Shared_Clean": "shared_clean_kb",
"Shared_Dirty": "shared_dirty_kb",
"Private_Clean": "private_clean_kb",
"Private_Dirty": "private_dirty_kb",
"Anonymous": "anonymous_kb",
"Swap": "swap_kb",
"AnonHugePages": "anon_huge_kb",
}
@dataclasses.dataclass(frozen=True)
class Memory:
"""One process's memory, in kb, in the four columns that matter for copy-on-write."""
pid: int
rss_kb: int
pss_kb: int
shared_clean_kb: int
shared_dirty_kb: int
private_clean_kb: int
private_dirty_kb: int
anonymous_kb: int
swap_kb: int
anon_huge_kb: int
@property
def private_kb(self) -> int:
"""Pages only this process can read: clean ones it has not written, dirty ones it has."""
return self.private_clean_kb + self.private_dirty_kb
@property
def shared_kb(self) -> int:
"""Pages it maps together with at least one other process."""
return self.shared_clean_kb + self.shared_dirty_kb
def growth_kb(self, baseline: "Memory") -> int:
"""How much private memory appeared since ``baseline``, never negative."""
return max(0, self.private_kb - baseline.private_kb)
@dataclasses.dataclass(frozen=True)
class Totals:
"""A process tree summed the two ways: once per process, and once per page."""
processes: int
rss_kb: int
pss_kb: int
private_kb: int
shared_kb: int
@property
def rss_over_pss(self) -> float:
"""How many times the naive sum overstates the tree: 1.0 means nothing is shared."""
return self.rss_kb / self.pss_kb if self.pss_kb else 0.0
def parse_rollup(text: str, pid: int = 0) -> Memory:
"""Turn one /proc/<pid>/smaps_rollup into a Memory, ignoring fields not listed above."""
found: dict[str, int] = {}
for line in text.splitlines():
key, _, rest = line.partition(":")
column = FIELDS.get(key.strip())
rest = rest.strip()
if column is None or not rest.endswith("kB"):
continue
found[column] = int(rest.split()[0])
return Memory(pid=pid, **{name: found.get(name, 0) for name in FIELDS.values()})
def read(pid: int, root: pathlib.Path = pathlib.Path("/proc")) -> Memory:
"""Read one process's rollup. A process that has exited raises FileNotFoundError."""
path = root / str(pid) / "smaps_rollup"
return parse_rollup(path.read_text(encoding="ascii"), pid=pid)
def children(pid: int, root: pathlib.Path = pathlib.Path("/proc")) -> list[int]:
"""The live children of a process, as the kernel lists them per thread.
A single-threaded parent lists them once; a threaded parent lists each child under
the thread that forked it, so the answer is de-duplicated.
"""
parent = root / str(pid) / "task"
if not parent.is_dir():
return []
seen: set[int] = set()
for thread in parent.iterdir():
listing = thread / "children"
if not listing.exists():
continue
for piece in listing.read_text(encoding="ascii").split():
seen.add(int(piece))
return sorted(seen)
def tree(pid: int, root: pathlib.Path = pathlib.Path("/proc")) -> list[Memory]:
"""The process and every descendant that is still alive, parents first."""
out: list[Memory] = []
queue = [pid]
while queue:
current = queue.pop(0)
try:
out.append(read(current, root))
except (FileNotFoundError, ProcessLookupError):
continue
queue.extend(children(current, root))
return out
def totals(memories: list[Memory]) -> Totals:
"""Sum a tree both ways, so the page that is shared is not counted four times."""
return Totals(
processes=len(memories),
rss_kb=sum(memory.rss_kb for memory in memories),
pss_kb=sum(memory.pss_kb for memory in memories),
private_kb=sum(memory.private_kb for memory in memories),
shared_kb=sum(memory.shared_kb for memory in memories),
)
The freeze and the alarm threshold prefork.py
"""The two things a preloading server can do to its shared heap after the fork.
``freeze`` answers the collector: it walks every container it tracks, and that walk writes
the collector's own words into each object's ``PyGC_Head``, which copies the page. Moving
the survivors into the permanent generation before the fork keeps the collector out of
them afterwards.
``threshold_kb`` answers the alarm: a worker whose private growth passes a quarter of the
heap has stopped sharing it. Both are here because both are read against the same heap.
"""
from __future__ import annotations
import dataclasses
import gc
import os
import pathlib
import time
from . import mem
@dataclasses.dataclass(frozen=True)
class FreezeResult:
"""How many objects the collector was told to stop tracking, and how long it took."""
frozen: int
total_frozen: int
elapsed_ms: float
@property
def moved(self) -> int:
return self.frozen
def freeze(collector=gc) -> FreezeResult:
"""Move every object the collector tracks into the permanent generation.
Objects the collector does not track - integers, strings, bytes - are not in its
lists and are not affected; they are still copied by the reference counts a worker's
own code writes. What the freeze removes is the collector's own pass.
The call is incremental: it moves what is tracked at that moment, so a second call
minutes later moves only what was allocated in between, and a hot loop that allocates
containers will keep offering the collector new objects to freeze.
"""
before = collector.get_freeze_count()
started = time.perf_counter()
collector.freeze()
elapsed_ms = (time.perf_counter() - started) * 1000
total = collector.get_freeze_count()
return FreezeResult(frozen=int(total - before), total_frozen=int(total),
elapsed_ms=round(elapsed_ms, 3))
def unfreeze(collector=gc) -> int:
"""Return frozen objects to the oldest generation; returns how many came back."""
before = collector.get_freeze_count()
collector.unfreeze()
return int(before - collector.get_freeze_count())
@dataclasses.dataclass(frozen=True)
class Mark:
"""A child's private memory at the moment it was forked."""
pid: int
private_kb: int
@classmethod
def take(cls, root: pathlib.Path = pathlib.Path("/proc")) -> "Mark":
"""Record the child's own baseline. Call this in the child, before it serves."""
current = mem.read(os.getpid(), root)
return cls(pid=current.pid, private_kb=current.private_kb)
def threshold_kb(heap_kb: int, share: float = 0.25) -> int:
"""The private growth at which a worker is paying for a quarter of the heap again.
A worker that has copied more than this share has stopped sharing: the alarm is worth
one page of a log line, and the fix is either a smaller heap or fewer workers.
"""
if not 0 < share <= 1:
raise ValueError("share must be inside (0, 1]")
return int(heap_kb * share)
The watcher: per-worker growth against the fork baseline watch.py
"""A sampler that says whether a worker still shares its heap.
The question a preloading server has to answer at runtime is not "how much memory does
this worker use" - it is "how much of that memory is its own". This module answers it by
reading ``Private_Dirty`` per worker and comparing it with the heap the workers were
forked from: a worker near zero copies nothing, a worker near the heap size has stopped
sharing it and the saving preloading promised is gone.
"""
from __future__ import annotations
import dataclasses
import pathlib
from . import mem
@dataclasses.dataclass(frozen=True)
class Growth:
"""One worker's private memory now, against the same worker's baseline at fork."""
pid: int
baseline_kb: int
private_kb: int
@property
def delta_kb(self) -> int:
return max(0, self.private_kb - self.baseline_kb)
def share_of(self, heap_kb: int) -> float:
"""What portion of the shared heap this worker has copied for itself."""
if heap_kb <= 0:
raise ValueError("heap_kb must be positive")
return self.delta_kb / heap_kb
@property
def delta_mib(self) -> float:
return self.delta_kb / 1024
class Watcher:
"""Reads every worker of one process tree, remembering each worker's baseline.
A worker is seen for the first time when it appears, and its baseline is the private
memory it has at that moment. That is the closest a watcher can get to the fork
itself: the first sample of a worker is taken before it has served a request, and the
growth from then on is what the worker copied.
"""
def __init__(self, root: pathlib.Path = pathlib.Path("/proc")) -> None:
self.root = root
self.baselines: dict[int, int] = {}
def register(self, pid: int) -> Growth:
"""Take (or retake) one process's baseline and return it as a zero growth."""
current = mem.read(pid, self.root)
self.baselines[pid] = current.private_kb
return Growth(pid=pid, baseline_kb=current.private_kb, private_kb=current.private_kb)
def observe(self, pid: int) -> Growth:
"""One worker's private growth since the baseline this watcher recorded."""
if pid not in self.baselines:
return self.register(pid)
current = mem.read(pid, self.root)
return Growth(pid=pid, baseline_kb=self.baselines[pid], private_kb=current.private_kb)
def sample(self, master: int) -> list[Growth]:
"""Every worker below ``master`` that is still alive, each against its own baseline.
A worker can exit between the moment the kernel lists it and the moment its rollup
is read - a restart, a crash, a deploy. That worker is not a memory finding, so it
is skipped rather than turned into an exception in a monitoring loop.
"""
seen: list[Growth] = []
for pid in mem.children(master, self.root):
try:
seen.append(self.observe(pid))
except (FileNotFoundError, ProcessLookupError):
continue
return seen
def over_budget(self, growths: list[Growth], heap_kb: int,
share: float = 0.25) -> list[Growth]:
"""The workers that have copied more than ``share`` of the heap."""
if not 0 < share <= 1:
raise ValueError("share must be inside (0, 1]")
return [growth for growth in growths if growth.share_of(heap_kb) > share]
@staticmethod
def line(growth: Growth, heap_kb: int) -> str:
"""One worker as one line: the two numbers a deploy log should carry."""
return (f"worker {growth.pid}: {growth.delta_mib:,.1f} MiB copied of a "
f"{heap_kb / 1024:,.1f} MiB heap ({growth.share_of(heap_kb) * 100:,.1f}%)")
The package’s public names __init__.py
"""cowguard: know what a forked worker really costs.
The three modules answer the three questions a preloading server asks:
mem - what does this process tree cost, counted per page rather than per process?
prefork - what does the collector do to the shared heap after fork, and when has a
worker stopped sharing it?
watch - which worker has stopped sharing, and by how much?
"""
from __future__ import annotations
from .mem import Memory, Totals, children, parse_rollup, read, totals, tree
from .prefork import FreezeResult, Mark, freeze, threshold_kb, unfreeze
from .watch import Growth, Watcher
__all__ = [
"FreezeResult", "Growth", "Mark", "Memory", "Totals", "Watcher", "children", "freeze",
"parse_rollup", "read", "threshold_kb", "totals", "tree", "unfreeze",
]
The claims, on real forks test_fork.py
"""The claims, measured on real forks: a read copies, a frozen heap keeps the collector out.
These tests assert direction and ordering, not the article's exact megabytes: this machine
runs them while other processes compete for memory, so a threshold here is a proof of the
mechanism. The numbers the article quotes come from the probes.
"""
from __future__ import annotations
import gc
import os
from cowguard import Mark, freeze, read, unfreeze
def _heap(records: int = 20_000) -> list[dict]:
return [{"id": index, "payload": b"x" * 256} for index in range(records)]
def _in_child(action) -> int:
"""Fork, run ``action`` in the child, and return the private memory it added, in kB."""
read_fd, write_fd = os.pipe()
pid = os.fork()
if pid == 0: # pragma: no cover - the child never returns
os.close(read_fd)
try:
mark = Mark.take()
action()
after = read(os.getpid())
os.write(write_fd, f"{after.private_kb - mark.private_kb}".encode())
finally:
os.close(write_fd)
os._exit(0)
os.close(write_fd)
data = os.read(read_fd, 32)
os.close(read_fd)
os.waitpid(pid, 0)
return int(data)
def _touch_every_record(heap: list[dict]) -> int:
total = 0
for record in heap:
total += len(record["payload"])
return total
def test_a_child_that_does_nothing_copies_almost_nothing():
assert _in_child(lambda: None) < 1024
def test_a_child_that_reads_every_record_copies_pages():
heap = _heap()
assert _in_child(lambda: _touch_every_record(heap)) > 1024
def test_a_frozen_heap_keeps_the_collector_from_copying_it():
heap = _heap()
assert heap
hot = _in_child(gc.collect)
gc.collect()
freeze()
try:
cold = _in_child(gc.collect)
finally:
unfreeze()
assert cold < hot // 2
def test_the_child_mark_names_the_child_pid():
read_fd, write_fd = os.pipe()
pid = os.fork()
if pid == 0: # pragma: no cover - the child never returns
os.close(read_fd)
try:
os.write(write_fd, str(Mark.take().pid).encode())
finally:
os.close(write_fd)
os._exit(0)
os.close(write_fd)
reported = int(os.read(read_fd, 32))
os.close(read_fd)
os.waitpid(pid, 0)
assert reported == pid
assert reported != os.getpid()
def test_a_frozen_heap_is_still_copied_by_a_read():
"""Freezing keeps the collector out; it does not stop the reference counts a read writes."""
heap = _heap()
gc.collect()
freeze()
try:
cold_gc = _in_child(gc.collect)
read_growth = _in_child(lambda: _touch_every_record(heap))
finally:
unfreeze()
assert cold_gc < 256
assert read_growth > 1024
The shared heap, the fork wrapper and the summaries harness.py
"""Shared measurements for the fork-memory probes.
Every probe builds the same heap, forks children from it, and asks the kernel what each
process actually costs. The kernel answers in four different columns and the difference
between them is the whole article:
Rss - pages mapped into the process, shared or not, counted once per process;
Pss - the same pages divided by the number of processes that map them;
Shared_Clean - pages mapped by more than one process and not written since;
Private_Dirty - pages that belong to this process alone and hold data written by it.
A forked child that touched nothing has almost no Private_Dirty. The same child after it
reads its objects has a lot, because reading a Python object writes its reference count.
"""
from __future__ import annotations
import gc
import json
import os
import pathlib
import statistics
import sys
import time
HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
# The heap every probe forks from: plain Python containers and one payload per record.
# Containers are tracked by the collector; bytes are not, which is why the collector's
# pass and a read of the same heap copy different numbers of pages.
RECORDS = 120_000
PAYLOAD = 512
def build_heap(records: int = RECORDS, payload: int = PAYLOAD) -> list[dict]:
"""The same heap in every probe: 120,000 records of dicts, strings and bytes."""
heap: list[dict] = []
for index in range(records):
heap.append({
"id": index,
"name": f"record-{index:07d}",
"tags": ["alpha", "beta"],
"payload": b"x" * payload,
})
return heap
def build_measured_heap(records: int = RECORDS, payload: int = PAYLOAD) -> tuple[list[dict], dict]:
"""Build the heap and report what the heap cost, not what the process costs.
``Private_Dirty`` of a whole process also counts the interpreter and every module the
probe imported, so two probes that build the same heap in differently loaded processes
report two different heap sizes. The difference around ``build_heap`` is the heap.
"""
before = read_smaps()
heap = build_heap(records, payload)
after = read_smaps()
return heap, {
"baseline_private_kb": before.get("Private_Dirty", 0),
"private_kb": after.get("Private_Dirty", 0),
"growth_kb": after.get("Private_Dirty", 0) - before.get("Private_Dirty", 0),
"rss_growth_kb": after.get("Rss", 0) - before.get("Rss", 0),
}
def read_smaps(pid: int | str = "self") -> dict[str, int]:
"""One process's /proc/<pid>/smaps_rollup as a dict of kB values."""
values: dict[str, int] = {}
with open(f"/proc/{pid}/smaps_rollup", encoding="ascii") as handle:
for line in handle:
key, _, rest = line.partition(":")
rest = rest.strip()
if rest.endswith("kB"):
values[key.strip()] = int(rest.split()[0])
return values
def private_kb(pid: int | str = "self") -> int:
"""Private_Dirty: the pages this process wrote and no other process can see."""
return read_smaps(pid).get("Private_Dirty", 0)
def summarize(samples: list[float]) -> dict[str, float]:
"""Median, minimum, maximum and count of a set of repeated runs."""
return {
"median": round(statistics.median(samples), 3),
"min": round(min(samples), 3),
"max": round(max(samples), 3),
"count": len(samples),
}
def page_size() -> int:
return os.sysconf("SC_PAGE_SIZE")
def malloc_stats() -> str:
"""The interpreter's own pymalloc summary, captured from the descriptor it writes to.
``sys._debugmallocstats()`` writes to file descriptor 2 rather than to ``sys.stderr``,
so rebinding the stream object captures nothing: the descriptor is what has to move.
"""
import tempfile
with tempfile.TemporaryFile(mode="w+") as capture:
saved = os.dup(2)
try:
os.dup2(capture.fileno(), 2)
sys._debugmallocstats()
finally:
os.dup2(saved, 2)
os.close(saved)
capture.seek(0)
return capture.read()
def run_child(action, repeat: int = 1) -> dict:
"""Fork once, run ``action`` in the child, and return what the child measured.
The child records its own baseline immediately after fork, before the action, so a
measurement never includes the fork itself. The parent waits, so no probe leaves a
process behind.
"""
read_fd, write_fd = os.pipe()
pid = os.fork()
if pid == 0: # pragma: no cover - the child never returns
os.close(read_fd)
try:
baseline = read_smaps("self")
before_faults = resource_minflt()
started = time.perf_counter()
for _ in range(repeat):
action()
elapsed_ms = (time.perf_counter() - started) * 1000
after = read_smaps("self")
record = {
"baseline_private_kb": baseline.get("Private_Dirty", 0),
"baseline_rss_kb": baseline.get("Rss", 0),
"private_kb": after.get("Private_Dirty", 0),
"rss_kb": after.get("Rss", 0),
"pss_kb": after.get("Pss", 0),
"shared_clean_kb": after.get("Shared_Clean", 0),
"minor_faults": resource_minflt() - before_faults,
"elapsed_ms": round(elapsed_ms, 3),
}
os.write(write_fd, json.dumps(record).encode())
finally:
os.close(write_fd)
os._exit(0)
os.close(write_fd)
chunks = []
while True:
chunk = os.read(read_fd, 65536)
if not chunk:
break
chunks.append(chunk)
os.close(read_fd)
os.waitpid(pid, 0)
return json.loads(b"".join(chunks).decode())
def resource_minflt() -> int:
"""Minor page faults this process has taken, from getrusage."""
import resource
return resource.getrusage(resource.RUSAGE_SELF).ru_minflt
def repeat_arm(action, repeats: int = 5) -> dict:
"""Run one arm ``repeats`` times in fresh children and summarize the columns."""
runs = [run_child(action) for _ in range(repeats)]
columns = ("private_kb", "pss_kb", "rss_kb", "minor_faults", "elapsed_ms")
return {
"runs": runs,
**{f"{column}_{'median' if column != 'minor_faults' else 'median'}":
summarize([run[column] for run in runs])["median"] for column in columns},
"private_kb_min": min(run["private_kb"] for run in runs),
"private_kb_max": max(run["private_kb"] for run in runs),
"minor_faults_min": min(run["minor_faults"] for run in runs),
"minor_faults_max": max(run["minor_faults"] for run in runs),
}
def write_result(name: str, payload: dict) -> pathlib.Path:
"""Store one probe's record so values.py can read it back as a token."""
RESULTS.mkdir(exist_ok=True)
path = RESULTS / name
path.write_text(json.dumps(payload, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"wrote {path}", flush=True)
return path
def host_facts() -> dict:
"""The constants this host runs with, read rather than assumed."""
facts = {
"python": sys.version.split()[0],
"kernel": os.uname().release,
"page_size": page_size(),
"mem_total_kb": 0,
"gc_thresholds": list(gc.get_threshold()),
"gc_freeze": hasattr(gc, "freeze"),
"heap_records": RECORDS,
"payload_bytes": PAYLOAD,
}
with open("/proc/meminfo", encoding="ascii") as handle:
for line in handle:
if line.startswith("MemTotal:"):
facts["mem_total_kb"] = int(line.split()[1])
return facts
The WSGI application, the heap and the setup the recipe asks for preload_app.py
"""The WSGI application probe 08 serves, and the setup the recipe asks for in the master.
Gunicorn imports this module in the master when ``--preload`` is given, and in each worker
when it is not, so the heap exists once and is shared or exists four times and is not.
A request reads one slice of the heap - the part a page render or a query would touch -
and, when ``COWGUARD_COLLECT=1``, each worker runs one full collection after its first
read. That is the collection an application's own warm-up or periodic job performs, and
doing it once per worker is what makes the arm comparable across workers: whichever worker
answers first collects exactly once, and so does every other one.
``COWGUARD_RECIPE`` selects what the master does around the fork, and the four settings
are the ones the ``gc.freeze()`` documentation names:
plain - build the heap, collect, freeze; the collector was never turned off.
disable - ``gc.disable()`` before the heap exists, then collect and freeze, so
the child can start with collection off and enable it when it is ready
(that last step is ``gunicorn_conf.py``'s post_fork hook).
churn - build the heap and then a quarter-million unreachable cycles, with the
collector running, so the automatic collections that a real import
performs actually happen inside the window between heap and fork.
churn_disable - the same garbage with ``gc.disable()`` first, so the only collection in
that window is the explicit one before the freeze.
The setup writes one report per run - how many collections each generation ran in the
master's window, how long the window took, how much of the heap's memory was in free
blocks when it ended - so the probe prices the master's side of the recipe and not only
the child's. ``X-Collects`` reports how often the worker that answered has collected and
``X-Gc`` whether the collector is enabled in it, so the probe can prove the child did what
the arm asked instead of inferring it.
"""
from __future__ import annotations
import gc
import json
import os
import pathlib
import time
from urllib.parse import parse_qs
import harness
RECORDS = int(os.environ.get("COWGUARD_RECORDS", "40000"))
SLICE_RECORDS = int(os.environ.get("COWGUARD_SLICE", "5000"))
CHURN_OBJECTS = int(os.environ.get("COWGUARD_CHURN", "0"))
COLLECT = os.environ.get("COWGUARD_COLLECT") == "1"
RECIPE = os.environ.get("COWGUARD_RECIPE", "plain")
REPORT = os.environ.get("COWGUARD_SETUP_REPORT", "")
COLLECTS = 0
_started = time.perf_counter()
# Early in the parent, before the heap exists: the first of the three calls.
if RECIPE.startswith("disable") or RECIPE == "churn_disable":
gc.disable()
HEAP = harness.build_heap(RECORDS, harness.PAYLOAD)
def churn(count: int) -> None:
"""Allocate ``count`` unreachable cycles: memory only the collector can reclaim.
A list that refers to itself is not freed when the name is rebound, because its
reference count never reaches zero. Dropping the last name therefore leaves garbage,
and the garbage is what an automatic collection in the master's window frees - the
freed slots are the "holes" the ``gc.freeze()`` documentation asks a parent to stop
creating.
"""
for _ in range(count):
cycle: list = []
cycle.append(cycle)
def free_blocks() -> dict:
"""What pymalloc says about its own free space, read from the runtime's debug summary."""
text = harness.malloc_stats()
report = {}
for line in text.splitlines():
if "arenas allocated current" in line:
report["arenas"] = int(line.split("=")[-1])
elif "bytes in allocated blocks" in line:
report["allocated_bytes"] = int(line.split("=")[-1].replace(",", ""))
elif "bytes in available blocks" in line:
report["available_bytes"] = int(line.split("=")[-1].replace(",", ""))
return report
def setup_report() -> None:
"""Write the master's account of its own window: collections, time, free space."""
if not REPORT:
return
stats = gc.get_stats()
pathlib.Path(REPORT).write_text(json.dumps({
"recipe": RECIPE,
"collections": [generation["collections"] for generation in stats],
"collected": [generation["collected"] for generation in stats],
"heap_records": len(HEAP),
"churn_objects": CHURN_OBJECTS if RECIPE.startswith("churn") else 0,
"gc_enabled_at_fork": gc.isenabled(),
"setup_ms": round((time.perf_counter() - _started) * 1000, 3),
"malloc": free_blocks(),
}), encoding="utf-8")
if RECIPE.startswith("churn"):
churn(CHURN_OBJECTS)
if os.environ.get("COWGUARD_FREEZE_AT_IMPORT") == "1":
import cowguard
gc.collect()
cowguard.freeze()
setup_report()
def app(environ, start_response):
"""Serve a ping, a read of one slice, or a collection; report which worker answered."""
global COLLECTS
query = parse_qs(environ.get("QUERY_STRING", ""))
if query.get("ping"):
body = b"ok\n"
elif query.get("collect"):
gc.collect()
COLLECTS += 1
body = f"collected {len(HEAP)}\n".encode()
else:
total = 0
for record in HEAP[:SLICE_RECORDS]:
total += len(record["payload"])
if COLLECT and COLLECTS == 0:
gc.collect()
COLLECTS += 1
body = f"{total}\n".encode()
return _reply(start_response, body)
def _reply(start_response, body: bytes):
start_response("200 OK", [("Content-Type", "text/plain"),
("Content-Length", str(len(body))),
("X-Worker", str(os.getpid())),
("X-Collects", str(COLLECTS)),
("X-Gc", str(int(gc.isenabled())))])
return [body]
The post_fork hook that enables the collector in a worker gunicorn_conf.py
"""The post-fork hook that turns the collector back on in a worker.
The recipe in the ``gc.freeze()`` documentation has three calls: ``gc.disable()`` early in
the parent, ``gc.freeze()`` right before the fork, and ``gc.enable()`` early in the child.
Gunicorn forks in its arbiter and the worker's first code is this hook, so this is where
the third call belongs. The first two live in ``preload_app.py``; the flag is read from
the environment so that the same file serves the arms that never disable anything.
"""
from __future__ import annotations
import gc
import os
ENABLE_IN_CHILD = os.environ.get("COWGUARD_ENABLE_IN_CHILD") == "1"
def post_fork(server, worker):
"""Called in the worker right after the fork, before it accepts a connection."""
if ENABLE_IN_CHILD:
gc.enable()
The read that copies 03_read.py
"""Probe 03 - what reading every record costs a forked child.
The action is deliberately read-only: it looks at each record and adds up the length of
its payload. No application data is changed. What changes is the reference count of every
object the loop touches, and that write is enough to copy the page under it.
"""
from __future__ import annotations
import harness
def read_every_record(heap: list[dict]) -> int:
"""Touch every record the way a template or a serializer would: read, never write."""
total = 0
for record in heap:
total += len(record["payload"])
return total
def main() -> None:
heap = harness.build_heap()
heap_kb = harness.read_smaps()["Private_Dirty"]
arm = harness.repeat_arm(lambda: read_every_record(heap), repeats=5)
harness.write_result("03_read.json", {
"conditions": {
"records": harness.RECORDS,
"payload_bytes": harness.PAYLOAD,
"repeats": 5,
"heap_kb": heap_kb,
},
"arms": {"read": arm},
"checks": {"payload_total": read_every_record(heap)},
})
if __name__ == "__main__":
main()
Four gunicorn workers, nine configurations, and the recipe 08_gunicorn.py
"""Probe 08 - four gunicorn workers, with and without a preloaded heap.
Every working arm serves the same twenty-four requests, each reading the same slice of the
heap, and every worker that answers performs exactly one collection after its first read
when the arm collects at all. The response names the worker that answered, so the probe
keeps issuing requests until all four workers have served at least one, and records each
worker's own request and collection count. Nothing is inferred from the master's log.
The heap is measured as the growth around ``build_heap``: ``Private_Dirty`` of the whole
probe process includes the interpreter and every imported module, and a heap measured from
it would depend on what the probe happened to import.
Three arms exist only to price what the working arm subtracts. The no-request arm is the
floor: the same preloaded tree with four workers that have answered nothing, waited for by
listing the master's children rather than by sending it a ping. The ping arm serves the
same twenty-four requests through the same workers but touches no heap, so what it costs
is gunicorn's own request handling and what the working arm adds to it is the heap read.
The last three arms are the recipe itself. ``preload_recipe`` runs ``gc.disable()`` in the
master before the heap exists, collects and freezes before the fork, and enables the
collector in the child through the config file's ``post_fork`` hook - the three calls the
``gc.freeze()`` documentation names, in the order it names them, with the same read and the
same single collection as the arm it is compared with. The two ``churn`` arms put
unreachable garbage in the master's window between heap and fork, one with the collector
running and one with it disabled, so the difference the first call makes is measured
rather than assumed.
"""
from __future__ import annotations
import json
import os
import signal
import subprocess
import sys
import time
import urllib.request
import harness
from cowguard import freeze as freeze_heap
from cowguard import mem, unfreeze
HERE = harness.HERE
WORKERS = 4
REQUESTS = 24
REPEATS = 5
HEAP_RECORDS = 40_000
SLICE_RECORDS = 5_000
CHURN_OBJECTS = 250_000
# How long the idle arm waits after the fourth worker appears, so that a worker still
# starting up is not measured as a worker already at ``accept``. Every worker has reached
# its accept loop well inside this window; the extra time costs no request either way.
SETTLE_S = 0.5
REPORTS = HERE / "scratch"
ARMS = (
{"name": "no_preload", "preload": False},
{"name": "preload", "preload": True},
{"name": "preload_ping", "preload": True, "query": "?ping=1"},
{"name": "preload_collect", "preload": True, "collect": True},
{"name": "preload_freeze_collect", "preload": True, "collect": True, "freeze": True},
{"name": "preload_recipe", "preload": True, "collect": True, "freeze": True,
"recipe": "disable", "enable_child": True},
{"name": "preload_churn", "preload": True, "collect": True, "freeze": True,
"recipe": "churn"},
{"name": "preload_churn_recipe", "preload": True, "collect": True, "freeze": True,
"recipe": "churn_disable", "enable_child": True},
)
def start(arm: dict, port: int, report: str) -> subprocess.Popen:
"""Start gunicorn with four sync workers and the environment the hooks read."""
command = [sys.executable, "-m", "gunicorn", "-b", f"127.0.0.1:{port}",
"-w", str(WORKERS), "--log-level", "error",
"-c", str(HERE / "gunicorn_conf.py"), "preload_app:app"]
if arm.get("preload"):
command.insert(-1, "--preload")
recipe = arm.get("recipe", "plain")
environment = dict(os.environ,
PYTHONPATH=f"{HERE.parent / 'module'}:{HERE}",
COWGUARD_RECORDS=str(HEAP_RECORDS),
COWGUARD_SLICE=str(SLICE_RECORDS),
COWGUARD_CHURN=str(CHURN_OBJECTS),
COWGUARD_RECIPE=recipe,
COWGUARD_FREEZE_AT_IMPORT="1" if arm.get("freeze") else "0",
COWGUARD_COLLECT="1" if arm.get("collect") else "0",
COWGUARD_ENABLE_IN_CHILD="1" if arm.get("enable_child") else "0",
COWGUARD_SETUP_REPORT=report)
return subprocess.Popen(command, cwd=HERE, env=environment,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def wait_ready(process: subprocess.Popen, port: int, workers: int) -> None:
"""Wait until the master has all its workers and answers a request that touches nothing."""
deadline = time.time() + 30
while time.time() < deadline:
if len(mem.children(process.pid)) >= workers and process.poll() is None:
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/?ping=1", timeout=2):
return
except OSError:
pass
if process.poll() is not None:
raise RuntimeError(f"gunicorn exited with {process.returncode}")
time.sleep(0.1)
raise RuntimeError("gunicorn did not become ready")
def wait_workers(process: subprocess.Popen, workers: int) -> None:
"""Wait until the master has all its workers, without sending the tree a request."""
deadline = time.time() + 30
while time.time() < deadline:
if len(mem.children(process.pid)) >= workers:
return
if process.poll() is not None:
raise RuntimeError(f"gunicorn exited with {process.returncode}")
time.sleep(0.05)
raise RuntimeError("gunicorn workers did not appear")
def get(port: int, query: str = "", pause_s: float = 0.03) -> tuple[int, int, int, int]:
"""One request: its status, the worker that answered, its collect count, its gc state.
The pause is what makes the arms comparable: a sync worker is back at ``accept`` a
millisecond after it replies, so a burst of requests can all land on one worker. A
short gap lets the kernel hand the next connection to a worker that is waiting.
"""
time.sleep(pause_s)
with urllib.request.urlopen(f"http://127.0.0.1:{port}/{query}", timeout=10) as response:
response.read()
return (response.status, int(response.headers["X-Worker"]),
int(response.headers["X-Collects"]), int(response.headers["X-Gc"]))
def stop(process: subprocess.Popen) -> None:
"""Stop the master and make sure no worker is left behind."""
if process.poll() is None:
process.send_signal(signal.SIGTERM)
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
def read_report(path: str) -> dict:
"""The master's account of its setup window, or an empty record if it wrote none."""
try:
with open(path, encoding="utf-8") as handle:
return json.load(handle)
except (OSError, ValueError):
return {}
def run_arm(arm: dict, port: int) -> dict:
"""One arm: start, serve until every worker answered, read the tree, stop."""
REPORTS.mkdir(exist_ok=True)
report = str(REPORTS / f"setup_{arm['name']}_{port}.json")
if os.path.exists(report):
os.unlink(report)
query = arm.get("query", "")
process = start(arm, port, report)
try:
wait_ready(process, port, WORKERS)
seen: dict[int, int] = {}
collects: dict[int, int] = {}
states: dict[int, int] = {}
answered = 0
for _ in range(REQUESTS):
status, pid, done, enabled = get(port, query)
answered += status == 200
seen[pid] = seen.get(pid, 0) + 1
collects[pid] = done
states[pid] = enabled
extra = 0
while len(seen) < WORKERS and extra < WORKERS * 5:
status, pid, done, enabled = get(port, query)
extra += 1
answered += status == 200
seen[pid] = seen.get(pid, 0) + 1
collects[pid] = done
states[pid] = enabled
memories = mem.tree(process.pid)
summed = mem.totals(memories)
worker_memory = sorted(memory.private_kb for memory in memories[1:])
worker_dirty = sorted(memory.private_dirty_kb for memory in memories[1:])
return {
"answered": answered,
"query": query or "slice",
"extra_requests": extra,
"worker_requests": dict(sorted(seen.items())),
"worker_collects": dict(sorted(collects.items())),
"worker_gc": dict(sorted(states.items())),
"collect_workers": sum(1 for done in collects.values() if done),
"processes": summed.processes,
"rss_kb": summed.rss_kb,
"pss_kb": summed.pss_kb,
"private_kb": summed.private_kb,
"private_dirty_kb": sum(memory.private_dirty_kb for memory in memories),
"rss_over_pss": round(summed.rss_over_pss, 3),
"worker_private_kb": worker_memory,
"worker_private_dirty_kb": worker_dirty,
"worker_rss_kb": sorted(memory.rss_kb for memory in memories[1:]),
"master": read_report(report),
}
finally:
stop(process)
def run_idle_arm(port: int) -> dict:
"""The same preloaded tree with four workers that have answered no request.
Readiness is the master's child list, not an HTTP ping: a ping would make the arm
something other than idle, and the difference it makes is the thing being measured.
"""
REPORTS.mkdir(exist_ok=True)
report = str(REPORTS / f"setup_idle_{port}.json")
process = start({"name": "idle", "preload": True}, port, report)
try:
wait_workers(process, WORKERS)
time.sleep(SETTLE_S)
memories = mem.tree(process.pid)
summed = mem.totals(memories)
return {
"workers": len(memories) - 1,
"requests": 0,
"rss_kb": summed.rss_kb,
"pss_kb": summed.pss_kb,
"private_kb": summed.private_kb,
"private_dirty_kb": sum(memory.private_dirty_kb for memory in memories),
"worker_private_kb": sorted(memory.private_kb for memory in memories[1:]),
"worker_private_dirty_kb": sorted(memory.private_dirty_kb
for memory in memories[1:]),
"master": read_report(report),
}
finally:
stop(process)
def summarize_master(runs: list[dict]) -> dict:
"""The master's side of the recipe: collections per generation, time, free space."""
reports = [run["master"] for run in runs if run.get("master")]
if not reports:
return {}
generations = len(reports[0].get("collections", []))
collections = [sum(report["collections"]) for report in reports]
return {
"runs": len(reports),
"collections_median": harness.summarize([float(value) for value in collections])["median"],
"collections_min": min(collections),
"collections_max": max(collections),
"per_generation_median": [
harness.summarize([float(report["collections"][index]) for report in reports])["median"]
for index in range(generations)
],
"collected_median": harness.summarize(
[float(sum(report["collected"])) for report in reports])["median"],
"setup_ms_median": harness.summarize(
[float(report["setup_ms"]) for report in reports])["median"],
"churn_objects": reports[0].get("churn_objects", 0),
"gc_enabled_at_fork": reports[0].get("gc_enabled_at_fork"),
"available_bytes_median": harness.summarize(
[float(report["malloc"]["available_bytes"]) for report in reports
if "malloc" in report])["median"],
"allocated_bytes_median": harness.summarize(
[float(report["malloc"]["allocated_bytes"]) for report in reports
if "malloc" in report])["median"],
}
def summarize_idle(runs: list[dict]) -> dict:
"""Median and range of the no-request tree, per worker and summed."""
workers = [value for run in runs for value in run["worker_private_kb"]]
dirty = [value for run in runs for value in run["worker_private_dirty_kb"]]
return {
"runs": runs,
"requests": 0,
"workers_per_run": sorted({run["workers"] for run in runs}),
"rss_kb_median": harness.summarize([float(run["rss_kb"]) for run in runs])["median"],
"pss_kb_median": harness.summarize([float(run["pss_kb"]) for run in runs])["median"],
"private_kb_median": harness.summarize(
[float(run["private_kb"]) for run in runs])["median"],
"private_dirty_kb_median": harness.summarize(
[float(run["private_dirty_kb"]) for run in runs])["median"],
"worker_private_kb_median": harness.summarize([float(value) for value in workers])["median"],
"worker_private_kb_min": min(workers),
"worker_private_kb_max": max(workers),
"worker_private_dirty_kb_median": harness.summarize(
[float(value) for value in dirty])["median"],
"worker_private_dirty_kb_min": min(dirty),
"worker_private_dirty_kb_max": max(dirty),
"master": summarize_master(runs),
}
def summarize_arm(runs: list[dict]) -> dict:
"""Median and range of every tree column, plus the per-worker median of the whole arm."""
workers = [memory for run in runs for memory in run["worker_private_kb"]]
return {
"runs": runs,
"rss_kb_median": harness.summarize([float(run["rss_kb"]) for run in runs])["median"],
"pss_kb_median": harness.summarize([float(run["pss_kb"]) for run in runs])["median"],
"private_kb_median": harness.summarize(
[float(run["private_kb"]) for run in runs])["median"],
"private_dirty_kb_median": harness.summarize(
[float(run["private_dirty_kb"]) for run in runs])["median"],
"private_kb_min": min(run["private_kb"] for run in runs),
"private_kb_max": max(run["private_kb"] for run in runs),
"worker_private_kb_median": harness.summarize([float(value) for value in workers])["median"],
"worker_private_kb_min": min(workers),
"worker_private_kb_max": max(workers),
"worker_private_dirty_kb_median": harness.summarize(
[float(value) for run in runs for value in run["worker_private_dirty_kb"]])["median"],
"worker_private_dirty_kb_min": min(value for run in runs
for value in run["worker_private_dirty_kb"]),
"worker_private_dirty_kb_max": max(value for run in runs
for value in run["worker_private_dirty_kb"]),
"rss_over_pss_median": harness.summarize(
[run["rss_over_pss"] for run in runs])["median"],
"answered": sorted({run["answered"] for run in runs}),
"collect_workers": sorted({run["collect_workers"] for run in runs}),
"requests_per_worker": sorted({value for run in runs
for value in run["worker_requests"].values()}),
"collects_per_worker": sorted({value for run in runs
for value in run["worker_collects"].values()}),
"gc_states": sorted({value for run in runs for value in run["worker_gc"].values()}),
"master": summarize_master(runs),
}
def main() -> None:
heap, sizes = harness.build_measured_heap(HEAP_RECORDS, harness.PAYLOAD)
frozen = freeze_heap()
unfreeze()
del heap
arms: dict[str, dict] = {}
for index, arm in enumerate(ARMS):
runs = [run_arm(arm, 9200 + index * 10 + repeat) for repeat in range(REPEATS)]
arms[arm["name"]] = summarize_arm(runs)
summary = arms[arm["name"]]
print(arm["name"], summary["rss_kb_median"], summary["pss_kb_median"],
summary["private_kb_median"], summary["worker_private_kb_median"],
summary["collects_per_worker"], summary["gc_states"],
summary["master"].get("collections_median"), flush=True)
idle_runs = [run_idle_arm(9400 + repeat) for repeat in range(REPEATS)]
idle = summarize_idle(idle_runs)
print("idle", idle["rss_kb_median"], idle["pss_kb_median"], idle["private_kb_median"],
idle["worker_private_kb_median"], idle["worker_private_dirty_kb_median"],
idle["workers_per_run"], flush=True)
harness.write_result("08_gunicorn.json", {
"conditions": {
"workers": WORKERS,
"requests": REQUESTS,
"repeats": REPEATS,
"idle_repeats": len(idle_runs),
"idle_requests": 0,
"settle_s": SETTLE_S,
"records": HEAP_RECORDS,
"payload_bytes": harness.PAYLOAD,
"slice_records": SLICE_RECORDS,
"churn_objects": CHURN_OBJECTS,
"heap_kb": sizes["growth_kb"],
"heap_private_kb": sizes["private_kb"],
"server": "gunicorn sync",
},
"master_heap": {"freeze_moved": frozen.frozen, "freeze_total": frozen.total_frozen,
"freeze_ms": frozen.elapsed_ms},
"arms": arms,
"idle": idle,
})
if __name__ == "__main__":
main()
The same payload in fifteen objects 13_density.py
"""Probe 13 - the same payload held by fifteen objects instead of 120,000.
The small-object heap of the other probes is dense: each record's five objects are
allocated one after another into the same small window of the heap, the 545 B payload by
glibc malloc and the dictionary, tag list, name and id from pymalloc's 16 KiB pools, so a
4 KiB page usually holds several objects' headers. Dense here means adjacent allocations,
not that the payload and the dictionary are a few hundred bytes apart in every record.
This probe keeps the record shape and the total payload bytes identical and changes only
the number of objects: fifteen 4,096,000 B payloads instead of 120,000 512 B ones.
If the copy-on-read bill came from the payload bytes, this heap would copy the same pages as
the small one. If it comes from the object headers, this heap copies fifteen pages.
"""
from __future__ import annotations
import gc
import sys
import harness
OBJECTS = 15
PAYLOAD = 4_096_000 # 15 x 4,096,000 B = 61,440,000 B, the small heap's payload total
REPEATS = 5
SMALL_RECORDS = 120_000
SMALL_PAYLOAD = 512
def read_every_object(heap: list[dict]) -> int:
"""Read one attribute of every record and write nothing back."""
total = 0
for record in heap:
total += len(record["payload"])
return total
def main() -> None:
heap, sizes = harness.build_measured_heap(OBJECTS, PAYLOAD)
tracked = len(gc.get_objects())
record = heap[0]
idle = harness.repeat_arm(lambda: None, REPEATS)
read = harness.repeat_arm(lambda: read_every_object(heap), REPEATS)
harness.write_result("13_density.json", {
"conditions": {
"objects": OBJECTS,
"payload_bytes": PAYLOAD,
"payload_total": OBJECTS * PAYLOAD,
"repeats": REPEATS,
"page_kb": harness.page_size() // 1024,
"small_records": SMALL_RECORDS,
"small_payload_bytes": SMALL_PAYLOAD,
"small_payload_total": SMALL_RECORDS * SMALL_PAYLOAD,
},
"parent": {
**sizes,
"pages": round(sizes["growth_kb"] / (harness.page_size() // 1024)),
"tracked_objects": tracked,
"sizeof_payload": sys.getsizeof(record["payload"]),
"payload_header_bytes": sys.getsizeof(record["payload"]) - PAYLOAD,
"sizeof_record": sys.getsizeof(record),
},
"checks": {
"dict_tracked": gc.is_tracked(record),
"payload_tracked": gc.is_tracked(record["payload"]),
"read_total": read_every_object(heap),
},
"arms": {"idle": idle, "read": read},
})
if __name__ == "__main__":
main()
The record’s object sizes and the pages they share 15_sizes.py
"""Probe 15 - the sizes behind the density, and where pymalloc stops.
Probe 13 shows that the same payload costs 87 MiB of private memory when it is held by
120,000 records and 92 KiB of copying when it is held by fifteen. The difference is object density, and density is a
question about allocation: CPython's pymalloc serves requests of 512 bytes or less from its
own pools and hands anything larger to the C library, so which parts of a record share a
page is decided by their sizes, not by their order in the dictionary.
The pool is not a page. On a 64-bit build pymalloc carves 16 KiB pools out of 1 MiB
arenas (``pycore_obmalloc.h``: ``USE_LARGE_POOLS`` sets ``POOL_BITS`` to 14), and the
kernel's copy-on-write works on the 4 KiB page, so this probe reads the runtime's own
numbers for both sizes and then counts, for every part of the record, how many of them
share one 4 KiB page in a heap built exactly as the other probes build it. ``id()`` is the
object's address in CPython, so the count is the density the kernel sees when a reference
count in one of them dirties the page.
"""
from __future__ import annotations
import gc
import statistics
import sys
import harness
RECORDS = 20_000
PAYLOAD = 512
# Documented: pymalloc is used for allocations of 512 bytes or fewer (CPython C-API,
# "Memory Management"). A request above it goes to malloc, below it to a pool.
PYMALLOC_MAX = 512
PARTS = ("record", "id", "name", "tags", "payload")
def part(record: dict, name: str):
"""The object a part name refers to; ``record`` is the dictionary itself."""
return record if name == "record" else record[name]
def per_page(heap: list[dict], name: str, page: int) -> dict:
"""How many of one part share a page: median, maximum and the pages they occupy."""
groups: dict[int, int] = {}
for record in heap:
address = id(part(record, name)) // page
groups[address] = groups.get(address, 0) + 1
counts = sorted(groups.values())
return {
"pages": len(groups),
"per_page_median": statistics.median(counts),
"per_page_max": counts[-1],
"per_page_min": counts[0],
"share_of_pages_with_2_or_more": round(
sum(1 for value in counts if value > 1) / len(counts), 4),
}
def allocator() -> dict:
"""The pool and arena sizes the running interpreter reports, and the ratio of them.
``sys._debugmallocstats()`` prints its own accounting: the number of arenas, the bytes
per arena, and the size of an unused pool. Reading those numbers is how the page's
"16 KiB pool" claim is the host's rather than a value copied from a header comment.
"""
text = harness.malloc_stats()
pool_bytes = arena_bytes = 0
for line in text.splitlines():
if "unused pool" in line and " bytes" in line:
pool_bytes = int(line.split("*")[1].split()[0])
elif "bytes/arena" in line:
arena_bytes = int(line.split("*")[1].split()[0].replace(",", ""))
return {
"pool_bytes": pool_bytes,
"arena_bytes": arena_bytes,
"pools_per_arena": arena_bytes // pool_bytes if pool_bytes else 0,
"pages_per_pool": pool_bytes // harness.page_size() if pool_bytes else 0,
"small_request_threshold": 512,
"size_classes": 32,
"source": "sys._debugmallocstats()",
}
def main() -> None:
heap = harness.build_heap(RECORDS, PAYLOAD)
page = harness.page_size()
record = heap[0]
sizes = {name: sys.getsizeof(part(record, name)) for name in PARTS}
sizes["tag"] = sys.getsizeof(record["tags"][0])
tracked = {name: gc.is_tracked(part(record, name)) for name in PARTS}
density = {name: per_page(heap, name, page) for name in PARTS}
harness.write_result("15_sizes.json", {
"conditions": {
"records": RECORDS,
"payload_bytes": PAYLOAD,
"page_size": page,
"pymalloc_max_bytes": PYMALLOC_MAX,
"python": sys.version.split()[0],
},
"sizes": sizes,
"over_pymalloc": {name: sizes[name] > PYMALLOC_MAX for name in PARTS},
"payload_over_pymalloc_by": sizes["payload"] - PYMALLOC_MAX,
# The record owns five of the objects it holds: the dictionary, the name, the tag
# list, the id and the payload. The two tag strings are interned literals that every
# record only points at, so their bytes are reported apart from the record's own
# cost and are never added into it - the same split section 5 of the page makes.
"record_owned_bytes": (sizes["record"] + sizes["id"] + sizes["name"]
+ sizes["tags"] + sizes["payload"]),
"record_tag_bytes": 2 * sizes["tag"],
"record_objects": len(PARTS),
"allocator": allocator(),
"density": density,
"tracked": tracked,
})
if __name__ == "__main__":
main()
Take the next step
- Zero-Crash Python – one measured failure per issue, with its probe. Free.
- Runbook checklists on Gumroad – these tables as an incident-doc checklist.
