已开启
[Context] ContextFactory 类级全局 _instances 跨进程/测试不隔离 #35
henry创建于  7月7日
henry成员
7月7日 创建

现象

dataagent/core/context/context.py:74-76ContextFactory._instances / _n_instances类级全局字典,跨进程/测试不隔离:

class ContextFactory:
    _instances: dict[tuple, Context] = {}
    _n_instances: int = 0
    _lock = threading.Lock()

影响

  • 跨进程不共享:子 agent subprocess(sub_agent_entry.py)无法继承父进程的 _instances,每个进程独立计数,sub_id 从 0 开始可能与父进程冲突
  • 跨测试不隔离:测试间未显式调 clear_context() 会导致实例泄漏,后续测试读到上一轮残留状态
  • tests/ut/test_planner_prompt_builder.pytests/ut/flex/hooks/test_context_reference_rewriter.py 已发现多处缺 autouse fixture / teardown_method 清理

修复方案

任选其一或组合:

  1. atexit 清理:进程退出时调 clear_context()
  2. contextvars.ContextVar 隔离(每个 asyncio task / 线程独立 ContextFactory)
  3. 改为 WeakValueDictionary 让 GC 回收无引用的 Context
  4. 测试侧:所有相关测试文件加 autouse fixture:
@pytest.fixture(autouse=True)
def _clear_context_factory():
    ContextFactory.clear_context()
    yield
    ContextFactory.clear_context()

涉及文件

  • dataagent/core/context/context.py:74-76
  • tests/ut/test_planner_prompt_builder.py(缺 autouse fixture)
  • tests/ut/flex/hooks/test_context_reference_rewriter.py:273TestContextReferenceRewriterHelpers 缺 teardown_method)

验证

  • 单测:连续运行两个使用相同 user_id/session_id 的测试,断言第二个测试的 Context 不含第一个测试的轨迹节点。

严重性

major(跨进程/测试状态泄漏)

环境

  • 分支:0623
  • HEAD:c5c899a4196717d1eb5944a9736f766310655ef7
likedislike
xsmqxsmq成员
7月20日 关联了看板:@hwxsmq的看板 20260720