Counting References

Contents
A parent process builds a list of a million small lists, 184 MB of objects, and forks. The child never assigns to the list. It only loops over it and reads one number from each element, and when it’s done, 93 MB of the parent’s memory has been copied into the child. Reading a Python object writes to it, because every reference taken and dropped changes the object’s reference count, and the reference count lives in the object. The kernel can’t tell a reference count from data. It sees a write to a shared page and copies the page.
This post is about that first field of every object, ob_refcnt: when it makes objects die, the
references that keep them alive without anyone seeing them, the second garbage collector that exists
because counting can’t free cycles, and what both of them cost. The last part measures the copying
above on Ubuntu 18.04’s own kernel, and Python 3.7’s new gc.freeze(), which fixes half of it.
This is Part 4 of a series on the CPython runtime. Part 1
introduced ob_refcnt and the cycle collector’s header, and Part 3
used the trashcan that makes deep frees safe. It is written for Python programmers who have written a
little C. Everything here ran on CPython 3.7.0, built from its tag with Ubuntu 18.04’s gcc 7.3.0, in
a virtual machine booting 18.04’s release kernel. The note at the end says exactly where and how.
The moment an object dies
Part 1 quoted Py_DECREF: decrement the count, and if it reaches zero, call the type’s
deallocator immediately. Here’s what “immediately” looks like from Python:
class Noisy:
def __init__(self, name):
self.name = name
print(" made", name)
def __del__(self):
print(" freed", self.name)
print("a = Noisy('a'); b = a")
a = Noisy("a"); b = a
print("del a")
del a
print("del b")
del b
print("a function's locals die when it returns:")
def f():
x = Noisy("x")
print(" returning")
f()
print("back in the module")
$ python3 dies.py
a = Noisy('a'); b = a
made a
del a
del b
freed a
a function's locals die when it returns:
made x
returning
freed x
back in the module
del a removes one of two references, so nothing happens. del b removes the last one, and the
object is freed during the del statement itself, before the next line runs. When f returns, its
frame is freed, which drops the frame’s references to its locals, and x goes with it, before
control is back in the module. CPython frees memory at a precise, predictable point: the decrement
that reaches zero.
That precision is CPython’s, not Python’s. The language reference says only that objects “may be garbage-collected” once unreachable, and PyPy and Jython free them whenever their tracing collectors get round to it, which can be much later or never. But programs come to rely on what CPython actually does, and the commonest case is files:
def first_line(path):
return open(path).readline() # never closed explicitly
print(first_line(__file__).strip())
print("done")
$ python3 files.py
def first_line(path):
done
$ python3 -X dev files.py
files.py:2: ResourceWarning: unclosed file <_io.TextIOWrapper name='files.py' mode='r' encoding='UTF-8'>
return open(path).readline() # never closed explicitly
def first_line(path):
done
The file object is a temporary. Its count drops to zero as soon as readline() returns, the
deallocator closes the file descriptor, and on CPython that’s the end of it. Python 3.7’s new
development mode, -X dev, turns on the warnings that are normally hidden, and shows that the
interpreter noticed: a file was closed by its deallocator instead of by the program. On an
implementation without reference counting, the descriptor stays open until a collection happens,
and a loop that opens many files that way runs out of descriptors. The code works because of a C
implementation detail, and with exists to make it not depend on one.
References nobody sees
If freeing happens when the last reference goes, then whatever holds a reference decides when. Some holders are not obvious:
import gc, sys
class Big:
def __del__(self):
print(" Big freed")
def fail():
big = Big()
raise ValueError("boom")
try:
fail()
except ValueError as e:
err = e
print("caught; is Big still alive?")
frames = []
tb = err.__traceback__
while tb:
frames.append(tb.tb_frame.f_code.co_name)
tb = tb.tb_next
print(" the exception's traceback holds frames:", frames)
print(" ... and fail()'s frame holds its locals:", list(err.__traceback__.tb_next.tb_frame.f_locals))
del err
print("after del err")
$ python3 hidden.py
caught; is Big still alive?
the exception's traceback holds frames: ['<module>', 'fail']
... and fail()'s frame holds its locals: ['big']
Big freed
after del err
fail() returned by raising, and normally its frame would have been freed with its locals. But a
traceback is a linked list of traceback objects, each holding a reference to a frame, and each
frame holds references to its locals. The exception holds its traceback, and err holds the
exception. So keeping an exception keeps every frame it passed through, and everything those frames
referred to, alive. Here that’s one Big. In a real program it can be a request, a database
connection, or a buffer of a hundred megabytes. del err dropped the chain and Big went at once.
This is why Python 3 deletes the name in except ValueError as e: at the end of the block. Without
that, e → traceback → this very frame → e would be a reference cycle, and counting alone could
never free it. The same goes for anything kept from sys.exc_info(), a logged exception that a
handler stores, or a closure that captures a large local. The language looks the same either way.
Only the lifetime of the memory changes.
Cycles: the second collector
A cycle is the case that reference counting can’t handle by construction. Two objects that point at each other each have a count of at least one, forever, even after nothing else can reach them. CPython has a second, separate collector for exactly that:
import gc
class Node:
def __init__(self, name):
self.name = name
self.other = None
def __del__(self):
print(" freed", self.name)
print("gc.get_threshold() =", gc.get_threshold())
print("gc.get_count() =", gc.get_count())
a, b = Node("a"), Node("b")
a.other, b.other = b, a # a cycle: each keeps the other's count at 1
del a, b
print("after del a, b: nothing freed yet")
print("gc.collect() found", gc.collect(), "unreachable objects")
print("gc.garbage =", gc.garbage)
$ python3 cycles.py
gc.get_threshold() = (700, 10, 10)
gc.get_count() = (615, 9, 0)
after del a, b: nothing freed yet
freed a
freed b
gc.collect() found 4 unreachable objects
gc.garbage = []
After del a, b, nothing can reach the two nodes, but neither was freed: each still holds the
other. gc.collect() found four unreachable objects, the two nodes and their two instance __dict__s,
called their __del__ methods, and freed them. gc.garbage, where objects the collector couldn’t
free used to end up, is empty. Since Python 3.4 (PEP 442), objects with __del__ in a cycle are
finalized and freed like any others. Before that, they were put in gc.garbage and leaked.
The cycle collector on six objects · illustration
One generation: A is named by a frame; B and C form a cycle that A leads to; D and E form a cycle that nothing outside leads to, and E points at F.
The collector finds that D, E and F are unreachable, although each has a reference count of 1, and that A, B and C are reachable.
Each node shows its reference count and the gc_refs the collector computes from it. The dashed arrow is a reference from outside the generation: the collector never sees where it comes from, only that the count is higher than the internal references explain.
gc.get_count() showed (615, 9, 0): 615 container allocations since the last collection of
generation 0, nine of those collections since the last of generation 1. Just starting the
interpreter and running the script’s imports came within 85 allocations of a collection.
What the collector costs
The thresholds are counts of objects, not of time or memory, so a program that makes many
containers triggers many collections, whether or not it ever makes a cycle. That’s measurable with
gc.callbacks, which calls a function at the start and end of every collection:
import gc, time
events = []
def cb(phase, info):
if phase == "start":
events.append([info["generation"], time.perf_counter()])
else:
events[-1][1] = time.perf_counter() - events[-1][1]
gc.callbacks.append(cb)
def build(n):
return [[i] for i in range(n)] # n small lists: n new containers
for enabled in (True, False):
if not enabled:
gc.disable()
events.clear()
t = time.perf_counter()
data = build(3000000)
total = time.perf_counter() - t
by_gen = {}
for gen, dt in events:
c, s = by_gen.get(gen, (0, 0.0))
by_gen[gen] = (c + 1, s + dt)
print("gc %-8s build %.3f s;" % ("enabled" if enabled else "disabled", total),
"; ".join("gen%d: %d runs, %.3f s" % (g, c, s) for g, (c, s) in sorted(by_gen.items())) or "no collections")
del data
gc.enable()
$ python3 gcpause.py
gc enabled build 0.996 s; gen0: 3911 runs, 0.014 s; gen1: 356 runs, 0.023 s; gen2: 13 runs, 0.748 s
gc disabled build 0.117 s; no collections
Building three million one-element lists took a second with the collector on, and an eighth of a second with it off. The young-generation collections are cheap: 3,911 of them in 14 milliseconds, because each looks at only about 700 objects. The cost is the 13 full collections, which took three quarters of a second between them, because each walks every container in the process, and the process kept getting bigger. Nothing here was garbage, and the collector did 0.75 seconds of work to find that out.
Thirteen is already the reduced number. Full collections used to make building a large structure
quadratic, so since Python 3.1 the collector skips a full collection unless the objects that
survived young collections since the last full one amount to at least a quarter of the long-lived
objects, from collect_generations:
/* Avoid quadratic performance degradation in number
of tracked objects. See comments at the beginning
of this file, and issue #4074.
*/
if (i == NUM_GENERATIONS - 1
&& _PyRuntime.gc.long_lived_pending < _PyRuntime.gc.long_lived_total / 4)
continue;
That makes the number of full collections logarithmic in the size of the heap instead of linear, but each is still proportional to the heap. This is the leak: a program’s latency depends on how many containers exist anywhere in the process, including in libraries it doesn’t know about, because any allocation can trigger a pause that walks all of them. Disabling the collector, or raising its thresholds, during a bulk load is a common optimisation for exactly that reason. It’s safe as long as the code in question makes no cycles, and that’s something nobody can check from the language.
Reading is writing
Now the fork. Pre-forking servers (uWSGI, gunicorn, multiprocessing with the fork start method)
load the application once in a parent process and then fork() workers. The kernel doesn’t copy
the parent’s memory for each child. It maps the same physical pages into both, marked read-only, and
copies a page only when one side writes to it. That is copy-on-write, and it lets dozens of workers
share one copy of a large application, as long as nobody writes.
In Python, everybody writes. Every time a worker takes a reference to a shared object, binding it to
a name, passing it to a function, or iterating over it, Py_INCREF writes to the object’s
ob_refcnt, and the page holding it is copied. Then a collection runs, update_refs writes
gc_refs into every container’s header, and more pages are copied. Instagram’s engineers described
both effects in two posts. “Dismissing Python Garbage Collection at Instagram” (January 2017) turned
the collector off in their Django workers and reported roughly 10% more capacity. “Copy-on-write
friendly Python garbage collection” (December 2017) proposed a way to turn it back on, which became
Python 3.7’s gc.freeze().
Here is the effect measured, with Linux’s per-process memory accounting. /proc/self/smaps_rollup
(new in Linux 4.14, present in 18.04’s 4.15 kernel) reports, among other things, Private_Dirty:
memory this process has written to that no other process shares, which for a forked child is
exactly what has been copied.
import gc, os, sys
def rollup():
out = {}
for line in open("/proc/self/smaps_rollup"):
parts = line.split()
if len(parts) == 3 and parts[2] == "kB":
out[parts[0].rstrip(":")] = int(parts[1])
return out
N = 1000000
data = [["item", i, str(i)] for i in range(N)] # a million small lists, each with an int and a str
if "freeze" in sys.argv:
gc.freeze() # new in 3.7: park everything in a permanent generation
def child(action):
before = rollup()["Private_Dirty"]
if action == "read":
n = 0
for item in data: # only reads: no assignment into data
n += item[1]
elif action == "collect":
gc.collect()
after = rollup()["Private_Dirty"]
return after - before
parent_rss = rollup()["Rss"]
for action in ("nothing", "read", "collect"):
r, w = os.pipe()
pid = os.fork()
if pid == 0:
os.close(r)
os.write(w, str(child(action)).encode())
os._exit(0)
os.close(w)
copied = int(os.read(r, 100))
os.waitpid(pid, 0)
print("%-7s parent RSS %6.1f MB; child %-7s copied %6.1f MB" %
("freeze" if "freeze" in sys.argv else "", parent_rss / 1024, action, copied / 1024))
$ python3 cow.py
parent RSS 183.9 MB; child nothing copied 0.1 MB
parent RSS 183.9 MB; child read copied 93.1 MB
parent RSS 183.9 MB; child collect copied 62.8 MB
$ python3 cow.py freeze
freeze parent RSS 183.9 MB; child nothing copied 0.1 MB
freeze parent RSS 183.9 MB; child read copied 93.1 MB
freeze parent RSS 183.9 MB; child collect copied 0.2 MB
(The MB here are mebibytes: /proc reports KiB and the script divides by 1,024.)
What a forked child copied of its parent's 183.9 MiB
Python 3.7.0 on Linux 4.15. The parent holds a million small lists; each child does one thing, and the kernel counts the pages it had to copy.
gc.freeze() before forkinggc.collect()one gc.collect()Hover or focus a bar for details.
Each bar is the growth of the child's Private_Dirty in /proc/self/smaps_rollup across the one action. Reading copies the pages of every list and int it touches, because each reference changes a count; a collection copies every container's GC header unless the containers were frozen first.
Why 93 MB and 62.8 MB, exactly
The numbers can be predicted from the object layouts in Part 1, and checking them is a good test of whether the explanation is right.
Reading copied 93.1 MB. The loop does two things to each element. for item in data binds
item, an increment of the inner list’s count, and item[1] pushes the integer, an increment of the
int’s count. Both are released a moment later, but the write has already happened. The third field,
the string, is never touched. The "item" constant is one shared object, so its page is copied once.
CPython’s small-object allocator, the subject of the next post, keeps objects of one size together in
4 KiB pages. A list is a 40-byte PyListObject plus the 24-byte GC header, so it lives in the 64-byte
size class. An int up to 230 is 28 bytes, rounded up to 32. So reading dirtied every page of
64-byte blocks and every page of 32-byte blocks, and nothing else: a million × (64 + 32) bytes is 91.6
MiB. The rest of the 93.1 is the interpreter’s own pages (its stack, its frames, the loop’s
temporaries).
Collecting copied 62.8 MB. gc.collect() touches no ints and no strings, which aren’t containers.
It writes gc_refs into the header of every tracked container: every list, 64 bytes each, a million
of them. That’s 61.0 MiB, plus the dicts, functions and modules of the interpreter itself. The
collection freed nothing. It only looked, and looking is writing.
gc.freeze() fixed the second and not the first. Here is all of it, in Modules/gcmodule.c:
static PyObject *
gc_freeze_impl(PyObject *module)
{
for (int i = 0; i < NUM_GENERATIONS; ++i) {
gc_list_merge(GEN_HEAD(i), &_PyRuntime.gc.permanent_generation.head);
_PyRuntime.gc.generations[i].count = 0;
}
Py_RETURN_NONE;
}
It moves every tracked object onto a fourth list, the permanent generation, that no collection ever
examines. The objects are untouched. Only the list heads move, and they are in the parent’s static
data. A child’s collections then walk only the objects created after the fork, and the inherited ones'
headers are never written. That brought the collection in the child from 62.8 MB to 0.2 MB. But reading
still copied 93.1 MB, because no API can stop Py_INCREF from writing to ob_refcnt. That would need
objects whose count is never written, and CPython has no such thing.
So the recommended pattern from the 3.7 documentation, gc.disable() early in the parent,
gc.freeze() just before forking, gc.enable() in the child, solves the collector’s part of the
problem. Reference counting’s part is permanent: in a pre-forked server, the memory shared between
workers shrinks as the workers touch it, and every request touches some.
What we covered
- An object is freed by the
Py_DECREFthat takes its count to zero, during whatever statement did it. Programs rely on that timing (files closed by going out of scope), and it’s a CPython behaviour, not a language guarantee. 3.7’s-X devshows where it’s being relied on. - Exceptions hold tracebacks, tracebacks hold frames, and frames hold every local, so a kept exception keeps whole call stacks of objects alive.
- Reference cycles never reach zero, so a separate generational cycle collector finds them by
subtracting internal references from reference counts, without knowing the roots. Since 3.4 it
handles
__del__in cycles. - Its collections are triggered by container counts. Building three million lists took a second with it on and an eighth of one with it off, three quarters of it in 13 full collections that found nothing.
- After
fork, reading shared objects copies them, because every reference changes a count. A child that iterated over a million lists copied 93 MB of 184. A collection copied 63 MB more, because it writes every container’s header. Python 3.7’sgc.freeze()eliminates the second, and nothing can eliminate the first.
The next post follows the memory itself: where those 64-byte and 32-byte blocks come from, why
CPython has its own allocator on top of malloc, and why a Python process that frees most of its
objects often doesn’t get smaller.
A note on the evidence
What I ran, and where. Everything ran on CPython 3.7.0, built from the v3.7.0 tag with Ubuntu
18.04’s gcc 7.3.0, in a KVM virtual machine (4 virtual CPUs, 4 GiB) booting 18.04’s release kernel
4.15.0-20-generic #21-Ubuntu on a minimal 18.04 userland from the release archive, so that the
copy-on-write and smaps_rollup numbers are that kernel’s. Each script was extracted from this page
and run as shown.
The numbers. The copy-on-write figures are one run each, in a VM with nothing else running, and
they’re counts of pages, not timings: running them again gave the same values to the tenth of a MB.
The collector timings are one run, and the ratio (eight to one) is the point, not the milliseconds:
a second run of every script on this page, extracted from the page, gave 0.950 and 0.120 seconds with
the same thirteen full collections. The only other difference in that run was gc.get_count(), which
read (641, 9, 0) instead of (615, 9, 0). How many containers start-up leaves behind varies a little
from run to run.
The predicted 91.6 and 61.0 MiB assume that every 64-byte and 32-byte block belongs to these lists
and ints. A few belong to other objects, and that, plus the interpreter’s own pages, is the
difference from the measured values.
What I worked out rather than read. The size classes (64 bytes for a list, 32 for an int) come from Part 1’s struct sizes and the allocator’s 8-byte rounding, not from asking the allocator. The next post measures them directly. That reading dirties the list and int pages and not the string pages is inferred from the arithmetic matching, not from inspecting which pages were copied.
What I cited rather than ran. The C quoted here is from the v3.7.0 tag: Modules/gcmodule.c
(update_refs, subtract_refs, collect_generations, gc_freeze_impl). Instagram’s two posts are
“Dismissing Python Garbage Collection at Instagram” (January 2017) and “Copy-on-write friendly Python
garbage collection” by Zekun Li (20 December 2017), and the change itself is bpo-31558. PEP 442 is
from Python 3.4, and the long-lived heuristic from issue #4074, first in 3.1. The history of the
collector is from the 2.0 release notes.
What I’d still change. A million identical small lists is the friendliest case for the arithmetic. A real application’s objects are mixed sizes spread across pages, so every page holding any touched object is copied, and the fraction copied is usually higher. A useful next experiment would be the same measurement on a real Django worker.
Counting References