ENOMEM errno 12: Cannot Allocate Memory – The Limit That Said No

Dark cover headed 'Cannot allocate memory': errno 12, 65,420 pages mapped before the ceiling refused, 354 MiB still available, and 56 passing tests

Updated December 1, 2026 · every figure below was measured on the host described in Section 1, and a table that counts runs says how many it used.

  • errno 12 says a wall was hit, not which one. Three of this page’s four walls are refused with that number: the 65,530-mapping ceiling, an address-space limit and a data limit. A process count is the fourth, and it answers 11 at fork and RuntimeError at a thread.
  • The ceiling answered first here. 65,420 pages were mapped with 354 MiB still available, and the next call succeeded after a single page was released.
  • A row is not a call. Python’s default mapping is MAP_SHARED, and three of those cost three rows; 1 row covered 1,000 adjacent MAP_PRIVATE mappings, and one guard page costs 2.
  • Python gives the same failure three names. A refused allocation arrives as OSError, MemoryError or RuntimeError depending on the call, so a handler for one of them misses the others.
  • can't start new thread has four causes. Two can be forced from inside a process – the stack’s address space and RLIMIT_NPROC – and this host answered RLIMIT_NPROC to the second.
  • 1,536 KiB of address space decides by request size. With 1,536 KiB left, a 4 KiB map and a 512 KiB allocation still worked; a 2 MiB map, a 4 MiB allocation and a default thread did not.

Fix It First: Ten Changes, Matched to What You Saw

What you sawWhat it usually isFirst move
OSError: [Errno 12] from mmap, and MemAvailable in the hundreds of MiBThe mapping count of this process is at vm.max_map_countCompare rows in /proc/self/maps with the ceiling; map fewer, larger regions
The same 12 only under ulimit -v, a systemd MemoryLimit or a Job objectA hard address-space limit, not RAMRead RLIMIT_AS and this process’s VmSize; the difference is all the room there is
MemoryError for a request far smaller than free memoryA data limit or the mapping count, hit inside the interpreter’s own allocatorCheck RLIMIT_DATA against VmData, and the row count, before resizing anything
RuntimeError: can't start new threadThe thread’s stack does not fit the address space, or the uid is at its task countLower threading.stack_size for the pool; if the address space is unlimited, compare the task count with RLIMIT_NPROC
fork refused with errno 11, EAGAINRLIMIT_NPROC: a count of tasks, not bytesCount tasks for the uid and compare with the limit
The worker disappears, the exit code is 137, no exception is raisedThe kernel’s OOM killer, or a cgroup limit – never an ENOMEM the code can catchRead the cgroup’s memory.events and memory.max
A retry decorator that never retries, and a MemoryError that reaches the topThe handler catches OSError, which MemoryError is notCatch (OSError, MemoryError, RuntimeError), then classify
12 on the first request after a long, healthy runA mapping count that grew with traffic and never came downLog the row count with every refusal; a rising count is the bug
12 in a loop that maps once per item with Python’s default flagsThe loop, not the host: one MAP_SHARED row per call accumulates until the ceilingBatch the work into one region, or close each mapping as the item ends
More RAM changed nothingThe wall is a count or a limit, so memory was never the constraintRead the mapping count, address space, data limit and available memory, in that order
Table 1: ten symptoms and the wall each one points at. The order in the last row is the order that costs least to check.

1. What This Page Measures

Everything below comes from one machine: Linux 6.12.118-guest-1.1, x86-64, 2 CPUs, 1,486 MiB of RAM and no swap, running Python 3.12.16 as uid 1000. The numbers that decide an ENOMEM were read from the kernel before any arm ran: vm.max_map_count is 65,530, vm.overcommit_memory is 0, CommitLimit is 743 MiB while Committed_AS is 1,121 MiB, so the host already runs over-committed. RLIMIT_AS is unlimited, RLIMIT_DATA is 2,048 MiB, RLIMIT_NPROC is 256 and the default thread stack is 8 MiB.

Each arm runs in its own interpreter, so an arm that lowers a limit cannot lower the next one’s. Every arm ran five times; a cell shows the median and, where the runs disagreed, the range. The probe that walks to the mapping ceiling records the row count, the address space, the resident pages and the memory available at the moment of refusal, so the arithmetic can be checked instead of trusted.

One detail decides whether that walk measures anything at all. mmap.mmap(-1, n) asks for a shared anonymous mapping: the row the kernel writes for it ends in rw-s and names /dev/zero, and three such calls add three rows. The private form of the same call behaves differently, and Section 3 measures the difference rather than assuming it away.

QuestionMeasured hereHow
What the mapping ceiling is and what it countsYesA probe maps 4 KiB pages until the kernel refuses, five times
Whether one mapping is always one rowYesThree shared, three private and a thousand private mappings, counted in /proc/self/maps
What a guard page costs in rowsYesOne and three pages turned PROT_NONE inside a twelve-page mapping
What RLIMIT_AS refuses and what still fitsYesThe limit is set relative to each child’s own VmSize
What RLIMIT_DATA boundsYesA limit set to this process’s VmData plus 8 MiB, asked for 4 KiB, 16 MiB and 64 MiB, private and shared
What a process-count limit answersYesRLIMIT_NPROC lowered, then fork and a thread
How each failure surfaces in PythonYesThe exception class, its errno attribute and its message are recorded
cgroup v2 memory.max, pids.max and OOM killsNoThis host has no cgroup v2 mount, so the page describes them and does not measure them
vm.overcommit_memory=2 refusalsNoThe value is recorded as 0; the policy was not changed to force a refusal
Table 2: nine questions, seven answered by a run on this host. The other two are marked as described, not measured, wherever they appear.

2. One Number, Fourteen Calls

The matrix below is the argument in one table: fourteen arms, five repeats each, each in a fresh interpreter. Four were refused with errno 12, one with 11, three raised MemoryError, one RuntimeError, and three simply worked; the two ceiling follow-ups answered 12 for MAP_NORESERVE and a clean map once every page was released.

Call, and what was arrangedAnswerRunsWhat the caller sees
Map one anonymous page, no limit changedok5/5Nothing: the control
Map 128 TiB125/5OSError
RLIMIT_AS = own VmSize + 1,536 KiB, map 2 MiB125/5OSError
Same limit, start a default threadRuntimeError5/5RuntimeError: can't start new thread
Same limit, allocate 4 MiBMemoryError5/5MemoryError
Same limit, forkok5/5A child, with no new address space
RLIMIT_NPROC = own threads + 1, fork115/5BlockingIOError (an OSError)
RLIMIT_DATA = VmData + 8 MiB, allocate 64 MiBMemoryError5/5MemoryError
Same limit, map 64 MiB with Python’s default flagsok5/5A shared mapping, which this limit does not cover (Section 6)
Map 4 KiB pages until the kernel refuses125/5OSError
At that ceiling, allocate 16 MiBMemoryError5/5MemoryError, from the interpreter’s own allocator
At that ceiling, map 4 KiB with MAP_NORESERVE125/5OSError: the wall is not commit
At that ceiling, close every page and map againok5/5Nothing: the room came back
mprotect a page that was never mapped125/5OSError
Table 3: fourteen allocation paths, 70 runs. The answer column is the errno or the exception class; where it says ok, nothing was raised.

Three rows carry the argument. errno 12 is not a statement about memory: the same number came from a request too large for the accounting, from a map at a ceiling that counts regions, and from a mprotect on a page no mapping covers. The kernel has other numbers for other shortages, and 11 is the one a process count produces – Python reports it as BlockingIOError, still an OSError. And a fork with 1,536 KiB of address space left succeeds five times out of five, because the child shares the parent’s mappings and no new region is charged.

The ninth row is the one this page had to correct. A mapping that succeeds under the same data limit is not proof that the limit ignores mappings: it is proof that the call was shared. Section 6 asks the same question with both flags under the same limit, and the private answer is 12.

fork is where the two numbers are easiest to confuse, and the arms above keep them apart. The fork at the task count answered 11, Resource temporarily unavailable, five times out of five – not 12 – and the fork under a tight address space succeeded, because the child shares the parent’s mappings. So a fork: Cannot allocate memory is not the process count: it is an allocation the kernel refused, and the three walls that answer 12 are where to look. Reading it the other way round costs the first hour of an incident.

3. The Ceiling That Counts Regions, Not Bytes

The cheapest way to make 12 look like a memory problem is to fill the mapping ceiling. A process may hold only so many regions – vm.max_map_count of them, 65,530 here – and each anonymous one-page mapping made the way Python makes it is one region. The probe maps 4 KiB pages until the kernel refuses. Before that walk can be evidence of anything, though, one question has to be answered: what does the kernel count as one region?

One mapping is not one row

The kernel keeps one region per row in /proc/self/maps, and it merges two neighbouring regions when their attributes match. So the number of rows a process holds is not the number of times it called mmap. The probe measured both sides of that: three mappings made the way an application makes them, three made private and untouched, a thousand made either way, and a page turned into a guard in the middle of one region.

What was mappedRows addedRunsWhat it shows
Three pages with Python’s default flags (MAP_SHARED)+35/53 calls, 3 rows: each is its own file, so nothing merges
Three adjacent MAP_PRIVATE pages, untouched+15/53 calls, one row: the kernel merged them
The same three, with the first page written before the others+15/5The merge happened after a fault as well
1,000 adjacent MAP_PRIVATE pages, as a loop would make them+15/51,000 calls, one row, 4,000 kB of address space
The same 1,000 pages as MAP_SHARED+1,0005/5One row per call, which is what the ceiling walk relies on
One page of a twelve-page mapping turned into a guard page (PROT_NONE)+25/5One region became three: the guard splits it in two places
Three separated guard pages in the same mapping+65/5Two rows per guard; restoring the page returns +0
Table 4: seven calls the kernel answered differently, each repeated five times. The row count follows the kernel’s regions, not the application’s calls.

The merge is the reason the ceiling walk is a real experiment and not a tautology. mmap.mmap with no file argument asks for MAP_SHARED, the same call the application makes, so every page is its own row. A loop that maps private pages instead would add one row for a thousand calls and never reach the sysctl – the same loop, 4,000 kB larger, and invisible to a row count. And a process that follows the usual advice to guard its regions is charged two rows for every guard page, so its ceiling arrives sooner than its page count suggests.

With the premise measured, the walk itself: 65,420 pages mapped one at a time, five runs, identical to the row.

At the moment of refusalMedianRange of five runs
Pages the loop had mapped65,42065,420
Rows in /proc/self/maps before the loop106106
Rows at refusal65,53265,532
vm.max_map_count65,530the same in every run
Address space (VmSize)282 MiB–
Resident pages (VmRSS)21 MiB22,000 (21,940–22,108) kB
MemAvailable354 MiB362,152 (360,064–363,656) kB
Table 5: the refusal recorded five times. 21 MiB had been touched and 354 MiB were still available: this is not a host that ran out of memory.

The arithmetic is worth reading twice, because it explains why the number your loop reaches is not the number in the sysctl. The loop managed 65,420 pages, 106 regions already belonged to the interpreter, and it grew 6 more rows of its own while the loop ran, for 65,532 rows at refusal against a ceiling of 65,530. So the room a process has depends on what it already holds, which is why the same image fails at different counts on different hosts, and why a process that grows its region count over hours fails long after anyone stopped looking at memory.

That is also why the row counts quoted in this section start from different places. The shell one-liner below printed 39 rows, the example’s interpreter held 61, the ceiling probe 106, the guard’s probe 127, and the matrix probe’s ceiling arm 122 – because each process imports a different set of modules, and the interpreter and the shared libraries it loads are mapped before the first line of the script runs. The ceiling is the same 65,530 in every one of them; only the part already spent differs, so the pages a walk can add differ while the total it stops at does not.

The walk is quick too. The matrix probe’s ceiling arm started from a 122-row baseline and reached the same 65,532 rows in a median 147.9 ms – 2.26 µs a page. The example’s --full walk starts from 61 rows instead, so it has to add 65,465 pages to arrive at the same total.

Two follow-ups separate the ceiling from every memory explanation. At the wall, the probe releases one page and maps 4 KiB again; then it releases a second page and asks for 256 MiB in a single region. Both succeed five times out of five, and the size of the request barely enters into it: 256 MiB is 65,536 times the bytes and still one row.

What was done at the ceilingAnswerRunsWhat it shows
One page released, then map 4 KiBok5/5One row was the whole difference
Two pages released, then map 256 MiBok5/5The request was 65,536 times larger and still fitted
Every page released, then map 4 KiBok5/5Row count returned to 112: the 106 it started with, plus the rows the interpreter grew
Map 4 KiB with MAP_NORESERVE, without releasing125/5Skipping the commit charge does not buy a row
Allocate 16 MiB, without releasingMemoryError5/5The interpreter’s own allocator hits the same wall first
Table 6: five answers from a process that had already been refused. Each one narrows what the ceiling is.

MAP_NORESERVE changes whether a mapping is counted against commit; it does not change how many regions exist, so it cannot help at a region ceiling. And a plain 16 MiB allocation, which a reader expects to raise OSError, raised MemoryError: CPython maps large blocks itself, the kernel refused that internal map, and the interpreter translated it. The call you wrote is not necessarily the call that failed.

Counting the rows yourself

Two shell blocks answer what the ceiling is and how close this process is to it. Both were run here as printed.

grep -E '^(MemAvailable|CommitLimit|Committed_AS)' /proc/meminfo
cat /proc/sys/vm/max_map_count /proc/sys/vm/overcommit_memory

The first block printed:
MemAvailable: 464356 kB
CommitLimit: 761060 kB
Committed_AS: 1154952 kB
65530
0

python3 -c 'print(sum(1 for _ in open("/proc/self/maps")), "mappings of",
                     open("/proc/sys/vm/max_map_count").read().strip())'

The second printed:
39 mappings of 65530
That count belongs to one interpreter at one moment; a service with thread pools and native extensions starts hundreds of rows higher.

Can one process raise its own ceiling?

No. vm.max_map_count is a global sysctl, so raising it changes the ceiling for every process on the host and needs root. The per-process alternative is to need fewer regions: one large map instead of thousands of small ones, a pool instead of a map per request, and a close in the same block that opened the mapping.

4. 1,536 KiB of Address Space, Seven Calls

RLIMIT_AS is the other wall that produces 12, and it most often appears on a host with plenty of memory, because a limit written into a unit file years ago is still in force. The probe sets the limit to each child’s own VmSize plus 1,536 KiB, and the readings taken at every failure show 1,536 KiB left. It then asks seven calls to fit.

Call, with 1,536 KiB of address space leftAnswerRunsWhy
Map 4 KiBok5/5Fits in the room
Map 2 MiB125/5Larger than the whole room
Allocate 512 KiBok5/5Fits
Allocate 4 MiBMemoryError5/5Translated by the interpreter, not returned by a call you made
Start a default threadRuntimeError5/5The default stack is 8 MiB, more than the room left
Start a thread with a 256 KiB stackok5/5Same call, one thirty-second of the mapping
forkok5/5The child shares the parent’s mappings
Table 7: seven calls against the same 1,536 KiB, each repeated five times. Request size decides, not the free-memory number.

threading.Thread does not fail because a process is near a limit in the abstract; it fails because starting a thread maps a stack, and the default stack is 8 MiB – the RLIMIT_STACK this host reports. A 256 KiB stack made the same call succeed in the same room, five times out of five. That is a two-line change in a pool’s initializer. It is also only one of the four causes of that message, and Section 5 lists the rest.

The fork row corrects intuition. A process 1,536 KiB from its address-space limit still forks, because the child begins by sharing the parent’s mappings copy-on-write and nothing is charged until either side writes. What fails in that state is the call that asks for a new region. If fork itself is refused, the limit is the process count and the number is 11.

  1. Read RLIMIT_AS and subtract VmSize: the difference is the whole budget every map, stack and large allocation shares.
  2. Start threads with an explicit stack_size under any limit, sized against that budget.
  3. Treat a failed thread as a sizing decision first and a count second: the same call with the same stack fails the same way, and Section 5 shows where the count comes in.

5. Three Names for the Same Refusal

The kernel has one number for the refusal and Python has three ways of telling you about it. Which one you get depends on the call, not the wall – the detail that lets a retry loop walk past a failure it was written to handle.

Call that failedPython raiseserrno attributeSubclass of OSErrorCaught by except OSError
mmap, or any direct syscall wrapperOSError12yesyes
A large allocation, or one that forces a new arenaMemoryErrornonenono
threading.Thread.startRuntimeErrornonenono
fork at a process-count limitBlockingIOError11yesyes
mprotect over a range no mapping coversOSError12yesyes
Table 8: five failures, four exception classes in three families. The two cells in bold are the ones a handler written for errno 12 never sees.

MemoryError is not a subclass of OSError; it sits beside it under Exception. So the common shape – a decorator that catches OSError, checks exc.errno == errno.ENOMEM and backs off – never runs for the allocation that raised MemoryError, and never runs for the thread that raised RuntimeError. The failure then surfaces wherever the next raise happens to be, usually far from the call that caused it, and the traceback names a variable instead of a wall.

The fix is not to catch Exception and hope. Catch the three, then classify with the numbers rather than the message: a failure with no rows left is the mapping count, one with a small RLIMIT_AS remainder is the address space, a MemoryError that does not fit what is left of the data limit is that limit, and an 11 from a fork is the process count. Section 7 wraps that in 391 lines of package, with the tests printed alongside.

The same message, four causes

RuntimeError: can't start new thread is the least informative of the three, because the call that fails carries no errno at all. Four different causes produce it. A thread begins by mapping its stack, so a tight address space refuses that map. The task it then creates is counted against RLIMIT_NPROC, which is a count of tasks for the uid rather than bytes. Behind both sit two limits no ordinary process can lower: the kernel-wide threads-max, and a cgroup’s pids.max. The page forced the two it could and read the two it could not.

What was arrangedThe exceptionWhat diagnose answeredRuns
RLIMIT_AS with 1,536 KiB left, start a default threadRuntimeErrorRLIMIT_AS5/5
RLIMIT_NPROC at the uid’s own task count (4 tasks, limit 4), start a threadRuntimeErrorRLIMIT_NPROC5/5
RLIMIT_NPROC one task above that count (5): two threads asked forRuntimeError on the secondthe first started, the second did not5/5
The kernel’s threads-max, read as 7,743; lowering it needs rootnot forceddescribed, not measured–
A cgroup’s pids.maxnot availabledescribed, not measured: no cgroup v2 mount–
Table 9: five rows, four causes, three of them forced here. The address space and the two task-count rows are the ones a process can arrange for itself; RLIMIT_NPROC is not enforced for root (CAP_SYS_RESOURCE), so the task-count rows are reproduced as an ordinary user and the test that drives that wall skips itself as root.

The second row is the one a message-only classifier gets wrong. With RLIMIT_AS unlimited and the uid at its task count, the stack fits and the task does not, so a classifier that looks only for an address space has nothing to name – and before the count is read, undetermined is the honest name for that state. The guard reads the count on that path, which is why this row is answered RLIMIT_NPROC. The third row shows what the count actually counts: with one task of room, the first thread started and the second was refused, five times out of five, so a thread costs the limit one and the limit is per uid, not per process.

The last two rows are named so they are not mistaken for measured ones. threads-max is readable (7,743 on this host, with 4 tasks running) and writable only by root; pids.max needs a cgroup v2 mount, and this host has none. In a container they are the likeliest cause left, and an undetermined answer there says exactly what it should: no limit this guard can read was spent.

Two caveats belong to the task count itself. The kernel does not enforce RLIMIT_NPROC for a process with CAP_SYS_RESOURCE, so the row cannot be reproduced as root; the test in the appendix skips that wall when it runs with that privilege. And the count is read by walking /proc, which sees only this PID namespace and, under a hidepid mount, only the status files it is allowed to read – so in a container the sum is lower than the uid’s real task count, and the verdict is a verdict about what is visible from here.

6. The Numbers to Read Before Changing Anything

Six readings decide an ENOMEM, and each is one file or one syscall, answering the question directly where free answers a different one.

QuestionWhere the answer isOn this host, as read
How many mapping regions does this process hold, and what is the ceiling?/proc/<pid>/maps row count, /proc/sys/vm/max_map_count106 of 65,530 before the loop
How much address space is left under the limit?RLIMIT_AS and VmSize in /proc/<pid>/statusunlimited, with a 282 MiB process at the ceiling
Is a data limit set, and how much of it is spent?RLIMIT_DATA, and VmData in the same status file2,048 MiB; the spent part is VmData
How many tasks does this uid hold, against what limit?RLIMIT_NPROC, and Threads for each process of the uid256, with 4 tasks when the probe read it
Does the kernel think memory is committed?MemAvailable, CommitLimit, Committed_AS in /proc/meminfo354 MiB available at the ceiling; 743 MiB of limit against 1,121 MiB committed
Was the process killed rather than refused?exit status 137, and the cgroup’s memory.eventsdescribed, not measured: this host has no cgroup v2 mount
Table 10: six readings, five of them available on any Linux host without root. The order matters more than the values.

The commit accounting earns its own paragraph because it looks like a lie. CommitLimit is 743 MiB on a host with 1,486 MiB of RAM, and Committed_AS is already 1,121 MiB. The machine is over-committed before a container starts, which is legal and normal under the heuristic policy (vm.overcommit_memory is 0), and it is why free memory and commit accounting can disagree by hundreds of MiB while both are right.

The same wall, in one request size

One anonymous mapping of six sizes, five repeats each: 512 MiB and 1 GiB were accepted, 2 GiB and 4 GiB were refused with 12, and so were 1 TiB and 128 TiB. No page was written, so what changed at the boundary was the kernel’s accounting decision, not the state of the RAM. The obvious reading – commit pressure, because a request of 2 GiB is past every commit figure on the machine – is wrong, and the next table shows why: the probe bisected the boundary to the mebibyte and found it at the host’s own size.

One anonymous mappingAnswerRunsWhat it rules out
1,486 MiB, private and sharedok5/5Twice CommitLimit, and still accepted
1,487 MiB, one past the host’s RAM plus swap125/5The boundary is the host’s size, not the commit figure
1,485 MiB, one short of itok5/5A mebibyte decides it
2 GiB, the size the first walk refused125/5Refused for its size, not for the pages behind it
Table 11: the heuristic’s boundary, bisected under vm.overcommit_memory 0. RAM plus swap is 1,486 MiB and a fraction; CommitLimit is 743 MiB.

So the 12 at 2 GiB is not the kernel declining to promise what it does not have. Under the heuristic policy a single request larger than RAM plus swap is refused, and this host has 1,486 MiB and no swap: 1,486 MiB was accepted five times and 1,487 MiB refused five times, private and shared alike. A request of 1 GiB passed even though Committed_AS was already above CommitLimit, which is the cleanest evidence that the commit figure was never the test.

Changing the policy is a decision for the host, not a fix for the process: vm.overcommit_memory=2 refuses anything past CommitLimit, which turns a slow death into an early refusal and breaks hosts already above that line. The value is recorded here, not recommended.

What the data limit covers

The ninth row of Table 3 mapped 64 MiB with Python’s default flags under the same relative limit and succeeded, which reads like a rule: mappings are not data. It is not a rule, it is a flag. Since Linux 4.7 the kernel charges a writable private anonymous mapping to RLIMIT_DATA, and this host on kernel 6.12 behaved exactly as that rule says; the call Python makes by default is shared, which the limit does not cover.

A fixed 8 MiB limit cannot show the boundary, though, because an interpreter spends more than that before the first line of a script runs: every private request would be refused and the flag would look irrelevant. So every table on this page sets the limit relative to each child’s own VmData plus 8 MiB – the two data rows of Table 3 and all six rows of Table 12 alike – which leaves 8,192 KiB of room to spend. The same probe asks for four sizes with both flags, and the charge is visible in the reading, not inferred: a 4 KiB private mapping moves VmData by 4 kB, 7 MiB by 7,168 kB, and the shared mapping by nothing.

Request with RLIMIT_DATA at VmData + 8 MiBAnswerRunsWhat it shows
Map 4 KiB with MAP_PRIVATEok5/5Charged 4 kB: the request is the charge
Map 7 MiB with MAP_PRIVATEok5/5Charged 7,168 kB of the room left
Map 16 MiB with MAP_PRIVATE125/5Twice the room left, and refused
Map 64 MiB with MAP_PRIVATE125/5Eight times the room left, and refused
Map 64 MiB with Python’s default MAP_SHAREDok5/5Charged 0 kB: the same bytes, not this limit
Allocate 16 MiB with bytearrayMemoryError5/5The interpreter’s own allocator, translated before you see it
Table 12: one relative limit, two flags and four sizes, six answers, five runs each. Which wall answers depends on the flag, not on the number of bytes.

For a runbook the consequence is narrow and useful: if a MemoryError and a 12 arrive from the same service under the same limit, the difference may be nothing more than which mapping call the code path took. Compare VmData with RLIMIT_DATA before blaming the host, and read the flag before concluding that mappings are exempt.

One failure never becomes an exception: when the kernel or a cgroup kills a process for memory, no code runs. The shell sees exit status 137 – 9 plus 128 – and the evidence sits in the cgroup’s memory.events, not in a traceback. A service that dies at a limit with no log line was judged by the kernel.

One shell block ties the two files together, and was run here as printed:

python3 -c 'import mmap; mmap.mmap(-1, 2 ** 47)' ; echo "exit=$?"

It printed exit=1 and, above that, OSError: [Errno 12] Cannot allocate memory – the smallest reproduction of this page’s subject, with no file, no limit and no setup.

Is errno 12 ever worth retrying?

Only after something is released. In Table 6 a page was freed and the next map succeeded, so a retry that frees first is not superstition. A retry against an unchanged mapping count, an unchanged address space or an unchanged data limit fails identically and the backoff only delays the diagnosis.

7. A Guard That Refuses Before the Kernel Does

Everything so far ends in a diagnosis after the fact. The other half is cheaper: the numbers a refusal would be judged by are readable at any moment, so a process that is about to need many regions can look before it maps. The package does that in two files, reads four files and three rlimits, walks /proc for the task count only when a thread has already failed, and allocates nothing it does not return.

The package is an __init__ that exports nine names and two modules that do the work; all three are printed below, so the folder can be reconstructed from this page.

"""A small guard against the four walls that answer for an ENOMEM."""
from memguard.guard import Exhausted, Limit, MappingBudget, diagnose
from memguard.limits import Headroom, headroom, map_limit, map_room, maps_used

__all__ = ["Exhausted", "Limit", "MappingBudget", "diagnose", "Headroom", "headroom",
           "map_limit", "map_room", "maps_used"]

The readings

The first file is only reading: a row count, the ceiling, the address space in use, the data limit and how much of it this process has spent, the memory the kernel says is available, and the task count that RLIMIT_NPROC is compared with. A guard against ENOMEM has no business allocating while it measures, so each read is one small file or one syscall, and those numbers travel together as a Headroom record.

That record comes in two sizes, and the difference is the point of the file. map_room is the reading a mapping budget starts from: the rows in use, the ceiling and the address space left – three reads, and none of them a pass over /proc. The row count is itself a read of this process’s own maps file, and its size is bounded by the ceiling it is compared with, so it grows with the rows it counts and with nothing else on the host – which is why the budget takes the reading once and counts its own rows after that. headroom is the whole record and is taken after something has failed; its task count stays unread until with_tasks asks for it, because that one reading costs a walk over every process on the host and no map can spend it. Both readings use one sentinel: a field that was not read is None, and -1 is a limit that was read and has no ceiling.

"""Read what the kernel says about this process, in the numbers that answer ENOMEM.

A guard that runs out of memory while measuring memory is no guard, so every read here is one
small file read, one syscall, or one pass over /proc for the task count, and nothing is
allocated on purpose.

The readings come in two sizes. ``map_room`` is the reading a mapping budget starts from: the
rows in use, the ceiling and the address space left, which are the three numbers a mapping can
spend, and ``None`` in every field a map cannot. ``headroom`` is the whole record, and it is
what a failure is judged with. The task count - the one reading that costs a pass over every
process on the host - is taken only when it is asked for, because no map can spend it.
"""
from __future__ import annotations

import os
import pathlib
import resource
from dataclasses import dataclass, replace

PROC = pathlib.Path("/proc")
PAGE = 4096


def _proc(pid: int, leaf: str) -> pathlib.Path:
    return PROC / (str(pid) if pid else "self") / leaf


def status_fields(pid: int = 0) -> dict[str, int]:
    """Every numbered field of /proc/<pid>/status, read once: VmSize, VmData, Threads, Uid."""
    fields: dict[str, int] = {}
    for line in _proc(pid, "status").read_text().splitlines():
        key, _, rest = line.partition(":")
        parts = rest.split()
        if parts and parts[0].isdigit():
            fields[key] = int(parts[0])
    return fields


def status_kb(key: str, pid: int = 0) -> int:
    """One Vm* field of /proc/<pid>/status, in kB."""
    try:
        return status_fields(pid)[key]
    except KeyError:
        raise KeyError(key) from None


def maps_used(pid: int = 0) -> int:
    """Rows in /proc/<pid>/maps: one row per mapping, which is what the ceiling counts."""
    with open(_proc(pid, "maps"), "rb") as handle:
        return sum(1 for _ in handle)


def map_limit() -> int:
    return int((PROC / "sys/vm/max_map_count").read_text().strip())


def vm_size_kb(pid: int = 0) -> int:
    return status_kb("VmSize", pid)


def vm_data_kb(pid: int = 0) -> int:
    return status_kb("VmData", pid)


def mem_available_kb() -> int:
    for line in (PROC / "meminfo").read_text().splitlines():
        if line.startswith("MemAvailable:"):
            return int(line.split()[1])
    raise KeyError("MemAvailable")


def _limit(which: int) -> int:
    soft, _ = resource.getrlimit(which)
    return -1 if soft == resource.RLIM_INFINITY else soft


def _limit_kb(which: int) -> int:
    soft = _limit(which)
    return -1 if soft < 0 else soft // 1024


def address_space_left_kb(pid: int = 0) -> int:
    """Room left under RLIMIT_AS, or -1 when the limit is unlimited."""
    limit = _limit_kb(resource.RLIMIT_AS)
    return -1 if limit < 0 else max(0, limit - vm_size_kb(pid))


def data_limit_kb() -> int:
    return _limit_kb(resource.RLIMIT_DATA)


def nproc_limit() -> int:
    return _limit(resource.RLIMIT_NPROC)


def uid_tasks(uid: int | None = None) -> int:
    """Tasks this uid owns, threads included, which is what RLIMIT_NPROC counts.

    One pass over /proc: each readable status file gives its real uid and its thread count, so
    a thread that will not start can be measured against the count the kernel checks.

    What this cannot see, it cannot count. A ``hidepid`` mount hides other processes' status
    files, and inside a PID namespace - a container - /proc lists only that namespace's
    processes, so the sum is lower than the uid's real task count and a verdict built on it is
    a verdict about what is visible here. The same limit is also not enforced at all for a
    process with CAP_SYS_RESOURCE, which is why the wall test skips itself as root.
    """
    wanted = os.getuid() if uid is None else uid
    tasks = 0
    for entry in PROC.iterdir():
        if not entry.name.isdigit():
            continue
        try:
            fields = status_fields(int(entry.name))
        except OSError:
            continue
        if fields.get("Uid") == wanted:
            tasks += fields.get("Threads", 1)
    return tasks


@dataclass(frozen=True)
class Headroom:
    """One process's numbers: rows left, address space, data, tasks, free memory.

    A field that was not read is ``None``. The value -1 is reserved for one thing only: a limit
    that was read and has no ceiling. One sentinel for one meaning, so a cheap reading can be
    mistaken neither for a measurement of zero nor for a limit that is unlimited.
    """

    maps_used: int
    maps_limit: int
    address_space_left_kb: int
    data_limit_kb: int | None = None
    mem_available_kb: int | None = None
    data_used_kb: int | None = None
    nproc_soft: int | None = None
    nproc_used: int | None = None

    def maps_left(self) -> int:
        return max(0, self.maps_limit - self.maps_used)

    def data_left_kb(self) -> int | None:
        """Room left under RLIMIT_DATA: -1 unlimited, None when either number was not read."""
        if self.data_limit_kb is None or self.data_used_kb is None:
            return None
        if self.data_limit_kb < 0:
            return -1
        return self.data_limit_kb - self.data_used_kb

    def nproc_left(self) -> int | None:
        """Room left under RLIMIT_NPROC: -1 unlimited, None when either number was not read."""
        if self.nproc_soft is None:
            return None
        if self.nproc_soft < 0:
            return -1
        if self.nproc_used is None:
            return None
        return max(0, self.nproc_soft - self.nproc_used)

    def with_tasks(self, uid: int | None = None) -> "Headroom":
        """The same record with the uid's task count read: one pass over /proc, on request."""
        if self.nproc_used is not None:
            return self
        return replace(self, nproc_used=uid_tasks(uid))

    def pages_for(self, length: int) -> int:
        """The pages a length occupies; a row is one map whatever this says."""
        return max(1, -(-length // PAGE))


def map_room(pid: int = 0) -> Headroom:
    """What one mapping is checked against, and nothing a mapping cannot spend.

    Three reads at most - the rows this process holds, the ceiling they are compared with, and
    the address space left, the last only when a limit is set - and no pass over /proc. The
    fields a mapping cannot spend stay ``None`` here rather than a value that could be misread
    as a limit: the data limit, the free memory and the task count. The row count is itself a
    read of this process's own maps file, so it grows with the rows it counts; a budget that
    takes it before every map pays for it on every map, which is why ``MappingBudget`` reads it
    once and projects the rest.
    """
    space = _limit_kb(resource.RLIMIT_AS)
    return Headroom(
        maps_used=maps_used(pid),
        maps_limit=map_limit(),
        address_space_left_kb=-1 if space < 0 else max(0, space - vm_size_kb(pid)),
    )


def headroom(pid: int = 0, tasks: bool = False) -> Headroom:
    """The whole record: one read per question, and the task count only if it is asked for.

    ``tasks=True`` adds the pass over /proc that counts the uid's tasks. It is off by default
    because only a thread that has already failed needs the number, and a mapping error does
    not.
    """
    fields = status_fields(pid)
    space = _limit_kb(resource.RLIMIT_AS)
    room = Headroom(
        maps_used=maps_used(pid),
        maps_limit=map_limit(),
        address_space_left_kb=-1 if space < 0 else max(0, space - fields["VmSize"]),
        data_limit_kb=data_limit_kb(),
        mem_available_kb=mem_available_kb(),
        data_used_kb=fields.get("VmData", 0),
        nproc_soft=nproc_limit(),
    )
    return room.with_tasks() if tasks else room

The verdict, and the budget

The second file turns a failure into a name. diagnose takes the exception, the call that made it, the readings and the size that was asked for, and answers one of the four walls – the mapping count, the address space, the data limit or the process count – or undetermined when none of them is spent, which is not a claim that the host ran out of memory. It also says when the failure was not an allocation at all, and it does not read a field the reading never took: a None data limit or task count is not treated as unlimited, it is simply unavailable. MappingBudget is the pre-flight version: it holds a budget of rows, because the ceiling counts rows and one map costs one whatever its size, and it reads the process once, when the first map is asked for, then counts the rows it has added itself. It goes back to the kernel only when that count is within MAP_SLIP rows of the ceiling, near enough that only a fresh read can say what is left – so a budget of ten thousand maps stays linear instead of re-reading a maps file that has grown by every row it has taken.

"""Name the limit behind a failed allocation, and refuse one you can see coming.

ENOMEM is one number for walls that have nothing to do with free memory: the mapping ceiling, an
address-space limit, a data limit, and - for the thread and fork messages this page covers - a
process count. The exception alone cannot tell them apart; the call that failed, the size it
asked for, and the process's own numbers can. When none of those four fits, the answer is
``undetermined``: no limit this guard can read was spent, which is not the same as saying the
host ran out of memory.
"""
from __future__ import annotations

import errno
import mmap
from enum import Enum
from typing import Callable

from .limits import PAGE, Headroom, headroom, map_room


class Limit(Enum):
    MAP_COUNT = "vm.max_map_count"
    ADDRESS_SPACE = "RLIMIT_AS"
    DATA = "RLIMIT_DATA"
    PROCESSES = "RLIMIT_NPROC"
    UNDETERMINED = "undetermined"
    UNKNOWN = "not an allocation failure"


class Exhausted(RuntimeError):
    """Refused before the kernel had to: the numbers are attached for the log line."""

    def __init__(self, limit: Limit, message: str, **numbers: int):
        super().__init__(f"{limit.value}: {message}")
        self.limit = limit
        self.numbers = numbers


# Distances, not theorems. Each is the gap the walls this page measures leave, and the tests
# that drive those walls - memguard/tests/test_walls.py - fail here when the host disagrees.
MAP_SLIP = 16             # rows: a refusal this close to the ceiling is the ceiling
CLOSE_ROOM_KB = 64 * 1024  # address space: less than this left is the address-space limit
NPROC_SLIP = 0            # tasks: RLIMIT_NPROC counts every task, so none to spare is spent


def diagnose(exc: BaseException, call: str, room: Headroom | None = None,
             length: int | None = None) -> Limit:
    """The limit behind one failure, judged by the call, the readings and the request.

    ``call`` is the surface that failed: ``"mmap"``, ``"alloc"``, ``"thread"`` or ``"fork"``.
    A thread failure carries no errno of its own, a MemoryError carries none at all, and an
    OSError of 12 is the same number for three walls - which is why the call is an argument.

    ``length`` is what the failed call asked for. The data limit needs it: a data limit is only
    the answer when the request does not fit what is left of it, and without a length it can be
    named only once it is already spent. A limit that the reading never took is ``None`` there,
    and ``None`` is not read as unlimited: the ``map_room`` reading carries neither the data
    limit nor the task count, so a failure judged by it can be named only by the rows, the
    address space or - for a thread - the count this function reads itself. A cheap reading that
    did not look at a limit can never make that limit a verdict.

    Two causes of a failed thread are not readable from here - the kernel-wide ``threads-max``
    and a cgroup's ``pids.max`` - so a thread failure with neither the address space nor
    ``RLIMIT_NPROC`` near its edge answers ``UNDETERMINED``. That answer means no limit this
    guard can read was spent, not that the host was out of RAM. The task count is read here, on
    that path only: it costs a pass over /proc and no other verdict needs it. The count is also
    what a container and a ``hidepid`` mount can hide, and ``RLIMIT_NPROC`` is not enforced at
    all for root, so the process-count verdict is the one to distrust outside a plain host.
    """
    room = headroom() if room is None else room
    if call == "fork" and isinstance(exc, OSError) and exc.errno == errno.EAGAIN:
        return Limit.PROCESSES
    if isinstance(exc, RuntimeError) and "thread" in str(exc):
        # The stack is mapped before the task is created, so a tight address space is asked
        # first; the task count is read only after that has been ruled out.
        if 0 <= room.address_space_left_kb <= CLOSE_ROOM_KB:
            return Limit.ADDRESS_SPACE
        tasks_left = room.with_tasks().nproc_left()
        if tasks_left is not None and 0 <= tasks_left <= NPROC_SLIP:
            return Limit.PROCESSES
        return Limit.UNDETERMINED
    if isinstance(exc, OSError) and exc.errno not in (None, errno.ENOMEM):
        return Limit.UNKNOWN
    if not isinstance(exc, (OSError, MemoryError)):
        return Limit.UNKNOWN
    # An allocation can hit either the mapping ceiling (CPython maps large blocks itself) or a
    # tight address space, so those two are asked first, whatever the call was.
    if room.maps_left() <= MAP_SLIP:
        return Limit.MAP_COUNT
    if 0 <= room.address_space_left_kb <= CLOSE_ROOM_KB:
        return Limit.ADDRESS_SPACE
    data_left = room.data_left_kb()
    if (room.data_limit_kb is not None and room.data_limit_kb >= 0 and data_left is not None
            and (data_left <= 0 or (length is not None and length > data_left * 1024))):
        return Limit.DATA
    return Limit.UNDETERMINED


class MappingBudget:
    """Map within a row budget you chose, so the ceiling is never the thing that says no.

    The ceiling counts rows, and one map costs it one row whatever its length: a 4 KiB page and
    a 256 MiB region are both a single row. The budget counts rows for that reason. It takes
    ``map_room`` once, when the first map is asked for, and afterwards counts the rows it has
    added itself; it goes back to the kernel only when that count comes within ``MAP_SLIP``
    rows of the ceiling, near enough that only a fresh read can say. The reading it would
    otherwise repeat is the row count of this process's own maps file, which grows with every
    row, so reading before every map would make a budget of ten thousand maps quadratic. Read
    once and project, and ten thousand maps cost ten thousand appends and a handful of reads.
    Every mapping the budget takes is closed when the block ends.
    """

    def __init__(self, rows: int, readings: Callable[[], Headroom] = map_room):
        if rows < 1:
            raise ValueError("a budget of at least one row is required")
        self.rows = rows
        self.readings = readings
        self._taken: list[mmap.mmap] = []
        self._room: Headroom | None = None
        self._rows_at_read = 0
        self._taken_at_read = 0

    def __enter__(self) -> "MappingBudget":
        return self

    def __exit__(self, *exc_info: object) -> bool:
        self.close()
        return False

    def __len__(self) -> int:
        return len(self._taken)

    def bytes_mapped(self) -> int:
        return sum(len(mapping) for mapping in self._taken)

    def _rebase(self) -> None:
        """Take one reading and remember the rows it saw, so the next maps can be counted."""
        self._room = self.readings()
        self._rows_at_read = self._room.maps_used
        self._taken_at_read = len(self._taken)

    def _projected(self) -> tuple[int, int]:
        """Rows this process holds now and the space left, without a read per map."""
        if self._room is None:
            self._rebase()
        assert self._room is not None
        used = self._rows_at_read + (len(self._taken) - self._taken_at_read)
        if self._room.maps_limit - used <= MAP_SLIP:
            self._rebase()
            used = self._rows_at_read
        space = self._room.address_space_left_kb
        if space >= 0:
            space = max(0, space - self.bytes_mapped() // 1024)
        return used, space

    def map(self, length: int = PAGE) -> mmap.mmap:
        if length < 1:
            raise ValueError("length must be positive")
        if len(self._taken) + 1 > self.rows:
            raise Exhausted(Limit.MAP_COUNT, f"the budget of {self.rows} rows is spent",
                            taken=len(self._taken), budget=self.rows)
        used, space = self._projected()
        assert self._room is not None
        left = max(0, self._room.maps_limit - used)
        if left < 1:
            raise Exhausted(Limit.MAP_COUNT, "the process has no row left to map with",
                            left=left, used=used, ceiling=self._room.maps_limit)
        if 0 <= space * 1024 < length:
            raise Exhausted(Limit.ADDRESS_SPACE, "the map does not fit the address space left",
                            wanted_kb=length // 1024, left_kb=space)
        mapping = mmap.mmap(-1, length)
        self._taken.append(mapping)
        return mapping

    def close(self) -> None:
        while self._taken:
            self._taken.pop().close()

The verdicts below were produced by driving the module into each wall on this host, five times per wall. Every run named the same limit: a classification that flips between two answers is worse than none.

The wall that was arrangedThe exceptionWhat diagnose answeredRuns
Pages mapped until the kernel refusedOSError, errno 12vm.max_map_count5/5
RLIMIT_AS with 1,536 KiB left, map 2 MiBOSError, errno 12RLIMIT_AS5/5
RLIMIT_DATA: VmData + 8 MiB limit, 64 MiB private mappingOSError, errno 12RLIMIT_DATA5/5
RLIMIT_DATA = VmData + 8 MiB, allocate 64 MiBMemoryErrorRLIMIT_DATA5/5
RLIMIT_AS with 1,536 KiB left, start a threadRuntimeErrorRLIMIT_AS5/5
RLIMIT_NPROC at the uid’s task count, start a threadRuntimeErrorRLIMIT_NPROC5/5
RLIMIT_NPROC lowered, then forkBlockingIOError, errno 11RLIMIT_NPROC5/5
Pages mapped until the kernel refused, then allocate 16 MiBMemoryErrorvm.max_map_count5/5
RLIMIT_AS with 1,536 KiB left, allocate 4 MiBMemoryErrorRLIMIT_AS5/5
Table 13: nine failures, nine verdicts, five runs each. The exception alone names none of them; the call, the request and the readings name all nine.

Two of those verdicts rest on a distance rather than a theorem, and the distances should be read as what they are. MAP_SLIP treats a refusal within 16 rows of the ceiling as the ceiling, and CLOSE_ROOM_KB treats less than 64 MiB of address space as that limit; both are the gaps these walls left here, chosen so the nine arms above land on the right answer. The tests in the appendix do not trust them on this host’s word: test_walls.py lowers a real limit or fills the real ceiling in a child process and asks diagnose for the verdict there, so a host whose walls sit elsewhere fails the suite instead of publishing a wrong name. That file also keeps the suite runnable on a host that is not this one: the two limits it can set are set relative to the child’s own VmSize and VmData, its task-count test reads the uid’s count with relative offsets rather than fixed numbers, and it skips the process count when the suite runs as root, where RLIMIT_NPROC has no effect.

Using it

The example walks a process to its own ceiling, prints the readings before and after, names the wall through diagnose and then frees one page to show the room coming back. With no argument it stops after two thousand pages, which is safe to run on a production host; --full walks to the ceiling and is what produced the figures in Section 3.

"""Walk this process to its mapping ceiling, name the wall, then free one page and retry.

    python3 ceiling_demo.py            # stops after 2,000 pages
    python3 ceiling_demo.py --full     # walks all the way to vm.max_map_count

The demo never leaves a mapping behind and never touches a file.
"""
from __future__ import annotations

import mmap
import sys

from memguard import Headroom, diagnose, headroom


def walk(cap: int = 2000) -> tuple[int, BaseException | None, Headroom]:
    room = headroom()
    print(f"before: {room.maps_used} mappings of {room.maps_limit}, "
          f"{room.maps_left()} left, {room.mem_available_kb} kB available")
    taken: list[mmap.mmap] = []
    failure: BaseException | None = None
    while len(taken) < cap:
        try:
            taken.append(mmap.mmap(-1, 4096))
        except OSError as exc:
            failure = exc
            break
    now = headroom()
    print(f"mapped {len(taken)} pages; the process now holds {now.maps_used} mappings")
    if failure is not None or len(taken) >= cap:
        print(f"stopped with {failure or 'the cap reached'}")
    if failure is not None:
        print(f"the wall was {diagnose(failure, 'mmap', now).value}")
        taken.pop().close()
        try:
            again = mmap.mmap(-1, 4096)
        except OSError as exc:
            print(f"one page freed and the next map still failed: errno {exc.errno}")
        else:
            print("one page freed and the next map succeeded")
            again.close()
    for mapping in taken:
        mapping.close()
    print(f"after: {headroom().maps_used} mappings")
    return len(taken), failure, now


def main() -> int:
    cap = 65536 if "--full" in sys.argv else 2000
    walk(cap)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Its first run printed:
before: 61 mappings of 65530, 65469 left, 392924 kB available
mapped 2000 pages; the process now holds 2061 mappings
stopped with the cap reached
after: 61 mappings

The full walk, with --full, printed:
before: 61 mappings of 65530, 65469 left, 391456 kB available
mapped 65465 pages; the process now holds 65532 mappings
stopped with [Errno 12] Cannot allocate memory
the wall was vm.max_map_count
one page freed and the next map succeeded
after: 67 mappings

Why does the guard refuse instead of retrying?

Because the limits it names do not move on their own. A mapping count, an address space and a data limit stay where they are until something is released or the limit is changed, so a retry against them repeats the same refusal and hides the reason. The budget refuses once, with the row count and the ceiling attached, and leaves the decision – map fewer regions, release what is held, or raise the limit – to the caller who knows which of the three is negotiable.

8. Where To Go Next

If your refusal is not this one, the neighbouring runbooks cover the numbers that look like it from a dashboard, with the same method.

On a host you own, three changes are worth making. Raise vm.max_map_count only if the process legitimately needs the regions, and raise it in the sysctl configuration rather than at runtime. Give the unit an explicit LimitAS you can explain instead of one inherited from a template. And put the row count in the metrics you already scrape, because a count that climbs for hours before failing is a bug no traceback shows.

Questions This Page Answers

Does ENOMEM mean the machine is out of RAM?

No. On this host the first refusal arrived with 354 MiB available, and the wall was the process’s mapping count rather than memory. Treat 12 as a statement that an allocation was refused, then find out which wall.

Why does it say Cannot allocate memory when free memory is plentiful?

Three walls answer with that number: the mapping count, an address-space limit and a data limit. A fourth, the uid’s process count, arrives as 11 at a fork and as RuntimeError at a thread, so a 12 never means the process count. What is left – memory that is really gone – looks the same from inside the process, which is why the guard’s fallback is undetermined rather than a claim about RAM. The message names the failure, not the cause.

How do I see how many mappings a process holds?

Count the rows in /proc/<pid>/maps and compare with /proc/sys/vm/max_map_count. One row is one region, and an anonymous 4 KiB mapping made with Python’s default MAP_SHARED is one row, so a default-flag loop that maps per request burns the ceiling a page at a time.

Does one mmap call always cost one row?

No. The kernel merges neighbouring regions whose attributes match, so adjacent private mappings can share one row, and one guard page splits a region into three. Python’s default mapping is shared, which does not merge, so a row count only follows the number of calls when the calls are shared.

Can I raise vm.max_map_count for just one process?

No. It is a global sysctl; a per-process change would need a different kernel interface. The per-process answer is to need fewer regions, which is what the budget in Section 7 is for.

Adding RAM made no difference. Why?

Because the wall was a count or a limit, not memory. A mapping count, an address-space limit and a data limit are all fixed numbers that more RAM does not move. Read them before resizing the host.

Why did starting a thread raise RuntimeError instead of errno 12?

A thread begins by mapping its stack, and that failure reaches Python as RuntimeError: can't start new thread, with no errno attached. Four walls produce it: a tight address space, a spent RLIMIT_NPROC, the kernel’s threads-max and a cgroup’s pids.max. Under a tight address space an explicit smaller stack is what makes the call work; under a spent task count only fewer tasks help.

Why does my private mapping fail when a shared one worked?

Since Linux 4.7 a writable private anonymous mapping counts against RLIMIT_DATA, and a shared mapping does not. With the limit 8 MiB above the process’s own VmData, a 4 KiB and a 7 MiB private request are accepted, 16 MiB and 64 MiB are refused, and the same 64 MiB is accepted with the other flag – which is why the flag belongs in the incident notes.

Why does the guard answer undetermined instead of out of memory?

Because it cannot read that answer. undetermined means none of the four limits it measures was spent: the mapping count has rows left, the address space is unlimited or wide, the request fits what is left of the data limit, and the task count has room. A field the reading never took, such as the data limit in the cheap map_room reading, cannot be the answer either: it is None, not a limit with room to spare. That is the state genuine memory pressure leaves behind, and so is a limit the guard cannot read – a cgroup’s pids.max, another container’s share of the host, or a host that really is full. Naming RAM would be a guess in two of those three cases.

Is a 12 ever temporary?

Yes, when something is released before the retry. In this page’s ceiling run, freeing one page made the next map succeed five times out of five. A retry without a release repeats the refusal and delays the diagnosis.

What does exit code 137 mean?

The process was killed by signal 9, which is how an OOM kill reaches a shell. It is described here rather than measured, because this host has no cgroup v2 mount; the evidence lives in the cgroup’s memory.events, not in a traceback.

Which number should I check first?

The mapping count, then the address space, then the data limit, then the task count, then available memory. The first four cost one read each, are fixed numbers that do not move on their own, and explain most refusals that look like memory pressure.

TechBobby Engineering writes runbooks from failures it has seen. The package is printed in Section 7 and its three test files in the appendix, so the tests can be run from this page; the numbered probes that produced the figures are not printed, only their records, and the tables that count runs say how many each row took. The host is described in Section 1, so the size of every claim is visible even where the probe is not.

Appendix: the tests this page ships

All three files are printed whole below: they are what the 56 passing tests ran from, and the part of this page a reader can run without the probes. The last of them drives the real limits, so the distances the guard uses are checked against this host’s walls rather than believed.

Readings: memguard/tests/test_limits.py
"""The readings must be the kernel's own: compare them with an independent count."""
from __future__ import annotations

import mmap
import os
import resource
import statistics
import threading

import pytest

from memguard import limits


def _task_samples(times: int = 3) -> int:
    """The median of a few counts: another process of this uid may start or exit as we read."""
    return int(statistics.median([limits.uid_tasks() for _ in range(times)]))


def test_status_fields_are_the_kernels_numbers() -> None:
    reported = limits.status_fields()
    independent: dict[str, int] = {}
    for line in (limits.PROC / "self" / "status").read_text().splitlines():
        name, _, rest = line.partition(":")
        parts = rest.split()
        if parts and parts[0].isdigit():
            independent[name] = int(parts[0])
    assert reported["VmSize"] == independent["VmSize"] > 0
    assert reported["VmData"] == independent["VmData"] > 0
    assert reported["Threads"] == independent["Threads"] >= 1
    assert reported["Uid"] == independent["Uid"] == os.getuid()


def test_a_new_mapping_appears_as_one_more_row() -> None:
    before = limits.maps_used()
    mapping = mmap.mmap(-1, limits.PAGE)
    try:
        assert limits.maps_used() == before + 1
    finally:
        mapping.close()
    assert limits.maps_used() == before


def test_the_ceiling_is_a_system_setting_not_a_guess() -> None:
    assert limits.map_limit() == int(
        (limits.PROC / "sys" / "vm" / "max_map_count").read_text().strip())
    assert limits.map_limit() > 100


def test_available_memory_is_read_from_meminfo() -> None:
    fields = {}
    for line in (limits.PROC / "meminfo").read_text().splitlines():
        name, _, rest = line.partition(":")
        fields[name] = int(rest.split()[0])
    assert limits.mem_available_kb() == fields["MemAvailable"] > 0


def test_an_unlimited_address_space_reads_as_minus_one() -> None:
    room = limits.headroom()
    if room.address_space_left_kb == -1:
        assert room.data_limit_kb is not None and room.data_limit_kb >= -1
    else:
        assert room.address_space_left_kb >= 0


def test_headroom_counts_pages_left_the_way_the_kernel_does() -> None:
    room = limits.headroom()
    assert room.maps_left() == room.maps_limit - room.maps_used
    assert room.pages_for(limits.PAGE) == 1
    assert room.pages_for(limits.PAGE + 1) == 2
    assert room.pages_for(4 * 1024 * 1024) == 1024


def test_the_data_fields_are_the_kernels_data_accounting() -> None:
    room = limits.headroom()
    soft, _ = resource.getrlimit(resource.RLIMIT_DATA)
    assert room.data_used_kb == limits.vm_data_kb() > 0
    assert room.data_limit_kb == (-1 if soft == resource.RLIM_INFINITY else soft // 1024)
    left = -1 if room.data_limit_kb < 0 else room.data_limit_kb - room.data_used_kb
    assert room.data_left_kb() == left


def test_a_map_room_reads_no_further_than_a_map_can_spend() -> None:
    room = limits.map_room()
    assert room.maps_used == limits.maps_used()
    assert room.maps_limit == limits.map_limit()
    assert room.nproc_used is None
    assert room.nproc_left() is None
    assert room.data_limit_kb is None
    assert room.mem_available_kb is None
    assert room.data_used_kb is None


def test_an_unread_limit_is_none_and_never_the_unlimited_marker() -> None:
    """-1 is a limit that was read and has no ceiling; a field not read must not copy it."""
    cheap = limits.map_room()
    assert cheap.data_limit_kb is None and cheap.nproc_soft is None
    assert cheap.data_left_kb() is None
    assert cheap.nproc_left() is None
    full = limits.headroom()
    assert full.data_limit_kb is not None and full.nproc_soft is not None
    assert isinstance(full.data_limit_kb, int) and isinstance(full.nproc_soft, int)


def test_an_unlimited_data_limit_reads_as_minus_one_left() -> None:
    unlimited = limits.Headroom(maps_used=10, maps_limit=100, address_space_left_kb=-1,
                                data_limit_kb=-1, data_used_kb=4096)
    assert unlimited.data_left_kb() == -1
    unlimited_nproc = limits.Headroom(maps_used=10, maps_limit=100, address_space_left_kb=-1,
                                      nproc_soft=-1)
    assert unlimited_nproc.nproc_left() == -1


def test_the_full_reading_carries_the_data_and_the_free_memory() -> None:
    room = limits.headroom()
    assert room.mem_available_kb == limits.mem_available_kb() > 0
    assert room.data_used_kb == limits.vm_data_kb() > 0
    assert room.nproc_used is None, "the task count is a pass over /proc and is off by default"


def test_the_task_count_includes_this_process_and_its_threads() -> None:
    own = len(os.listdir("/proc/self/task"))
    assert limits.uid_tasks() >= own >= 1
    gate = threading.Event()
    threads = [threading.Thread(target=gate.wait) for _ in range(4)]
    before = _task_samples()
    for thread in threads:
        thread.start()
    try:
        after = _task_samples()
        assert after >= before + 1, (before, after)
        assert limits.uid_tasks() >= len(os.listdir("/proc/self/task"))
    finally:
        gate.set()
        for thread in threads:
            thread.join()


def test_with_tasks_fills_the_count_the_cheap_reading_left_out() -> None:
    room = limits.map_room().with_tasks()
    assert room.nproc_used == limits.uid_tasks()
    assert room.maps_used >= 1
    assert room.maps_limit == limits.map_limit()
    assert room.with_tasks() == room


def test_the_task_limit_is_the_one_the_kernel_reports() -> None:
    soft, _ = resource.getrlimit(resource.RLIMIT_NPROC)
    room = limits.headroom(tasks=True)
    assert room.nproc_soft == limits.nproc_limit()
    assert room.nproc_soft == (-1 if soft == resource.RLIM_INFINITY else soft)
    if room.nproc_soft < 0:
        assert room.nproc_left() == -1
    else:
        assert room.nproc_left() == max(0, room.nproc_soft - limits.uid_tasks())


def test_the_reported_uid_is_this_process_account() -> None:
    assert limits.uid_tasks(os.getuid()) == limits.uid_tasks()


@pytest.mark.parametrize("pid", [0])
def test_a_missing_field_is_an_error_not_a_zero(pid: int) -> None:
    with pytest.raises(KeyError):
        limits.status_kb("VmNonsense", pid)
Verdicts and budget: memguard/tests/test_guard.py
"""Each wall gets named, and the budget refuses before the kernel has to."""
from __future__ import annotations

import errno

import pytest

from memguard import limits
from memguard.guard import (MAP_SLIP, Exhausted, Limit, MappingBudget, diagnose)


def room(**overrides: int) -> limits.Headroom:
    """A cheap reading by default: what ``map_room`` carries, and nothing it leaves out."""
    base = dict(maps_used=100, maps_limit=65530, address_space_left_kb=-1,
                data_limit_kb=None, mem_available_kb=None, data_used_kb=None,
                nproc_soft=None, nproc_used=None)
    base.update(overrides)
    return limits.Headroom(**base)


def readings(*rooms: limits.Headroom):
    """A readings callable that answers with the next Headroom each time it is asked."""
    queue = list(rooms)
    return lambda: queue.pop(0) if len(queue) > 1 else queue[0]


def enomem() -> OSError:
    return OSError(errno.ENOMEM, "Cannot allocate memory")


def test_the_four_walls_and_two_outcomes_are_the_whole_vocabulary() -> None:
    assert {limit.value for limit in Limit} == {
        "vm.max_map_count", "RLIMIT_AS", "RLIMIT_DATA", "RLIMIT_NPROC",
        "undetermined", "not an allocation failure"}


def test_an_oserror_of_twelve_at_the_ceiling_is_the_mapping_limit() -> None:
    assert diagnose(enomem(), "mmap", room(maps_used=65530 - MAP_SLIP)) is Limit.MAP_COUNT


def test_an_oserror_of_twelve_with_no_wall_in_sight_is_undetermined() -> None:
    assert diagnose(enomem(), "mmap", room()) is Limit.UNDETERMINED


def test_an_oserror_of_twelve_under_a_tight_address_space_is_that_limit() -> None:
    assert diagnose(enomem(), "mmap", room(address_space_left_kb=2048)) is Limit.ADDRESS_SPACE


def test_a_memory_error_from_an_allocation_is_the_data_limit_when_that_limit_is_spent() -> None:
    assert diagnose(MemoryError(), "alloc", room(data_limit_kb=8192, data_used_kb=8192)) \
        is Limit.DATA


def test_a_request_larger_than_the_data_left_is_the_data_limit() -> None:
    readings_now = room(data_limit_kb=8192, data_used_kb=6032)
    assert diagnose(MemoryError(), "alloc", readings_now, length=64 * 1024 * 1024) is Limit.DATA


def test_a_request_that_fits_the_data_left_is_not_blamed_on_it() -> None:
    readings_now = room(data_limit_kb=8192, data_used_kb=6032)
    assert diagnose(MemoryError(), "alloc", readings_now, length=1024) is Limit.UNDETERMINED


def test_a_memory_error_at_the_ceiling_is_the_mapping_count() -> None:
    assert diagnose(MemoryError(), "alloc", room(maps_used=65530)) is Limit.MAP_COUNT


def test_a_memory_error_under_a_tight_address_space_is_that_limit() -> None:
    assert diagnose(MemoryError(), "alloc", room(address_space_left_kb=1536)) is Limit.ADDRESS_SPACE


def test_a_memory_error_without_a_data_limit_is_undetermined() -> None:
    assert diagnose(MemoryError(), "alloc", room()) is Limit.UNDETERMINED
    assert diagnose(MemoryError(), "alloc", room(data_limit_kb=-1)) is Limit.UNDETERMINED


def test_an_unread_data_limit_is_not_mistaken_for_an_unlimited_one() -> None:
    """The cheap reading leaves the data limit None; None is not a limit with room to spare."""
    assert room().data_limit_kb is None
    assert room().data_left_kb() is None
    assert diagnose(MemoryError(), "alloc", room(), length=64 * 1024 * 1024) \
        is Limit.UNDETERMINED


def test_a_map_room_reading_judges_a_refusal_without_inventing_a_limit() -> None:
    cheap = limits.map_room()
    assert cheap.data_limit_kb is None and cheap.nproc_soft is None
    assert diagnose(enomem(), "mmap", cheap) is Limit.UNDETERMINED
    assert diagnose(MemoryError(), "alloc", cheap, length=64 * 1024 * 1024) \
        is Limit.UNDETERMINED


def test_a_thread_failure_on_a_cheap_reading_is_undetermined_not_unlimited(monkeypatch) -> None:
    monkeypatch.setattr(limits, "uid_tasks", lambda uid=None: 256)
    failure = RuntimeError("can't start new thread")
    cheap = room()
    assert cheap.nproc_soft is None
    assert cheap.with_tasks().nproc_left() is None
    assert diagnose(failure, "thread", cheap) is Limit.UNDETERMINED


def test_a_thread_that_will_not_start_is_the_address_space() -> None:
    failure = RuntimeError("can't start new thread")
    assert diagnose(failure, "thread", room(address_space_left_kb=1024)) is Limit.ADDRESS_SPACE


def test_a_thread_that_will_not_start_at_the_task_count_is_the_process_limit() -> None:
    failure = RuntimeError("can't start new thread")
    assert diagnose(failure, "thread", room(nproc_soft=256, nproc_used=256)) is Limit.PROCESSES


def test_a_thread_failure_with_one_task_to_spare_is_not_blamed_on_the_count() -> None:
    failure = RuntimeError("can't start new thread")
    assert diagnose(failure, "thread", room(nproc_soft=256, nproc_used=255)) is Limit.UNDETERMINED


def test_a_thread_failure_with_no_limit_near_is_undetermined_not_the_process_count() -> None:
    failure = RuntimeError("can't start new thread")
    assert diagnose(failure, "thread", room(nproc_soft=256, nproc_used=5)) is Limit.UNDETERMINED


def test_a_thread_failure_reads_the_task_count_only_when_no_other_wall_fits(monkeypatch) -> None:
    asked: list[int | None] = []
    monkeypatch.setattr(limits, "uid_tasks", lambda uid=None: asked.append(uid) or 256)
    failure = RuntimeError("can't start new thread")
    unread = room(nproc_soft=256, nproc_used=None)
    assert unread.nproc_left() is None
    assert diagnose(failure, "thread", unread) is Limit.PROCESSES
    assert asked == [None], "the count should be read once, on the thread path"
    assert diagnose(failure, "thread", room(nproc_soft=256, nproc_used=256)) is Limit.PROCESSES
    assert asked == [None], "a reading that already carries the count is not read again"


def test_a_mapping_failure_never_reads_the_task_count(monkeypatch) -> None:
    def forbidden(uid: int | None = None) -> int:
        raise AssertionError("a mapping failure has no use for the task count")

    monkeypatch.setattr(limits, "uid_tasks", forbidden)
    assert diagnose(enomem(), "mmap", room()) is Limit.UNDETERMINED
    cheap = limits.Headroom(maps_used=65530, maps_limit=65530, address_space_left_kb=-1)
    assert diagnose(enomem(), "mmap", cheap) is Limit.MAP_COUNT


def test_eagain_from_a_fork_is_the_process_limit() -> None:
    failure = OSError(errno.EAGAIN, "Resource temporarily unavailable")
    assert diagnose(failure, "fork", room()) is Limit.PROCESSES


def test_another_errno_is_not_blamed_on_memory() -> None:
    failure = OSError(errno.EMFILE, "Too many open files")
    assert diagnose(failure, "mmap", room()) is Limit.UNKNOWN


def test_something_that_is_not_an_allocation_failure_is_unnamed() -> None:
    assert diagnose(ValueError("bad length"), "mmap", room()) is Limit.UNKNOWN


def test_a_budget_takes_its_readings_without_walking_every_process(monkeypatch) -> None:
    def forbidden(uid: int | None = None) -> int:
        raise AssertionError("the budget must not pass over /proc for every map")

    monkeypatch.setattr(limits, "uid_tasks", forbidden)
    with MappingBudget(4) as budget:
        for _ in range(4):
            budget.map()
    assert len(budget) == 0


def test_the_budget_maps_and_closes_what_it_took() -> None:
    before = limits.maps_used()
    with MappingBudget(4) as budget:
        first = budget.map()
        second = budget.map(limits.PAGE * 3)
        assert first is not second
        assert len(budget) == 2
        assert limits.maps_used() >= before + 2
    assert limits.maps_used() == before


def test_the_budget_refuses_the_row_that_would_exceed_it() -> None:
    budget = MappingBudget(2, readings=readings(room()))
    with budget:
        budget.map()
        budget.map()
        with pytest.raises(Exhausted) as caught:
            budget.map()
    assert caught.value.limit is Limit.MAP_COUNT
    assert caught.value.numbers["taken"] == 2


def test_a_large_mapping_costs_one_row_not_a_thousand() -> None:
    budget = MappingBudget(1, readings=readings(room()))
    with budget:
        mapping = budget.map(4 * 1024 * 1024)
        assert len(mapping) == 4 * 1024 * 1024
        assert len(budget) == 1
        assert budget.bytes_mapped() == 4 * 1024 * 1024
        with pytest.raises(Exhausted):
            budget.map()


def test_the_budget_reads_the_process_once_for_a_short_run() -> None:
    calls: list[int] = []

    def counting() -> limits.Headroom:
        calls.append(1)
        return room()

    with MappingBudget(50, readings=counting) as budget:
        for _ in range(50):
            budget.map()
        assert len(budget) == 50
    assert calls == [1], "one reading, and the rows it took counted from there"


def test_the_budget_reads_again_only_when_the_ceiling_is_near() -> None:
    """The row count is a file whose size grows with the rows, so it is not read per map."""
    calls: list[int] = []

    def counting() -> limits.Headroom:
        calls.append(1)
        return room(maps_used=120 if len(calls) > 1 else 100, maps_limit=120)

    budget = MappingBudget(64, readings=counting)
    with budget:
        for _ in range(4):
            budget.map()
        assert len(budget) == 4 and calls == [1]
        with pytest.raises(Exhausted) as caught:
            budget.map()
    assert caught.value.limit is Limit.MAP_COUNT
    assert caught.value.numbers["left"] == 0
    assert len(calls) == 2, "the ceiling was within MAP_SLIP rows, so the kernel was read again"


def test_the_budget_counts_its_own_rows_between_readings() -> None:
    budget = MappingBudget(8, readings=readings(room(maps_used=100, maps_limit=65530)))
    with budget:
        for index in range(5):
            budget.map()
            used, space = budget._projected()
            assert used == 100 + index + 1
            assert space == -1
    assert len(budget) == 0


def test_the_budget_refuses_a_map_wider_than_the_space_left() -> None:
    budget = MappingBudget(64, readings=readings(room(address_space_left_kb=4)))
    with budget:
        with pytest.raises(Exhausted) as caught:
            budget.map(limits.PAGE * 8)
    assert caught.value.limit is Limit.ADDRESS_SPACE
    assert caught.value.numbers["left_kb"] == 4


def test_the_budget_refuses_a_process_with_no_row_left() -> None:
    budget = MappingBudget(64, readings=readings(room(maps_used=65530)))
    with budget:
        with pytest.raises(Exhausted) as caught:
            budget.map(limits.PAGE * 4)
    assert caught.value.limit is Limit.MAP_COUNT
    assert caught.value.numbers["left"] == 0


def test_a_budget_of_zero_rows_is_a_programming_error() -> None:
    with pytest.raises(ValueError):
        MappingBudget(0)


def test_a_zero_length_map_is_a_programming_error() -> None:
    with pytest.raises(ValueError):
        MappingBudget(1, readings=readings(room())).map(0)


def test_the_refusal_reads_as_the_limit_it_names() -> None:
    budget = MappingBudget(1, readings=readings(room()))
    with budget:
        budget.map()
        with pytest.raises(Exhausted) as caught:
            budget.map()
    assert str(caught.value).startswith("vm.max_map_count:")


def test_a_real_mapping_still_works_inside_a_budget() -> None:
    with MappingBudget(1) as budget:
        mapping = budget.map(limits.PAGE)
        mapping.write(b"12")
        assert mapping[:2] == b"12"


def test_the_exhausted_error_is_a_runtime_error_so_old_handlers_see_it() -> None:
    assert issubclass(Exhausted, RuntimeError)
    assert not issubclass(Exhausted, OSError)
The real walls: memguard/tests/test_walls.py
"""Four real walls, driven and named in a child process, so a verdict is not a guess.

Every other test in this package feeds ``diagnose`` a made-up ``Headroom``, which proves the
arithmetic and nothing about the kernel. These tests lower a real limit or fill the real ceiling
in a child, catch the real exception, and ask for the verdict there: if a host's walls stop
matching the page's distances, this file fails.

Two of the walls are set relative to the child's own numbers, because an absolute figure means
different things in different interpreters: the address space is measured from that child's
``VmSize`` and the data limit from its ``VmData``, so a host that spends more before the first
line changes nothing here.

One wall cannot be driven as root: the kernel does not enforce ``RLIMIT_NPROC`` for a process
with ``CAP_SYS_RESOURCE``, so the task-count test skips itself there instead of failing on a
limit that has no effect.
"""
from __future__ import annotations

import ctypes
import json
import mmap
import os
import pathlib
import resource
import subprocess
import sys
import threading
import time

import pytest

from memguard import headroom, limits
from memguard.guard import Limit, diagnose

PAGE = 4096
PROT_READ, PROT_WRITE = 0x1, 0x2
MAP_PRIVATE, MAP_ANONYMOUS = 0x02, 0x20
MIB = 1024 * 1024

libc = ctypes.CDLL("libc.so.6", use_errno=True)
libc.mmap.restype = ctypes.c_void_p
libc.mmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int,
                      ctypes.c_int, ctypes.c_long]


def limit_bytes(which: int) -> int:
    """One rlimit in bytes, as the kernel holds it."""
    soft, _ = resource.getrlimit(which)
    return -1 if soft == resource.RLIM_INFINITY else soft


def limited(which: int, soft: int) -> None:
    _, hard = resource.getrlimit(which)
    resource.setrlimit(which, (soft, hard))


def wall_map_count() -> dict:
    """Fill the real mapping ceiling, then diagnose the refusal."""
    held = []
    try:
        while True:
            held.append(mmap.mmap(-1, PAGE))
    except OSError as exc:
        room = headroom()
        return {"errno": exc.errno, "limit": diagnose(exc, "mmap", room).value,
                "maps_left": room.maps_left()}
    finally:
        for mapping in held:
            mapping.close()


def wall_address_space() -> dict:
    """A 2 MiB map with 1 MiB of address space left."""
    limited(resource.RLIMIT_AS, limits.vm_size_kb() * 1024 + MIB)
    try:
        mmap.mmap(-1, 2 * MIB)
    except OSError as exc:
        room = headroom()
        return {"errno": exc.errno, "limit": diagnose(exc, "mmap", room).value,
                "as_left_kb": room.address_space_left_kb}
    return {"errno": 0, "limit": "mapped", "as_left_kb": -1}


def wall_data() -> dict:
    """A 64 MiB private mapping under a limit 8 MiB above this child's own VmData."""
    before = limits.vm_data_kb()
    limited(resource.RLIMIT_DATA, (before + 8 * 1024) * 1024)
    address = libc.mmap(None, 64 * MIB, PROT_READ | PROT_WRITE,
                        MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
    room = headroom()
    if address is None or address == ctypes.c_void_p(-1).value:
        error = OSError(ctypes.get_errno(), "Cannot allocate memory")
        return {"errno": error.errno,
                "limit": diagnose(error, "mmap", room, length=64 * MIB).value,
                "data_before_kb": before, "data_limit_kb": room.data_limit_kb,
                "data_left_kb": room.data_left_kb()}
    return {"errno": 0, "limit": "mapped", "data_before_kb": before,
            "data_limit_kb": room.data_limit_kb, "data_left_kb": -1}


def wall_processes() -> dict:
    """A thread with the uid's task count already at RLIMIT_NPROC."""
    tasks = len(os.listdir("/proc/self/task"))
    owned = limits.uid_tasks()
    limited(resource.RLIMIT_NPROC, owned)
    thread = threading.Thread(target=time.sleep, args=(0.01,))
    try:
        thread.start()
    except RuntimeError as exc:
        room = headroom(tasks=True)
        return {"tasks": tasks, "uid_tasks": owned,
                "limit": diagnose(exc, "thread", room).value,
                "nproc_left": room.nproc_left()}
    thread.join()
    return {"tasks": tasks, "uid_tasks": owned, "limit": "started", "nproc_left": -1}


ARMS = {"map_count": wall_map_count, "address_space": wall_address_space,
        "data": wall_data, "processes": wall_processes}


ROOT = pathlib.Path(__file__).resolve().parents[2]


def run(arm: str) -> dict:
    environment = {**os.environ,
                   "PYTHONPATH": str(ROOT) + os.pathsep + os.environ.get("PYTHONPATH", "")}
    completed = subprocess.run([sys.executable, __file__, arm], capture_output=True, text=True,
                               timeout=300, env=environment)
    line = next((text for text in completed.stdout.splitlines()
                 if text.startswith("@@WALL@@")), None)
    assert line, completed.stderr[-800:]
    return json.loads(line[len("@@WALL@@"):])


def test_the_real_mapping_ceiling_is_named() -> None:
    answer = run("map_count")
    assert answer["errno"] == 12
    assert answer["limit"] == Limit.MAP_COUNT.value


def test_the_real_address_space_limit_is_named() -> None:
    answer = run("address_space")
    assert answer["errno"] == 12
    assert answer["limit"] == Limit.ADDRESS_SPACE.value


def test_the_real_data_limit_is_named_for_a_private_mapping() -> None:
    answer = run("data")
    assert answer["errno"] == 12
    assert answer["limit"] == Limit.DATA.value
    assert answer["data_limit_kb"] == answer["data_before_kb"] + 8 * 1024


@pytest.mark.skipif(os.geteuid() == 0,
                    reason="root (CAP_SYS_RESOURCE) ignores RLIMIT_NPROC")
def test_the_real_task_limit_is_named_for_a_thread() -> None:
    answer = run("processes")
    assert answer["limit"] == Limit.PROCESSES.value
    assert answer["nproc_left"] == 0


if __name__ == "__main__":
    if len(sys.argv) == 2 and sys.argv[1] in ARMS:
        print("@@WALL@@" + json.dumps(ARMS[sys.argv[1]]()))
        raise SystemExit(0)
    raise SystemExit(pytest.main([__file__, "-q"]))

One failure per issue, with the probe behind it: Zero-Crash Python, free.


Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.