| 1 |
Garbage collector documentation and configuration |
| 2 |
================================================= |
| 3 |
|
| 4 |
|
| 5 |
Incminimark |
| 6 |
----------- |
| 7 |
|
| 8 |
PyPy's default garbage collector is called incminimark - it's an incremental, |
| 9 |
generational moving collector. Here we hope to explain a bit how it works |
| 10 |
and how it can be tuned to suit the workload. |
| 11 |
|
| 12 |
Incminimark first allocates objects in so called *nursery* - place for young |
| 13 |
objects, where allocation is very cheap, being just a pointer bump. The nursery |
| 14 |
size is a very crucial variable - depending on your workload (one or many |
| 15 |
processes) and cache sizes you might want to experiment with it via |
| 16 |
*PYPY_GC_NURSERY* environment variable. When the nursery is full, a minor |
| 17 |
collection is performed. Freed objects are no longer referenceable and |
| 18 |
just die, just by not being referenced any more; on the other hand, objects |
| 19 |
found to still be alive must survive and are copied from the nursery |
| 20 |
to the old generation. Either to arenas, which are collections |
| 21 |
of objects of the same size, or directly allocated with malloc if they're |
| 22 |
larger. (A third category, the very large objects, are initially allocated |
| 23 |
outside the nursery and never move.) |
| 24 |
|
| 25 |
Since Incminimark is an incremental GC, the major collection is incremental: |
| 26 |
the goal is not to have any pause longer than 1ms, but in practice it depends |
| 27 |
on the size and characteristics of the heap: occasionally, there can be pauses |
| 28 |
between 10-100ms. |
| 29 |
|
| 30 |
|
| 31 |
Semi-manual GC management |
| 32 |
-------------------------- |
| 33 |
|
| 34 |
If there are parts of the program where it is important to have a low latency, |
| 35 |
you might want to control precisely when the GC runs, to avoid unexpected |
| 36 |
pauses. Note that this has effect only on major collections, while minor |
| 37 |
collections continue to work as usual. |
| 38 |
|
| 39 |
As explained above, a full major collection consists of ``N`` steps, where |
| 40 |
``N`` depends on the size of the heap; generally speaking, it is not possible |
| 41 |
to predict how many steps will be needed to complete a collection. |
| 42 |
|
| 43 |
``gc.enable()`` and ``gc.disable()`` control whether the GC runs collection |
| 44 |
steps automatically. When the GC is disabled the memory usage will grow |
| 45 |
indefinitely, unless you manually call ``gc.collect()`` and |
| 46 |
``gc.collect_step()``. |
| 47 |
|
| 48 |
``gc.collect()`` runs a full major collection. |
| 49 |
|
| 50 |
``gc.collect_step()`` runs a single collection step. It returns an object of |
| 51 |
type GcCollectStepStats_, the same which is passed to the corresponding `GC |
| 52 |
Hooks`_. The following code is roughly equivalent to a ``gc.collect()``:: |
| 53 |
|
| 54 |
while True: |
| 55 |
if gc.collect_step().major_is_done: |
| 56 |
break |
| 57 |
|
| 58 |
For a real-world example of usage of this API, you can look at the 3rd-party |
| 59 |
module `pypytools.gc.custom`_, which also provides a ``with customgc.nogc()`` |
| 60 |
context manager to mark sections where the GC is forbidden. |
| 61 |
|
| 62 |
.. _`pypytools.gc.custom`: https://github.com/antocuni/pypytools/blob/master/pypytools/gc/custom.py |
| 63 |
|
| 64 |
|
| 65 |
Fragmentation |
| 66 |
------------- |
| 67 |
|
| 68 |
Before we discuss issues of "fragmentation", we need a bit of precision. |
| 69 |
There are two kinds of related but distinct issues: |
| 70 |
|
| 71 |
* If the program allocates a lot of memory, and then frees it all by |
| 72 |
dropping all references to it, then we might expect to see the RSS |
| 73 |
to drop. (RSS = Resident Set Size on Linux, as seen by "top"; it is an |
| 74 |
approximation of the actual memory usage from the OS's point of view.) |
| 75 |
This might not occur: the RSS may remain at its highest value. This |
| 76 |
issue is more precisely caused by the process not returning "free" |
| 77 |
memory to the OS. We call this case "unreturned memory". |
| 78 |
|
| 79 |
* After doing the above, if the RSS didn't go down, then at least future |
| 80 |
allocations should not cause the RSS to grow more. That is, the process |
| 81 |
should reuse unreturned memory as long as it has got some left. If this |
| 82 |
does not occur, the RSS grows even larger and we have real fragmentation |
| 83 |
issues. |
| 84 |
|
| 85 |
|
| 86 |
gc.get_stats |
| 87 |
------------ |
| 88 |
|
| 89 |
There is a special function in the ``gc`` module called |
| 90 |
``get_stats(memory_pressure=False)``. |
| 91 |
|
| 92 |
``memory_pressure`` controls whether or not to report memory pressure from |
| 93 |
objects allocated outside of the GC, which requires walking the entire heap, |
| 94 |
so it's disabled by default due to its cost. Enable it when debugging |
| 95 |
mysterious memory disappearance. |
| 96 |
|
| 97 |
Example call looks like that:: |
| 98 |
|
| 99 |
>>> gc.get_stats(True) |
| 100 |
Total memory consumed: |
| 101 |
GC used: 4.2MB (peak: 4.2MB) |
| 102 |
in arenas: 763.7kB |
| 103 |
rawmalloced: 383.1kB |
| 104 |
nursery: 3.1MB |
| 105 |
raw assembler used: 0.0kB |
| 106 |
memory pressure: 0.0kB |
| 107 |
----------------------------- |
| 108 |
Total: 4.2MB |
| 109 |
|
| 110 |
Total memory allocated: |
| 111 |
GC allocated: 4.5MB (peak: 4.5MB) |
| 112 |
in arenas: 763.7kB |
| 113 |
rawmalloced: 383.1kB |
| 114 |
nursery: 3.1MB |
| 115 |
raw assembler allocated: 0.0kB |
| 116 |
memory pressure: 0.0kB |
| 117 |
----------------------------- |
| 118 |
Total: 4.5MB |
| 119 |
|
| 120 |
In this particular case, which is just at startup, GC consumes relatively |
| 121 |
little memory and there is even less unused, but allocated memory. In case |
| 122 |
there is a lot of unreturned memory or actual fragmentation, the "allocated" |
| 123 |
can be much higher than "used". Generally speaking, "peak" will more closely |
| 124 |
resemble the actual memory consumed as reported by RSS. Indeed, returning |
| 125 |
memory to the OS is a hard and not solved problem. In PyPy, it occurs only if |
| 126 |
an arena is entirely free---a contiguous block of 64 pages of 4 or 8 KB each. |
| 127 |
It is also rare for the "rawmalloced" category, at least for common system |
| 128 |
implementations of ``malloc()``. |
| 129 |
|
| 130 |
The details of various fields: |
| 131 |
|
| 132 |
* GC in arenas - small old objects held in arenas. If the amount "allocated" |
| 133 |
is much higher than the amount "used", we have unreturned memory. It is |
| 134 |
possible but unlikely that we have internal fragmentation here. However, |
| 135 |
this unreturned memory cannot be reused for any ``malloc()``, including the |
| 136 |
memory from the "rawmalloced" section. |
| 137 |
|
| 138 |
* GC rawmalloced - large objects allocated with malloc. This is gives the |
| 139 |
current (first block of text) and peak (second block of text) memory |
| 140 |
allocated with ``malloc()``. The amount of unreturned memory or |
| 141 |
fragmentation caused by ``malloc()`` cannot easily be reported. Usually |
| 142 |
you can guess there is some if the RSS is much larger than the total |
| 143 |
memory reported for "GC allocated", but do keep in mind that this total |
| 144 |
does not include malloc'ed memory not known to PyPy's GC at all. If you |
| 145 |
guess there is some, consider using `jemalloc`_ as opposed to system malloc. |
| 146 |
|
| 147 |
.. _`jemalloc`: http://jemalloc.net/ |
| 148 |
|
| 149 |
* nursery - amount of memory allocated for nursery, fixed at startup, |
| 150 |
controlled via an environment variable |
| 151 |
|
| 152 |
* raw assembler allocated - amount of assembler memory that JIT feels |
| 153 |
responsible for |
| 154 |
|
| 155 |
* memory pressure, if asked for - amount of memory we think got allocated |
| 156 |
via external malloc (eg loading cert store in SSL contexts) that is kept |
| 157 |
alive by GC objects, but not accounted in the GC |
| 158 |
|
| 159 |
|
| 160 |
GC Hooks |
| 161 |
-------- |
| 162 |
|
| 163 |
GC hooks are user-defined functions which are called whenever a specific GC |
| 164 |
event occur, and can be used to monitor GC activity and pauses. You can |
| 165 |
install the hooks by setting the following attributes: |
| 166 |
|
| 167 |
``gc.hooks.on_gc_minor`` |
| 168 |
Called whenever a minor collection occurs. It corresponds to |
| 169 |
``gc-minor`` sections inside ``PYPYLOG``. |
| 170 |
|
| 171 |
``gc.hooks.on_gc_collect_step`` |
| 172 |
Called whenever an incremental step of a major collection occurs. It |
| 173 |
corresponds to ``gc-collect-step`` sections inside ``PYPYLOG``. |
| 174 |
|
| 175 |
``gc.hooks.on_gc_collect`` |
| 176 |
Called after the last incremental step, when a major collection is fully |
| 177 |
done. It corresponds to ``gc-collect-done`` sections inside ``PYPYLOG``. |
| 178 |
|
| 179 |
To uninstall a hook, simply set the corresponding attribute to ``None``. To |
| 180 |
install all hooks at once, you can call ``gc.hooks.set(obj)``, which will look |
| 181 |
for methods ``on_gc_*`` on ``obj``. To uninstall all the hooks at once, you |
| 182 |
can call ``gc.hooks.reset()``. |
| 183 |
|
| 184 |
The functions called by the hooks receive a single ``stats`` argument, which |
| 185 |
contains various statistics about the event. |
| 186 |
|
| 187 |
Note that PyPy cannot call the hooks immediately after a GC event, but it has |
| 188 |
to wait until it reaches a point in which the interpreter is in a known state |
| 189 |
and calling user-defined code is harmless. It might happen that multiple |
| 190 |
events occur before the hook is invoked: in this case, you can inspect the |
| 191 |
value ``stats.count`` to know how many times the event occurred since the last |
| 192 |
time the hook was called. Similarly, ``stats.duration`` contains the |
| 193 |
**total** time spent by the GC for this specific event since the last time the |
| 194 |
hook was called. |
| 195 |
|
| 196 |
On the other hand, all the other fields of the ``stats`` object are relative |
| 197 |
only to the **last** event of the series. |
| 198 |
|
| 199 |
The attributes for ``GcMinorStats`` in the ``on_gc_minor`` hook are: |
| 200 |
|
| 201 |
``count`` |
| 202 |
The number of minor collections occurred since the last hook call. |
| 203 |
|
| 204 |
``duration`` |
| 205 |
The total time spent inside minor collections since the last hook |
| 206 |
call, in seconds. |
| 207 |
|
| 208 |
``duration_min`` |
| 209 |
The duration of the fastest minor collection since the last hook call. |
| 210 |
|
| 211 |
``duration_max`` |
| 212 |
The duration of the slowest minor collection since the last hook call. |
| 213 |
|
| 214 |
``total_memory_used`` |
| 215 |
The amount of memory used at the end of the minor collection, in |
| 216 |
bytes. This include the memory used in arenas (for GC-managed memory) and |
| 217 |
raw-malloced memory (e.g., the content of numpy arrays). |
| 218 |
|
| 219 |
``pinned_objects`` |
| 220 |
the number of pinned objects. |
| 221 |
|
| 222 |
|
| 223 |
.. _GcCollectStepStats: |
| 224 |
|
| 225 |
The attributes for ``GcCollectStepStats`` in the ``on_gc_collect_step`` hook are: |
| 226 |
|
| 227 |
``count``, ``duration``, ``duration_min``, ``duration_max`` |
| 228 |
See above. |
| 229 |
|
| 230 |
``oldstate``, ``newstate`` |
| 231 |
Integers which indicate the state of the GC before and after the step. |
| 232 |
|
| 233 |
``major_is_done`` |
| 234 |
Boolean which indicate whether this was the last step of the major |
| 235 |
collection |
| 236 |
|
| 237 |
The value of ``oldstate`` and ``newstate`` is one of these constants, defined |
| 238 |
inside ``gc.GcCollectStepStats``: ``STATE_SCANNING``, ``STATE_MARKING``, |
| 239 |
``STATE_SWEEPING``, ``STATE_FINALIZING``, ``STATE_USERDEL``. It is possible |
| 240 |
to get a string representation of it by indexing the ``GC_STATES`` tuple. |
| 241 |
|
| 242 |
|
| 243 |
The attributes for ``GcCollectStats`` in the ``on_gc_collect`` hook are: |
| 244 |
|
| 245 |
``count`` |
| 246 |
See above. |
| 247 |
|
| 248 |
``num_major_collects`` |
| 249 |
The total number of major collections which have been done since the |
| 250 |
start. Contrarily to ``count``, this is an always-growing counter and it's |
| 251 |
not reset between invocations. |
| 252 |
|
| 253 |
``arenas_count_before``, ``arenas_count_after`` |
| 254 |
Number of arenas used before and after the major collection. |
| 255 |
|
| 256 |
``arenas_bytes`` |
| 257 |
Total number of bytes used by GC-managed objects. |
| 258 |
|
| 259 |
``rawmalloc_bytes_before``, ``rawmalloc_bytes_after`` |
| 260 |
Total number of bytes used by raw-malloced objects, before and after the |
| 261 |
major collection. |
| 262 |
|
| 263 |
``pinned_objects`` |
| 264 |
the number of pinned objects. |
| 265 |
|
| 266 |
Note that ``GcCollectStats`` does **not** have a ``duration`` field. This is |
| 267 |
because all the GC work is done inside ``gc-collect-step``: |
| 268 |
``gc-collect-done`` is used only to give additional stats, but doesn't do any |
| 269 |
actual work. |
| 270 |
|
| 271 |
Here is an example of GC hooks in use:: |
| 272 |
|
| 273 |
import sys |
| 274 |
import gc |
| 275 |
|
| 276 |
class MyHooks(object): |
| 277 |
done = False |
| 278 |
|
| 279 |
def on_gc_minor(self, stats): |
| 280 |
print 'gc-minor: count = %02d, duration = %d' % (stats.count, |
| 281 |
stats.duration) |
| 282 |
|
| 283 |
def on_gc_collect_step(self, stats): |
| 284 |
old = gc.GcCollectStepStats.GC_STATES[stats.oldstate] |
| 285 |
new = gc.GcCollectStepStats.GC_STATES[stats.newstate] |
| 286 |
print 'gc-collect-step: %s --> %s' % (old, new) |
| 287 |
print ' count = %02d, duration = %d' % (stats.count, |
| 288 |
stats.duration) |
| 289 |
|
| 290 |
def on_gc_collect(self, stats): |
| 291 |
print 'gc-collect-done: count = %02d' % stats.count |
| 292 |
self.done = True |
| 293 |
|
| 294 |
hooks = MyHooks() |
| 295 |
gc.hooks.set(hooks) |
| 296 |
|
| 297 |
# simulate some GC activity |
| 298 |
lst = [] |
| 299 |
while not hooks.done: |
| 300 |
lst = [lst, 1, 2, 3] |
| 301 |
|
| 302 |
|
| 303 |
.. _minimark-environment-variables: |
| 304 |
|
| 305 |
Environment variables |
| 306 |
--------------------- |
| 307 |
|
| 308 |
PyPy's default ``incminimark`` garbage collector is configurable through |
| 309 |
several environment variables: |
| 310 |
|
| 311 |
``PYPY_GC_NURSERY`` |
| 312 |
The nursery size. |
| 313 |
Defaults to 1/2 of your last-level cache, ``4M`` if unknown, or ``4M`` if |
| 314 |
the last-level cache is too small. |
| 315 |
Small values (like 1 or 1KB) are useful for debugging. |
| 316 |
|
| 317 |
``PYPY_GC_NURSERY_DEBUG`` |
| 318 |
If set to non-zero, will fill nursery with garbage, to help |
| 319 |
debugging. |
| 320 |
|
| 321 |
``PYPY_GC_INCREMENT_STEP`` |
| 322 |
The size of memory marked during the marking step. Default is size of |
| 323 |
nursery times 2. If you mark it too high your GC is not incremental at |
| 324 |
all. The minimum is set to size that survives minor collection times |
| 325 |
1.5 so we reclaim anything all the time. |
| 326 |
|
| 327 |
``PYPY_GC_MAJOR_COLLECT`` |
| 328 |
Major collection memory factor. |
| 329 |
Default is ``1.82``, which means trigger a major collection when the |
| 330 |
memory consumed equals 1.82 times the memory really used at the end |
| 331 |
of the previous major collection. |
| 332 |
|
| 333 |
``PYPY_GC_GROWTH`` |
| 334 |
Major collection threshold's max growth rate. |
| 335 |
Default is ``1.4``. |
| 336 |
Useful to collect more often than normally on sudden memory growth, |
| 337 |
e.g. when there is a temporary peak in memory usage. |
| 338 |
|
| 339 |
``PYPY_GC_MAX`` |
| 340 |
The max heap size. |
| 341 |
If coming near this limit, it will first collect more often, then |
| 342 |
raise an RPython MemoryError, and if that is not enough, crash the |
| 343 |
program with a fatal error. |
| 344 |
Try values like ``1.6GB``. |
| 345 |
|
| 346 |
``PYPY_GC_MAX_DELTA`` |
| 347 |
The major collection threshold will never be set to more than |
| 348 |
``PYPY_GC_MAX_DELTA`` the amount really used after a collection. |
| 349 |
Defaults to 1/8th of the total RAM size (which is constrained to be |
| 350 |
at most 2/3/4GB on 32-bit systems). |
| 351 |
Try values like ``200MB``. |
| 352 |
|
| 353 |
``PYPY_GC_MIN`` |
| 354 |
Don't collect while the memory size is below this limit. |
| 355 |
Useful to avoid spending all the time in the GC in very small |
| 356 |
programs. |
| 357 |
Defaults to 8 times the nursery. |
| 358 |
|
| 359 |
``PYPY_GC_DEBUG`` |
| 360 |
Enable extra checks around collections that are too slow for normal |
| 361 |
use. |
| 362 |
Values are ``0`` (off), ``1`` (on major collections) or ``2`` (also |
| 363 |
on minor collections). |
| 364 |
|
| 365 |
``PYPY_GC_MAX_PINNED`` |
| 366 |
The maximal number of pinned objects at any point in time. Defaults |
| 367 |
to a conservative value depending on nursery size and maximum object |
| 368 |
size inside the nursery. Useful for debugging by setting it to 0. |