php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Object holding a suspended Fiber of a closure bound to it is no longer collected (regression from GH-24134)

Open vudaltsov opened this issue 1 week ago • 1 comments

Description

Since #24134, an object that stores a suspended fiber whose callable is a closure bound to that object is never freed, not even by gc_collect_cycles(). Every Revolt event loop driver has this shape (its loop and callback fibers are closures over $this), so a driver that has run once is never freed, with its file descriptors. A test suite that creates a driver per test runs out of file descriptors.

<?php

final class Loop
{
    public Fiber $fiber;

    public function __construct()
    {
        $this->fiber = new Fiber(function () {
            while (true) {
                Fiber::suspend();
            }
        });
    }
}

$loop = new Loop();
$loop->fiber->start();
$weak = WeakReference::create($loop);
unset($loop);
gc_collect_cycles();
var_dump($weak->get() === null);

// The same cycle through `use` of a static closure is still collected.
$object = new stdClass();
$object->fiber = new Fiber(static function () use ($object) {
    Fiber::suspend();
});
$object->fiber->start();
$weak = WeakReference::create($object);
unset($object);
gc_collect_cycles();
var_dump($weak->get() === null);

Resulted in this output (PHP 8.6.0RC7, ZTS):

bool(false)
bool(true)

But I expected this output instead (PHP 8.5.12, NTS):

bool(true)
bool(true)

#24134 (67decbe81a) adds a reference to fci.object in Fiber::__construct() and reports it in zend_fiber_get_gc_callable(). It is in php-8.6.0RC7 and not in php-8.5.12 or php-8.4.16, and it is already on the branches PHP-8.4 and PHP-8.5, so 8.4.17 and 8.5.13 would ship the regression.

With Revolt (revolt/event-loop), any driver after run() stays alive:

$driver = new Revolt\EventLoop\Driver\StreamSelectDriver(); // Uv, Ev, Event: the same
$driver->defer(static fn() => null);
$driver->run();
$weak = WeakReference::create($driver);
unset($driver);
gc_collect_cycles();
var_dump($weak->get() === null); // false on 8.6.0RC7, true on 8.5.12

PHP Version

PHP 8.6.0RC7 (cli) (built: Nov 13 2026) (ZTS)

Operating System

Linux (Docker)

vudaltsov avatar Nov 17 '26 23:11 vudaltsov

I'd like to work on this

akasakariko avatar Nov 18 '26 11:11 akasakariko