Skip to content

A cycle through a closure's capture (object -> closure property -> captured object) is not collected by gc_collect_cycles(). #246

Closed

Description

@blacktrs

Summary

A cycle through a closure's capture (object -> closure property -> captured object) is not collected by gc_collect_cycles().

Repro

<?php
class Req
{
    public array $pad = [1, 2, 3, 4, 5, 6, 7, 8];
    private ?\Closure $factory = null;
    public function setFactory(\Closure $f): void { $this->factory = $f; }
}
$freed = 0;
$base = 0;
for ($i = 0; $i < 100000; $i++) {
    $r = new Req();
    $r->setFactory(function () use ($r) { return $r; });
    unset($r);
    if ($i % 1000 === 999) { $freed += gc_collect_cycles(); }
    if ($i === 1000) { $base = memory_get_peak_usage(); }
}
echo $freed > 0 ? "collected\n" : "not collected\n";
echo memory_get_peak_usage() - $base < 3000000 ? "flat\n" : "grows\n";

Expected (php)

collected
flat

Actual (manticore 0db98ae6, Darwin arm64)

not collected
grows

Tracking

Known-bug repro: tests/aot/repro/leak/closure_capture_cycle_not_collected.php — bash tests/aot/xfail.sh -k closure_capture_cycle_not_collected reports XFAIL while this is open and XPASS once it is fixed; then move the repro into tests/aot/cases/ and close this issue.

Activity

  1. added
    bug
    leak
    on Oct 13, 2026
  2. blacktrs commented on Oct 13, 2026

    @blacktrs
    ContributorAuthor

    Root of the per-request growth of a shared-Kernel Symfony app under Http\Server (~7-8 KB/request): AbstractSessionListener::onKernelRequest does $request->setSessionFactory(function () use ($request) {...}) on every main request, so each Request sits in a Request -> Closure -> Request cycle. leaks --atExit on the server (workers 0, 1000 requests) attributes 2.8 MB to that closure allocation, with the Request graph (HeaderBag arrays, strtr keys, ...) under it. Adding gc_collect_cycles() every 1000 requests frees 0 objects and RSS stays at +8.4 KB/request: the collector walks only rc obj properties, closures are excluded (their header and capture layout are not cycle nodes, see EmitLlvmRuntime per-class child walker comment). Fix needs closures as Bacon-Rajan nodes (colour bits, capture walker, white free) and add_root on closure release.

  3. added 2 commits that reference this issue on Oct 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugleak

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions