GH-108362: Revert "GH-108362: Incremental GC implementation (GH-108038)" (#115132)

Revert "GH-108362: Incremental GC implementation (GH-108038)"

This reverts commit 36518e69d7.
This commit is contained in:
Mark Shannon 2024-02-07 12:38:34 +00:00 committed by GitHub
parent d0322fdf2c
commit 8a3c499ffe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 446 additions and 701 deletions

View File

@ -92,10 +92,6 @@ Interpreter improvements:
New Features New Features
============ ============
* The cyclic garbage collector is now incremental.
This means that maximum pause times are reduced,
by an order of magnitude or more for larger heaps.
Improved Error Messages Improved Error Messages
----------------------- -----------------------
@ -105,13 +101,6 @@ Improved Error Messages
variables. See also :ref:`using-on-controlling-color`. variables. See also :ref:`using-on-controlling-color`.
(Contributed by Pablo Galindo Salgado in :gh:`112730`.) (Contributed by Pablo Galindo Salgado in :gh:`112730`.)
Incremental Garbage Collection
------------------------------
* The cycle garbage collector is now incremental.
This means that maximum pause times are reduced
by an order of magnitude or more for larger heaps.
Other Language Changes Other Language Changes
====================== ======================
@ -257,29 +246,6 @@ fractions
sign handling, minimum width and grouping. (Contributed by Mark Dickinson sign handling, minimum width and grouping. (Contributed by Mark Dickinson
in :gh:`111320`.) in :gh:`111320`.)
gc
--
* The cyclic garbage collector is now incremental, which changes the meanings
of the results of :meth:`gc.get_threshold` and :meth:`gc.get_threshold` as
well as :meth:`gc.get_count` and :meth:`gc.get_stats`.
* :meth:`gc.get_threshold` returns a three-tuple for backwards compatibility,
the first value is the threshold for young collections, as before, the second
value determines the rate at which the old collection is scanned; the
default is 10 and higher values mean that the old collection is scanned more slowly.
The third value is meangless and is always zero.
* :meth:`gc.set_threshold` ignores any items after the second.
* :meth:`gc.get_count` and :meth:`gc.get_stats`.
These functions return the same format of results as before.
The only difference is that instead of the results refering to
the young, aging and old generations, the results refer to the
young generation and the aging and collecting spaces of the old generation.
In summary, code that attempted to manipulate the behavior of the cycle GC may
not work as well as intended, but it is very unlikely to harmful.
All other code will work just fine.
Uses should avoid calling :meth:`gc.collect` unless their workload is episodic,
but that has always been the case to some extent.
glob glob
---- ----

View File

@ -88,15 +88,11 @@ static inline void _PyObject_GC_SET_SHARED(PyObject *op) {
/* Bit flags for _gc_prev */ /* Bit flags for _gc_prev */
/* Bit 0 is set when tp_finalize is called */ /* Bit 0 is set when tp_finalize is called */
#define _PyGC_PREV_MASK_FINALIZED 1 #define _PyGC_PREV_MASK_FINALIZED (1)
/* Bit 1 is set when the object is in generation which is GCed currently. */ /* Bit 1 is set when the object is in generation which is GCed currently. */
#define _PyGC_PREV_MASK_COLLECTING 2 #define _PyGC_PREV_MASK_COLLECTING (2)
/* Bit 0 is set if the object belongs to old space 1 */
#define _PyGC_NEXT_MASK_OLD_SPACE_1 1
/* The (N-2) most significant bits contain the real address. */ /* The (N-2) most significant bits contain the real address. */
#define _PyGC_PREV_SHIFT 2 #define _PyGC_PREV_SHIFT (2)
#define _PyGC_PREV_MASK (((uintptr_t) -1) << _PyGC_PREV_SHIFT) #define _PyGC_PREV_MASK (((uintptr_t) -1) << _PyGC_PREV_SHIFT)
/* set for debugging information */ /* set for debugging information */
@ -122,13 +118,11 @@ typedef enum {
// Lowest bit of _gc_next is used for flags only in GC. // Lowest bit of _gc_next is used for flags only in GC.
// But it is always 0 for normal code. // But it is always 0 for normal code.
static inline PyGC_Head* _PyGCHead_NEXT(PyGC_Head *gc) { static inline PyGC_Head* _PyGCHead_NEXT(PyGC_Head *gc) {
uintptr_t next = gc->_gc_next & _PyGC_PREV_MASK; uintptr_t next = gc->_gc_next;
return (PyGC_Head*)next; return (PyGC_Head*)next;
} }
static inline void _PyGCHead_SET_NEXT(PyGC_Head *gc, PyGC_Head *next) { static inline void _PyGCHead_SET_NEXT(PyGC_Head *gc, PyGC_Head *next) {
uintptr_t unext = (uintptr_t)next; gc->_gc_next = (uintptr_t)next;
assert((unext & ~_PyGC_PREV_MASK) == 0);
gc->_gc_next = (gc->_gc_next & ~_PyGC_PREV_MASK) | unext;
} }
// Lowest two bits of _gc_prev is used for _PyGC_PREV_MASK_* flags. // Lowest two bits of _gc_prev is used for _PyGC_PREV_MASK_* flags.
@ -136,7 +130,6 @@ static inline PyGC_Head* _PyGCHead_PREV(PyGC_Head *gc) {
uintptr_t prev = (gc->_gc_prev & _PyGC_PREV_MASK); uintptr_t prev = (gc->_gc_prev & _PyGC_PREV_MASK);
return (PyGC_Head*)prev; return (PyGC_Head*)prev;
} }
static inline void _PyGCHead_SET_PREV(PyGC_Head *gc, PyGC_Head *prev) { static inline void _PyGCHead_SET_PREV(PyGC_Head *gc, PyGC_Head *prev) {
uintptr_t uprev = (uintptr_t)prev; uintptr_t uprev = (uintptr_t)prev;
assert((uprev & ~_PyGC_PREV_MASK) == 0); assert((uprev & ~_PyGC_PREV_MASK) == 0);
@ -222,13 +215,6 @@ struct gc_generation {
generations */ generations */
}; };
struct gc_collection_stats {
/* number of collected objects */
Py_ssize_t collected;
/* total number of uncollectable objects (put into gc.garbage) */
Py_ssize_t uncollectable;
};
/* Running stats per generation */ /* Running stats per generation */
struct gc_generation_stats { struct gc_generation_stats {
/* total number of collections */ /* total number of collections */
@ -250,8 +236,8 @@ struct _gc_runtime_state {
int enabled; int enabled;
int debug; int debug;
/* linked lists of container objects */ /* linked lists of container objects */
struct gc_generation young; struct gc_generation generations[NUM_GENERATIONS];
struct gc_generation old[2]; PyGC_Head *generation0;
/* a permanent generation which won't be collected */ /* a permanent generation which won't be collected */
struct gc_generation permanent_generation; struct gc_generation permanent_generation;
struct gc_generation_stats generation_stats[NUM_GENERATIONS]; struct gc_generation_stats generation_stats[NUM_GENERATIONS];
@ -264,20 +250,22 @@ struct _gc_runtime_state {
/* This is the number of objects that survived the last full /* This is the number of objects that survived the last full
collection. It approximates the number of long lived objects collection. It approximates the number of long lived objects
tracked by the GC. tracked by the GC.
(by "full collection", we mean a collection of the oldest (by "full collection", we mean a collection of the oldest
generation). */ generation). */
Py_ssize_t long_lived_total; Py_ssize_t long_lived_total;
/* This is the number of objects that survived all "non-full"
Py_ssize_t work_to_do; collections, and are awaiting to undergo a full collection for
/* Which of the old spaces is the visited space */ the first time. */
int visited_space; Py_ssize_t long_lived_pending;
}; };
extern void _PyGC_InitState(struct _gc_runtime_state *); extern void _PyGC_InitState(struct _gc_runtime_state *);
extern Py_ssize_t _PyGC_Collect(PyThreadState *tstate, int generation, _PyGC_Reason reason); extern Py_ssize_t _PyGC_Collect(PyThreadState *tstate, int generation,
extern void _PyGC_CollectNoFail(PyThreadState *tstate); _PyGC_Reason reason);
extern Py_ssize_t _PyGC_CollectNoFail(PyThreadState *tstate);
/* Freeze objects tracked by the GC and ignore them in future collections. */ /* Freeze objects tracked by the GC and ignore them in future collections. */
extern void _PyGC_Freeze(PyInterpreterState *interp); extern void _PyGC_Freeze(PyInterpreterState *interp);

View File

@ -125,7 +125,19 @@ static inline void _Py_RefcntAdd(PyObject* op, Py_ssize_t n)
} }
#define _Py_RefcntAdd(op, n) _Py_RefcntAdd(_PyObject_CAST(op), n) #define _Py_RefcntAdd(op, n) _Py_RefcntAdd(_PyObject_CAST(op), n)
extern void _Py_SetImmortal(PyObject *op); static inline void _Py_SetImmortal(PyObject *op)
{
if (op) {
#ifdef Py_GIL_DISABLED
op->ob_tid = _Py_UNOWNED_TID;
op->ob_ref_local = _Py_IMMORTAL_REFCNT_LOCAL;
op->ob_ref_shared = 0;
#else
op->ob_refcnt = _Py_IMMORTAL_REFCNT;
#endif
}
}
#define _Py_SetImmortal(op) _Py_SetImmortal(_PyObject_CAST(op))
// Makes an immortal object mortal again with the specified refcnt. Should only // Makes an immortal object mortal again with the specified refcnt. Should only
// be used during runtime finalization. // be used during runtime finalization.
@ -313,12 +325,11 @@ static inline void _PyObject_GC_TRACK(
filename, lineno, __func__); filename, lineno, __func__);
PyInterpreterState *interp = _PyInterpreterState_GET(); PyInterpreterState *interp = _PyInterpreterState_GET();
PyGC_Head *generation0 = &interp->gc.young.head; PyGC_Head *generation0 = interp->gc.generation0;
PyGC_Head *last = (PyGC_Head*)(generation0->_gc_prev); PyGC_Head *last = (PyGC_Head*)(generation0->_gc_prev);
_PyGCHead_SET_NEXT(last, gc); _PyGCHead_SET_NEXT(last, gc);
_PyGCHead_SET_PREV(gc, last); _PyGCHead_SET_PREV(gc, last);
_PyGCHead_SET_NEXT(gc, generation0); _PyGCHead_SET_NEXT(gc, generation0);
assert((gc->_gc_next & _PyGC_NEXT_MASK_OLD_SPACE_1) == 0);
generation0->_gc_prev = (uintptr_t)gc; generation0->_gc_prev = (uintptr_t)gc;
#endif #endif
} }

View File

@ -162,12 +162,12 @@ extern PyTypeObject _PyExc_MemoryError;
}, \ }, \
.gc = { \ .gc = { \
.enabled = 1, \ .enabled = 1, \
.young = { .threshold = 2000, }, \ .generations = { \
.old = { \ /* .head is set in _PyGC_InitState(). */ \
{ .threshold = 700, }, \
{ .threshold = 10, }, \
{ .threshold = 10, }, \ { .threshold = 10, }, \
{ .threshold = 0, }, \
}, \ }, \
.work_to_do = -5000, \
}, \ }, \
.object_state = _py_object_state_INIT(INTERP), \ .object_state = _py_object_state_INIT(INTERP), \
.dtoa = _dtoa_state_INIT(&(INTERP)), \ .dtoa = _dtoa_state_INIT(&(INTERP)), \

View File

@ -383,11 +383,19 @@ class GCTests(unittest.TestCase):
# each call to collect(N) # each call to collect(N)
x = [] x = []
gc.collect(0) gc.collect(0)
# x is now in the old gen # x is now in gen 1
a, b, c = gc.get_count() a, b, c = gc.get_count()
# We don't check a since its exact values depends on gc.collect(1)
# x is now in gen 2
d, e, f = gc.get_count()
gc.collect(2)
# x is now in gen 3
g, h, i = gc.get_count()
# We don't check a, d, g since their exact values depends on
# internal implementation details of the interpreter. # internal implementation details of the interpreter.
self.assertEqual((b, c), (1, 0)) self.assertEqual((b, c), (1, 0))
self.assertEqual((e, f), (0, 1))
self.assertEqual((h, i), (0, 0))
def test_trashcan(self): def test_trashcan(self):
class Ouch: class Ouch:
@ -838,6 +846,16 @@ class GCTests(unittest.TestCase):
self.assertFalse( self.assertFalse(
any(l is element for element in gc.get_objects(generation=2)) any(l is element for element in gc.get_objects(generation=2))
) )
gc.collect(generation=1)
self.assertFalse(
any(l is element for element in gc.get_objects(generation=0))
)
self.assertFalse(
any(l is element for element in gc.get_objects(generation=1))
)
self.assertTrue(
any(l is element for element in gc.get_objects(generation=2))
)
gc.collect(generation=2) gc.collect(generation=2)
self.assertFalse( self.assertFalse(
any(l is element for element in gc.get_objects(generation=0)) any(l is element for element in gc.get_objects(generation=0))

View File

@ -1,13 +0,0 @@
Implements an incremental cyclic garbage collector. By collecting the old
generation in increments, there is no need for a full heap scan. This can
hugely reduce maximum pause time for programs with large heaps.
Reduces the number of generations from three to two. The old generation is
split into two spaces, "aging" and "collecting".
Collection happens in two steps:: * First, the young generation is scanned
and the survivors moved to the end of the aging space. * Then objects are
taken from the collecting space, at such a rate that all cycles are
collected eventually. Those objects are then scanned and the survivors
moved to the end of the aging space. When the collecting space becomes
empty, the two spaces are swapped.

View File

@ -158,12 +158,17 @@ gc_set_threshold_impl(PyObject *module, int threshold0, int group_right_1,
{ {
GCState *gcstate = get_gc_state(); GCState *gcstate = get_gc_state();
gcstate->young.threshold = threshold0; gcstate->generations[0].threshold = threshold0;
if (group_right_1) { if (group_right_1) {
gcstate->old[0].threshold = threshold1; gcstate->generations[1].threshold = threshold1;
} }
if (group_right_2) { if (group_right_2) {
gcstate->old[1].threshold = threshold2; gcstate->generations[2].threshold = threshold2;
/* generations higher than 2 get the same threshold */
for (int i = 3; i < NUM_GENERATIONS; i++) {
gcstate->generations[i].threshold = gcstate->generations[2].threshold;
}
} }
Py_RETURN_NONE; Py_RETURN_NONE;
} }
@ -180,9 +185,9 @@ gc_get_threshold_impl(PyObject *module)
{ {
GCState *gcstate = get_gc_state(); GCState *gcstate = get_gc_state();
return Py_BuildValue("(iii)", return Py_BuildValue("(iii)",
gcstate->young.threshold, gcstate->generations[0].threshold,
gcstate->old[0].threshold, gcstate->generations[1].threshold,
0); gcstate->generations[2].threshold);
} }
/*[clinic input] /*[clinic input]
@ -197,9 +202,9 @@ gc_get_count_impl(PyObject *module)
{ {
GCState *gcstate = get_gc_state(); GCState *gcstate = get_gc_state();
return Py_BuildValue("(iii)", return Py_BuildValue("(iii)",
gcstate->young.count, gcstate->generations[0].count,
gcstate->old[gcstate->visited_space].count, gcstate->generations[1].count,
gcstate->old[gcstate->visited_space^1].count); gcstate->generations[2].count);
} }
/*[clinic input] /*[clinic input]

View File

@ -2387,21 +2387,6 @@ _Py_NewReferenceNoTotal(PyObject *op)
new_reference(op); new_reference(op);
} }
void
_Py_SetImmortal(PyObject *op)
{
if (PyObject_IS_GC(op) && _PyObject_GC_IS_TRACKED(op)) {
_PyObject_GC_UNTRACK(op);
}
#ifdef Py_GIL_DISABLED
op->ob_tid = _Py_UNOWNED_TID;
op->ob_ref_local = _Py_IMMORTAL_REFCNT_LOCAL;
op->ob_ref_shared = 0;
#else
op->ob_refcnt = _Py_IMMORTAL_REFCNT;
#endif
}
void void
_Py_ResurrectReference(PyObject *op) _Py_ResurrectReference(PyObject *op)
{ {

View File

@ -603,9 +603,6 @@ _PyStructSequence_InitBuiltinWithFlags(PyInterpreterState *interp,
PyStructSequence_Desc *desc, PyStructSequence_Desc *desc,
unsigned long tp_flags) unsigned long tp_flags)
{ {
if (Py_TYPE(type) == NULL) {
Py_SET_TYPE(type, &PyType_Type);
}
Py_ssize_t n_unnamed_members; Py_ssize_t n_unnamed_members;
Py_ssize_t n_members = count_members(desc, &n_unnamed_members); Py_ssize_t n_members = count_members(desc, &n_unnamed_members);
PyMemberDef *members = NULL; PyMemberDef *members = NULL;
@ -621,7 +618,7 @@ _PyStructSequence_InitBuiltinWithFlags(PyInterpreterState *interp,
} }
initialize_static_fields(type, desc, members, tp_flags); initialize_static_fields(type, desc, members, tp_flags);
_Py_SetImmortal((PyObject *)type); _Py_SetImmortal(type);
} }
#ifndef NDEBUG #ifndef NDEBUG
else { else {

File diff suppressed because it is too large Load Diff

View File

@ -616,7 +616,7 @@ void
_PyGC_InitState(GCState *gcstate) _PyGC_InitState(GCState *gcstate)
{ {
// TODO: move to pycore_runtime_init.h once the incremental GC lands. // TODO: move to pycore_runtime_init.h once the incremental GC lands.
gcstate->young.threshold = 2000; gcstate->generations[0].threshold = 2000;
} }
@ -911,8 +911,8 @@ cleanup_worklist(struct worklist *worklist)
static bool static bool
gc_should_collect(GCState *gcstate) gc_should_collect(GCState *gcstate)
{ {
int count = _Py_atomic_load_int_relaxed(&gcstate->young.count); int count = _Py_atomic_load_int_relaxed(&gcstate->generations[0].count);
int threshold = gcstate->young.threshold; int threshold = gcstate->generations[0].threshold;
if (count <= threshold || threshold == 0 || !gcstate->enabled) { if (count <= threshold || threshold == 0 || !gcstate->enabled) {
return false; return false;
} }
@ -920,7 +920,7 @@ gc_should_collect(GCState *gcstate)
// objects. A few tests rely on immediate scheduling of the GC so we ignore // objects. A few tests rely on immediate scheduling of the GC so we ignore
// the scaled threshold if generations[1].threshold is set to zero. // the scaled threshold if generations[1].threshold is set to zero.
return (count > gcstate->long_lived_total / 4 || return (count > gcstate->long_lived_total / 4 ||
gcstate->old[0].threshold == 0); gcstate->generations[1].threshold == 0);
} }
static void static void
@ -1031,15 +1031,10 @@ gc_collect_main(PyThreadState *tstate, int generation, _PyGC_Reason reason)
/* update collection and allocation counters */ /* update collection and allocation counters */
if (generation+1 < NUM_GENERATIONS) { if (generation+1 < NUM_GENERATIONS) {
gcstate->old[generation].count += 1; gcstate->generations[generation+1].count += 1;
} }
for (i = 0; i <= generation; i++) { for (i = 0; i <= generation; i++) {
if (i == 0) { gcstate->generations[i].count = 0;
gcstate->young.count = 0;
}
else {
gcstate->old[i-1].count = 0;
}
} }
PyInterpreterState *interp = tstate->interp; PyInterpreterState *interp = tstate->interp;
@ -1362,7 +1357,7 @@ _PyGC_Collect(PyThreadState *tstate, int generation, _PyGC_Reason reason)
return gc_collect_main(tstate, generation, reason); return gc_collect_main(tstate, generation, reason);
} }
void Py_ssize_t
_PyGC_CollectNoFail(PyThreadState *tstate) _PyGC_CollectNoFail(PyThreadState *tstate)
{ {
/* Ideally, this function is only called on interpreter shutdown, /* Ideally, this function is only called on interpreter shutdown,
@ -1371,7 +1366,7 @@ _PyGC_CollectNoFail(PyThreadState *tstate)
during interpreter shutdown (and then never finish it). during interpreter shutdown (and then never finish it).
See http://bugs.python.org/issue8713#msg195178 for an example. See http://bugs.python.org/issue8713#msg195178 for an example.
*/ */
gc_collect_main(tstate, NUM_GENERATIONS - 1, _Py_GC_REASON_SHUTDOWN); return gc_collect_main(tstate, NUM_GENERATIONS - 1, _Py_GC_REASON_SHUTDOWN);
} }
void void
@ -1495,7 +1490,7 @@ _PyObject_GC_Link(PyObject *op)
{ {
PyThreadState *tstate = _PyThreadState_GET(); PyThreadState *tstate = _PyThreadState_GET();
GCState *gcstate = &tstate->interp->gc; GCState *gcstate = &tstate->interp->gc;
gcstate->young.count++; gcstate->generations[0].count++;
if (gc_should_collect(gcstate) && if (gc_should_collect(gcstate) &&
!_Py_atomic_load_int_relaxed(&gcstate->collecting)) !_Py_atomic_load_int_relaxed(&gcstate->collecting))
@ -1610,8 +1605,8 @@ PyObject_GC_Del(void *op)
#endif #endif
} }
GCState *gcstate = get_gc_state(); GCState *gcstate = get_gc_state();
if (gcstate->young.count > 0) { if (gcstate->generations[0].count > 0) {
gcstate->young.count--; gcstate->generations[0].count--;
} }
PyObject_Free(((char *)op)-presize); PyObject_Free(((char *)op)-presize);
} }

View File

@ -1030,7 +1030,7 @@ _extensions_cache_set(PyObject *filename, PyObject *name, PyModuleDef *def)
if (!already_set) { if (!already_set) {
/* We assume that all module defs are statically allocated /* We assume that all module defs are statically allocated
and will never be freed. Otherwise, we would incref here. */ and will never be freed. Otherwise, we would incref here. */
_Py_SetImmortal((PyObject *)def); _Py_SetImmortal(def);
} }
res = 0; res = 0;

View File

@ -1753,11 +1753,8 @@ class Frame(object):
return (name == 'take_gil') return (name == 'take_gil')
def is_gc_collect(self): def is_gc_collect(self):
'''Is this frame a collector within the garbage-collector?''' '''Is this frame gc_collect_main() within the garbage-collector?'''
return self._gdbframe.name() in ( return self._gdbframe.name() in ('collect', 'gc_collect_main')
'collect', 'gc_collect_full', 'gc_collect_main',
'gc_collect_young', 'gc_collect_increment'
)
def get_pyop(self): def get_pyop(self):
try: try: