@@ -431,6 +431,52 @@ async def notmuch():
431431 self .assertEqual (t .get_name (), '123456789' )
432432 self .loop .run_until_complete (t )
433433
434+ # The free-threaded GC publishes allocation counts in batches, so the
435+ # collection cannot be scheduled to run inside get_name().
436+ @support .requires_gil_enabled ("needs precise GC scheduling" )
437+ def test_task_get_name_reentered_during_formatting (self ):
438+ # gh-158159: formatting the lazy default name can run the GC, and a
439+ # finalizer may call get_name() on the same task, replacing the name
440+ # the outer call is still formatting.
441+ loop = self .loop
442+ observed = {}
443+ keep = []
444+ task = None
445+
446+ class Reenter :
447+ def __init__ (self ):
448+ self .cycle = self
449+
450+ def __del__ (self ):
451+ observed ['inner' ] = task .get_name ()
452+ # Reuse the memory of a counter that was freed too early.
453+ keep .extend (10 ** 9 + i for i in range (8 ))
454+
455+ async def notmuch ():
456+ pass
457+
458+ async def scenario ():
459+ gc .collect ()
460+ Reenter ()
461+ old_threshold = gc .get_threshold ()
462+ gc .set_threshold (1 )
463+ try :
464+ scratch = [[0 ], [0 ], [0 ]] # schedule a collection
465+ observed ['outer' ] = task .get_name ()
466+ finally :
467+ gc .set_threshold (* old_threshold )
468+ del scratch
469+
470+ # Names are only freeable once the counter is past the small ints.
471+ for _ in range (1100 ):
472+ loop .run_until_complete (self .new_task (loop , notmuch (), name = None ))
473+ task = self .new_task (loop , scenario (), name = None )
474+ loop .run_until_complete (task )
475+
476+ self .assertRegex (observed ['outer' ], r'^Task-\d+$' )
477+ self .assertEqual (observed ['outer' ], observed ['inner' ])
478+ self .assertEqual (task .get_name (), observed ['outer' ])
479+
434480 def test_task_repr_name_not_str (self ):
435481 async def notmuch ():
436482 return 123
0 commit comments