`TreeInterpreter` creates reference cycle, causing GC pressure

未关闭
#291 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

@sogav21 已经在做这个了。

开始于 2026年11月25日。

  • #398 来自 @sogav21 —— 未关闭

评估

难度
4/5
预计耗时
3-5 天
新手友好度
35/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
停滞
技术栈
python
领域
performance

调研方向

从 parser.py 中的 ParsedResult.search() 开始,检查 TreeInterpreter 的创建,然后阅读 visitor.py 中 Visitor._method_cache 附近的代码,以确认绑定方法引用循环。比较提议的解释器缓存方案,并运行提供的百万次迭代复现程序;当能够避免反复出现的 TreeInterpreter 循环及其相关的 GC 压力时,即视为完成。

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

描述

enhancement

We recently noticed that a heavy JMESpath workload was triggering a large number of garbage collection runs. We are using jmespath.compile(), and we tracked this down to the jmespath.visitor.TreeInterpreter that is created on every call to `ParsedResult.search(): https://github.com/jmespath/jmespath.py/blob/bbe7300c60056f52413603cf3e2bcd0b6afeda3d/jmespath/parser.py#L508

It appears that TreeInterpreter creates a reference cycle, which leads to the GC being triggered frequently to clean up the cycles. As far as I can tell, the problem comes from the Visitor._method_cache: https://github.com/jmespath/jmespath.py/blob/bbe7300c60056f52413603cf3e2bcd0b6afeda3d/jmespath/visitor.py#L91-L93

...which store references to methods that are bound to self in a member of self.

Possible solution

We worked around the problem by monkey patching ParsedResult so that it (1) caches a default_interpreter for use when options=None, and (2) uses it in search(). If I understand correctly, we could go further and use a global TreeInterpreter for all ParsedResult instances. The TreeInterpreter seems to be stateless apart from self._method_cache and that implementation seems to be thread-safe (with only the risk of multiple lookups for the same method in a multithreaded case).

I'd be happy to contribute a PR for either version if this would be welcome.

How to reproduce

The following reproducer shows the problem:

import jmespath

import gc
gc.set_debug(gc.DEBUG_COLLECTABLE)

pattern = jmespath.compile("foo")
value = {"foo": "bar"}

for _ in range(1000000):
    pattern.search(value)

...where the output contains one million repetitions of something like:

gc: collectable <TreeInterpreter 0x10f634fa0>
gc: collectable <dict 0x10f63e780>
gc: collectable <Options 0x10f634520>
gc: collectable <Functions 0x10f6345b0>
gc: collectable <method 0x10f63ee80>
gc: collectable <dict 0x10f63eb00>
主要语言
Python
星标
2.5k
派生
231
PR 合并指标
30 天内没有已合并 PR

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

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

jmespath/jmespath.py 的其他 Issue

查看 jmespath/jmespath.py 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

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