Stateless closure cache: unbounded memory growth when the declaring closure has a heap runtime cache (bind/call/traits)

未关闭
#25,380 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
48/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
活跃
技术栈
c, php
领域
backend

调研方向

The report points to ZEND_DECLARE_LAMBDA_FUNCTION, EG(lambda_cache), and the heap runtime cache used for rebound closures; it does not name source files or tests. Start by tracing the stateless closure cache and compare its behavior for ordinary closures and closures rebound with Closure::bind(), Closure::bindTo(), or Closure::call(). Reproduce with the provided loop and memory measurement, then check that repeated calls no longer grow memory while the closure remains usable.

由索引模型根据 Issue 内容生成。

描述

Bug Status: Needs Triage
Description

ZEND_DECLARE_LAMBDA_FUNCTION caches a stateless (static fn) closure in the declaring function's runtime cache and pushes it onto EG(lambda_cache), which is only released at shutdown. When the declaring function is a closure that gets a fresh ZEND_ACC_HEAP_RT_CACHE on every creation/call (rebinding to another scope via Closure::bind()/bindTo(), Closure::call(), or a closure in a trait method used by more than one class), every call misses the cache and pushes another closure, so memory grows linearly for the whole request. This hurts long-running workers (e.g. Macroable-style Closure::bind($macro, null, static::class)).

The following code:

<?php
class A {}
$outer = function () { return (static fn() => 1)(); };
$m = memory_get_usage();
for ($i = 0; $i < 100000; $i++) {
    Closure::bind($outer, null, A::class)();
}
echo memory_get_usage() - $m, "\n";

Resulted in this output:

40243200

But I expected this output instead (as in PHP 8.5.12):

0

Trait variant, no explicit binding:

<?php
trait T {
    public function m($k) {
        $f = function () use ($k) { return (static fn($x) => $x + 1)($k); };
        return $f();
    }
}
class U1 { use T; }
class U2 { use T; }
(new U1)->m(0);
$u2 = new U2;
$m = memory_get_usage();
for ($i = 0; $i < 100000; $i++) { $u2->m($i); }
echo memory_get_usage() - $m, "\n";

8.6: 41843072, 8.5.12: 0.

$outer->bindTo(null, A::class)() and $outer->call($obj) grow the same way. The debug build reports no leak because EG(lambda_cache) is cleaned at shutdown. Introduced by f47cd216e95 (stateless closure cache). Reproduces with opcache off, on, and with tracing JIT.

PHP Version
PHP 8.6.1-dev (cli) (NTS DEBUG), PHP-8.6 @ dfc3219f341
Operating System

macOS (arm64)

主要语言
C
星标
41.8k
派生
8.5k
平均合并
2 天 13 小时
30 天内合并 PR
145

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

php/php-src 的其他 Issue

查看 php/php-src 的全部 Issue

相似的 Issue

更多 C Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。