Skip to content

Bugfix: 修复trace上报框架内部state的问题 - #376

Merged
helloopenworld merged 1 commit into
mainfrom
bugfix/trace_remove_internal_state
Nov 18, 2026
Merged

helloopenworld merged 1 commit into
mainfrom
bugfix/trace_remove_internal_state

Conversation

@weimch

@weimch weimch commented Nov 17, 2026

Copy link
Copy Markdown
Contributor
  • 之前有用户需求是希望能看到用户设置state的变化,把state上报上去了,但框架的一些内部state key没有筛选,导致上报了过多信息,现在修复这个问题 --story=140218514 修复trace上报框架内部state的问题

- 之前有用户需求是希望能看到用户设置state的变化,把state上报上去了,但框架的一些内部state key没有筛选,导致上报了过多信息,现在修复这个问题
@weimch
weimch force-pushed the bugfix/trace_remove_internal_state branch from ca8a5a2 to b19ff0f Compare November 17, 2026 11:55
@helloopenworld

Copy link
Copy Markdown
Contributor

AI Code Review

审查结论

通过

审查范围:base_commit 905698c..head_commit ca8a5a2,涉及 2 个文件(trpc_agent_sdk/telemetry/_trace.py 新增 _filter_state_for_trace 过滤函数并接入 5 个 trace 函数、tests/telemetry/test_trace.py 新增 11 个测试用例)。计划符合性:变更核心思路(按「下划线前缀」约定过滤会话 state 快照中的框架内部键)方向正确,已覆盖 trpc_graph、_trpc_agent:summary 等实际内部键,5 个 trace 入口(trace_runner/cancellation/agent/tool_call/merged_tool_calls)接入一致,过滤为纯顶层键操作、不改动 state 本身、None 透传语义合理。主要风险:过滤规则只认顶层下划线前缀,未覆盖不以下划线开头但确属框架内部的键——如 advanced_memory 的 advanced_memory_pending_request_context_fingerprint(BEFORE_MODEL 自动压缩路径默认启用时写入每个会话 state,仓库内无任何读取方,属纯框架簿记数据,仍会出现在每个 span 的 state.begin/end/partial 中),以及 docstring 声称要丢弃的 temp:skill: 技能缓存键(temp:skill:docs:demo 等仍原样上报);此外以 _ 开头的合法用户键会被静默丢弃,属于附带风险(无仓库内证据,影响有界)。测试充分性:新增测试覆盖了过滤函数的 None/空/嵌套/非字符串键边界与 5 个 trace 入口的接入点,但测试夹具中的 __trpc_agent_cancel 在仓库内无任何生产者,且未覆盖上述真实未过滤的内部键(fingerprint、temp:skill:*),对实现缺陷存在盲区。门禁结论:无高置信的严重(SEVERE)缺陷,修复主体达成预期目标,但过滤规则对框架内部键的识别不完整,存在 1 个中等级别的不完整修复问题与 2 个低级别问题,建议合入前补充过滤规则或完善测试覆盖。

发现的问题

中等

trpc_agent_sdk/telemetry/_trace.py:106-127

问题: _filter_state_for_trace 仅按「顶层键以 _ 开头」识别框架内部键,但仓库内存在不以下划线开头、确属框架内部的 state 键未被过滤:advanced_memory_pending_request_context_fingerprint(trpc_agent_sdk/sessions/compact/advanced/_token_budget.py:251 由 TokenContextTracker.record_request_context 写入,调用点在 _auto_compact.py:581 的 BEFORE_MODEL 自动压缩路径,该路径默认启用)以及 temp:skill:docs:/temp:skill:loaded:/temp:skill:tools: 等技能缓存键(trpc_agent_sdk/skills/_constants.py 定义,经 trpc_agent_sdk/sessions/_base_session_service.py 的 _apply_temp_state 进入 session.state)。这些键正是本次修复声称要丢弃的「框架内部 state」,与修复目的直接冲突。

触发条件: 任意会话开启 advanced memory 自动压缩(默认配置即启用)时,每次 LLM 生成前的 state 快照都会带上 fingerprint 键;加载过任意技能(写入 temp:skill:* 缓存键)的会话,其 trace 属性会带上技能文档全文缓存。

实际影响: trace 上报仍包含框架内部簿记数据和技能缓存内容,本次修复的「只上报用户 state」目标未完全达成;fingerprint 为模型配置与请求上下文的序列化结果,冗余暴露在每次 span 中;技能缓存文档可能体积较大,造成每个 span 的 state 属性膨胀,与 docstring 所述「bloat every span」的动机相悖。

修正方向: 将过滤规则从单一的下划线启发式扩展为「下划线前缀 + 显式内部键/前缀白名单」的组合,例如复用或扩展 dsl/graph/_constants.py 已有的 is_graph_internal_state_key 模式,新增针对 advanced_memory_pending_request_context_fingerprint 与 temp:skill: 前缀的判定(可通过 dsl/graph/_constants.py 的 is_graph_internal_state_key 或独立常量维护),并在 docstring 中同步说明。

较低

trpc_agent_sdk/telemetry/_trace.py:127

问题: 过滤规则 key.startswith("_") 会无差别丢弃所有以 _ 开头的顶层键,包括用户自定义、不以 _trpc_* 为约定的用户状态键,而框架自身的键名约定(app:/user:/temp: 前缀)与下划线命名并无强制关联。

触发条件: 用户会话 state 中存在以单个或多个 _ 开头的合法业务键(如 _custom_flag、_retry_count 等自定义键)时,trace 快照将删除这些键。

实际影响: 这些用户数据不会丢失(session.state 本身未变),但从 trace 的 state.begin/state.end/state.partial 属性中消失,导致基于 trace 的调试与状态回放缺失用户可见的关键信息,属于对合法数据的附带误删。

修正方向: 将过滤范围收窄到框架内部键的确定性集合:仅丢弃已知内部前缀(如 _trpc_、_trpc_graph_、已定义常量的内部键名),而非所有下划线开头键;如确需保留宽泛规则,至少在 docstring 中明确该行为并让用户知晓自定义下划线键不会被上报。

较低

tests/telemetry/test_trace.py:1285-1299

问题: 新增测试的夹具与真实仓库脱节:_INTERNAL_STATE 中的 __trpc_agent_cancel 在全部源码中不存在任何生产者(grep 全仓仅测试自身出现),属于虚构键;而真实未被过滤的内部键 advanced_memory_pending_request_context_fingerprint 完全没有测试覆盖;同时 test_keeps_user_scoped_keys(tests/telemetry/test_trace.py:1317-1324)明确断言 temp:skill:docs:demo 应保留,与实现 docstring「skill caches 应被丢弃」的声明及修复目的相矛盾,测试固化了这一缺陷。

触发条件: 后续任何人修改过滤规则时,测试无法捕获「fingerprint 键未过滤」「技能缓存键未过滤」这两类真实回归;若某日有人按 docstring 修复 temp:skill:* 过滤,现有断言会直接失败。

实际影响: 测试通过并不代表修复达成预期目标,真实遗留问题(内部键继续外泄、技能缓存继续膨胀 span)在 CI 中不可见,测试对实现的校验能力弱于其呈现的覆盖度。

修正方向: 用真实存在的内部键(advanced_memory_pending_request_context_fingerprint、temp:skill:docs: 等)替换或补充夹具;将 temp:skill:* 的保留断言与 docstring 声明对齐——要么文档去掉「skill caches」的说法,要么按修复意图将 temp:skill:* 加入过滤并更新断言。

Comment on lines +106 to +127
def _filter_state_for_trace(state: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
"""Drop framework-internal keys from a session-state snapshot.

Internal state keys are identified by the leading underscore convention
(for example ``_trpc_graph_checkpoints`` or ``__trpc_agent_cancel``).
They are bookkeeping/continuation data that trace consumers cannot use,
and some of them (graph checkpoints, skill caches) can be large enough to
bloat every span that snapshots the state.

Only top-level keys are filtered: values nested under a user state key
are user data and are left untouched. ``None`` is passed through so
callers can keep "state not captured" distinct from "empty state".

Args:
state: The session-state snapshot to filter.

Returns:
A filtered copy of the snapshot, or ``None`` when ``state`` is ``None``.
"""
if state is None:
return None
return {key: value for key, value in state.items() if not (isinstance(key, str) and key.startswith("_"))}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题: _filter_state_for_trace 仅按「顶层键以 _ 开头」识别框架内部键,但仓库内存在不以下划线开头、确属框架内部的 state 键未被过滤:advanced_memory_pending_request_context_fingerprint(trpc_agent_sdk/sessions/compact/advanced/_token_budget.py:251 由 TokenContextTracker.record_request_context 写入,调用点在 _auto_compact.py:581 的 BEFORE_MODEL 自动压缩路径,该路径默认启用)以及 temp:skill:docs:/temp:skill:loaded:/temp:skill:tools: 等技能缓存键(trpc_agent_sdk/skills/_constants.py 定义,经 trpc_agent_sdk/sessions/_base_session_service.py 的 _apply_temp_state 进入 session.state)。这些键正是本次修复声称要丢弃的「框架内部 state」,与修复目的直接冲突。

触发条件: 任意会话开启 advanced memory 自动压缩(默认配置即启用)时,每次 LLM 生成前的 state 快照都会带上 fingerprint 键;加载过任意技能(写入 temp:skill:* 缓存键)的会话,其 trace 属性会带上技能文档全文缓存。

实际影响: trace 上报仍包含框架内部簿记数据和技能缓存内容,本次修复的「只上报用户 state」目标未完全达成;fingerprint 为模型配置与请求上下文的序列化结果,冗余暴露在每次 span 中;技能缓存文档可能体积较大,造成每个 span 的 state 属性膨胀,与 docstring 所述「bloat every span」的动机相悖。

修正方向: 将过滤规则从单一的下划线启发式扩展为「下划线前缀 + 显式内部键/前缀白名单」的组合,例如复用或扩展 dsl/graph/_constants.py 已有的 is_graph_internal_state_key 模式,新增针对 advanced_memory_pending_request_context_fingerprint 与 temp:skill: 前缀的判定(可通过 dsl/graph/_constants.py 的 is_graph_internal_state_key 或独立常量维护),并在 docstring 中同步说明。

"""
if state is None:
return None
return {key: value for key, value in state.items() if not (isinstance(key, str) and key.startswith("_"))}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题: 过滤规则 key.startswith("_") 会无差别丢弃所有以 _ 开头的顶层键,包括用户自定义、不以 _trpc_* 为约定的用户状态键,而框架自身的键名约定(app:/user:/temp: 前缀)与下划线命名并无强制关联。

触发条件: 用户会话 state 中存在以单个或多个 _ 开头的合法业务键(如 _custom_flag、_retry_count 等自定义键)时,trace 快照将删除这些键。

实际影响: 这些用户数据不会丢失(session.state 本身未变),但从 trace 的 state.begin/state.end/state.partial 属性中消失,导致基于 trace 的调试与状态回放缺失用户可见的关键信息,属于对合法数据的附带误删。

修正方向: 将过滤范围收窄到框架内部键的确定性集合:仅丢弃已知内部前缀(如 _trpc_、_trpc_graph_、已定义常量的内部键名),而非所有下划线开头键;如确需保留宽泛规则,至少在 docstring 中明确该行为并让用户知晓自定义下划线键不会被上报。

Comment on lines +1285 to +1299
_INTERNAL_STATE = {
"user_key": "keep",
"app:shared": "keep",
"user:pref": "keep",
"todos:root": ["keep"],
"temp:skill:docs:demo": "keep",
"_trpc_graph_checkpoints": {
"thread-1": "blob"
},
"_trpc_graph_pending_interrupt": True,
"_trpc_agent:summary": {
"title": "internal"
},
"__trpc_agent_cancel": False,
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题: 新增测试的夹具与真实仓库脱节:_INTERNAL_STATE 中的 __trpc_agent_cancel 在全部源码中不存在任何生产者(grep 全仓仅测试自身出现),属于虚构键;而真实未被过滤的内部键 advanced_memory_pending_request_context_fingerprint 完全没有测试覆盖;同时 test_keeps_user_scoped_keys(tests/telemetry/test_trace.py:1317-1324)明确断言 temp:skill:docs:demo 应保留,与实现 docstring「skill caches 应被丢弃」的声明及修复目的相矛盾,测试固化了这一缺陷。

触发条件: 后续任何人修改过滤规则时,测试无法捕获「fingerprint 键未过滤」「技能缓存键未过滤」这两类真实回归;若某日有人按 docstring 修复 temp:skill:* 过滤,现有断言会直接失败。

实际影响: 测试通过并不代表修复达成预期目标,真实遗留问题(内部键继续外泄、技能缓存继续膨胀 span)在 CI 中不可见,测试对实现的校验能力弱于其呈现的覆盖度。

修正方向: 用真实存在的内部键(advanced_memory_pending_request_context_fingerprint、temp:skill:docs: 等)替换或补充夹具;将 temp:skill:* 的保留断言与 docstring 声明对齐——要么文档去掉「skill caches」的说法,要么按修复意图将 temp:skill:* 加入过滤并更新断言。

@helloopenworld

Copy link
Copy Markdown
Contributor

AI Code Review

审查结论

不通过

审查范围:905698c..b19ff0f,共 2 个文件(trpc_agent_sdk/telemetry/_trace.py 与 tests/telemetry/test_trace.py),+197/-10 行。计划符合性:变更实现了"trace 上报过滤框架内部 state"的核心机制——新增 _filter_state_for_trace(顶层下划线键过滤)并覆盖全部 10 处 state.begin/.end/.partial 序列化点,测试(TestFilterStateForTrace、TestTraceStateFiltering 共 9 个用例)覆盖了基本过滤、None/空 dict、嵌套键、非字符串键与 5 个 trace 函数入口,未发现崩溃或运行时回归(本机无 pytest/python3.10 无法执行测试,结论基于静态证据)。主要风险:(1) 过滤语义与仓库既有集中式内部键判定(UNSAFE_STATE_KEYS/is_graph_internal_state_key/temp: 前缀)不一致——_trpc_agent:summary(用户可读会话记忆)被误删,而真正的大负载 temp:skill:* 与 session/exec_context 等非下划线内部键仍泄露,且测试把该遗漏固化为预期;(2) _filter_state_for_trace 对非 dict 输入抛 AttributeError,而调用点位于 runner 的取消/清理异常处理路径内,可能把正常取消变成未处理异常;(3) trace_merged_tool_calls 的测试用 MagicMock 掩盖真实路径。测试充分性:核心过滤逻辑有直接单测与 5 个入口集成测试,但缺少 temp: 键、session 对象、非 dict 值、真实合并事件等边界覆盖。门禁结论:由于存在中等严重度问题(摘要键误删造成用户数据在观测链路丢失,以及非 dict 崩溃路径),本审查判定为不通过(FAILED),建议修正过滤器语义与健壮性后合入。

发现的问题

中等

trpc_agent_sdk/telemetry/_trace.py:106-127

问题: 新过滤器按 key.startswith("_") 把所有下划线开头的顶层键一律丢弃,_SESSION_MEMORY_STATE_KEY = "_trpc_agent:summary"(trpc_agent_sdk/sessions/compact/advanced/_formats.py:28,由 _compaction_memory_extractor.py:672 通过 update_session_state 写入 session.state)也属于用户可读的会话记忆数据(示例 examples/session_summarizer_with_advanced/run_agent.py 直接从 session.state 读取并打印),并非纯框架簿记;它被一并从所有 state.begin/.end/.partial 属性中删除。

触发条件: 启用 Session Compact/记忆摘要的会话每次运行后都会产生 _trpc_agent:summary 键;过滤发生在 _trace.py:197-203 等全部 10 处 _safe_json_serialize(_filter_state_for_trace(...)) 调用中。

实际影响: 该键承载用户的会话目标、任务规格、关键结果等结构化记忆内容,是每次迭代快照中数据量最大的用户数据键;本次变更使其在 trace/数据平台(langfuse metadata 中的 state_begin/state_end)里完全不可见,同时 AG-UI 快照过滤(_event_translator.py:619,644 仅过滤 _trpc_graph_*)仍会把它发给客户端,形成同一 state 在不同出口互相矛盾,并造成用户记忆数据在观测链路的丢失。

修正方向: 在 _filter_state_for_trace 中对 _trpc_agent:summary(或更一般地,按 _trpc_agent:/__trpc_agent_* 与用户可见摘要键区分)做例外保留,或改为复用集中式判定(is_graph_internal_state_key/UNSAFE_STATE_KEYS)并显式列出要过滤的键集合,而不是一刀切删除所有下划线键。

中等

tests/telemetry/test_trace.py:1317-1324

问题: 过滤器只处理顶层下划线键,框架内部状态的其他命名空间全部漏掉:temp: 前缀键(State.TEMP_PREFIX = "temp:",_base_session_service.py:117-127 明确将其视为临时内部状态、不持久化)——其中 temp:skill:docs:*、temp:skill:loaded:*、temp:skill:artifacts 等(skills/_constants.py:26-58)恰恰是提交说明和 docstring 声称要解决的"大对象撑爆 span"的那类数据;此外 UNSAFE_STATE_KEYS(dsl/graph/_constants.py:174-190)中的非下划线键 session、exec_context、current_node_id、tool_callbacks 等仍原样进入 trace。

触发条件: 任何使用 skill 加载/技能选择(写入 temp:skill:docs:<skill> 等键)、或多智能体/图场景(session.state 中含 session/exec_context)的会话,进行 runner/agent/tool span 快照时。

实际影响: 修复目标只实现了一小半:真正的超大内部负载(skill 文档/工具缓存等 temp: 键)仍然每个 span 都上报;同时新的测试(test_trace.py:1324 断言 temp:skill:docs:demo 被保留)把这一遗漏固化为预期行为,且活 Session 对象等非下划线内部键序列化后以 "<not serializable>" 或整对象 dump 形式泄露。

修正方向: 扩展过滤器以覆盖 temp: 前缀和 UNSAFE_STATE_KEYS 集合(合并为单一判定函数),并在测试中覆盖 temp:skill:*、session 键被过滤的场景,修正 test_keeps_user_scoped_keys 对 temp: 键的断言。

中等

trpc_agent_sdk/telemetry/_trace.py:125-127

问题: 变更把对 state 快照的处理从 _safe_json_serialize(state_*)(可接受任意对象,失败时降级为字符串哨兵)改为先调用 _filter_state_for_trace(内部执行 state.items(),对非 dict 直接抛 AttributeError)。所有调用方(runners.py:438/646/710、_base_agent.py:282/363、_tools_processor.py:211/389/447 等)都来自 dict(session.state) 并混入 event.actions.state_delta(dict[str, object]),用户工具/状态补丁可以把任意非 dict 值写进这些键,旧代码可容忍,新代码会崩溃。

触发条件: 用户工具或事件将 session.state 的某个顶层键设为非 dict 值(或 session.state 本身被替换为非 dict)后,任何一次 runner/agent/tool span 的 state 快照序列化。

实际影响: trace_* 在 runners.py 的 except RunCancelledException: 与 finally: 块内被调用——_filter_state_for_trace 抛出的 AttributeError 不在 _safe_json_serialize 的 except (TypeError, OverflowError) 覆盖范围内,会从取消处理器/清理路径直接冒泡,把一次正常的用户取消变成未处理异常(500),或静默丢掉整条 span 属性;旧版本在此类输入下只会得到 "" 字符串。

修正方向: 在 _filter_state_for_trace 内对非 dict 输入做兜底(如 if not isinstance(state, dict): return state),或把过滤合并进 _safe_json_serialize 的 try/except 保护范围内,保证追踪路径永不因 state 形状异常而抛异常。

较低

tests/telemetry/test_trace.py:1412-1427

问题: test_trace_merged_tool_calls_filters_state(test_trace.py:1412-1427)以 MagicMock 作为 function_response_event 调用 trace_merged_tool_calls;真实路径(_tools_processor.py:250)传入的是 merged_event.actions.state_delta 参与构建的 state_end,且 trace_merged_tool_calls 内部会调用 event.model_dumps_json(exclude_none=True) 与 event.id。MagicMock 会自动满足这些调用,测试只验证了过滤函数本身,没有覆盖真实合并路径上 state 快照与事件混合的场景。

触发条件: 当并行工具调用合并(len(function_response_events) > 1)触发 trace_merged_tool_calls,且 state_end 包含事件 state_delta 中的非 dict 值等真实数据时,本测试无法发现回归。

实际影响: 该测试与 test_trace_tool_call_filters_state 覆盖路径重叠但掩盖了 trace_merged_tool_calls 的真实传参形态;将来若该函数其他参数契约变化(如 model_dumps_json 失败分支),回归不会被发现。

修正方向: 用真实的 Event 构造(可参考 _tools_processor 的 _merge_parallel_function_response_events 产物)或至少显式设置 model_dumps_json 返回非法 JSON 的分支断言,替换 MagicMock。

较低

trpc_agent_sdk/telemetry/_trace.py:197-199

问题: 过滤函数及 10 处调用点各自重复 _safe_json_serialize(_filter_state_for_trace(x)) 和 if x is not None: 守卫(_trace.py:197-203, 278-283, 343-349, 417-423, 474-480),且 _filter_state_for_trace 无条件为每次 span 快照新建整个字典(O(n) 键拷贝),即使没有任何下划线键可过滤时也照做。

触发条件: 每个 runner/agent/工具/合并工具 span 各创建 2 份过滤拷贝(runners.py:671/723、_tools_processor.py:253/456/618/645 等全部调用点),会话 state 较大时每轮多份分配。

实际影响: 代码量重复(约 40 行可收敛为 ~10 行),且热路径上产生无谓分配;对大型 state(多 .items() 迭代 + 新 dict)虽不构成量级问题,但与修复目标"避免大对象"相悖。

修正方向: 抽出单一辅助函数(如 _serialize_state_for_trace(state),内部含 None 守卫与过滤),并加无下划线键时的快速返回(调用方传入的 dict(session.state) 拷贝在调用后不再被修改,可安全复用原字典)。

Comment on lines +106 to +127
def _filter_state_for_trace(state: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
"""Drop framework-internal keys from a session-state snapshot.

Internal state keys are identified by the leading underscore convention
(for example ``_trpc_graph_checkpoints`` or ``__trpc_agent_cancel``).
They are bookkeeping/continuation data that trace consumers cannot use,
and some of them (graph checkpoints, skill caches) can be large enough to
bloat every span that snapshots the state.

Only top-level keys are filtered: values nested under a user state key
are user data and are left untouched. ``None`` is passed through so
callers can keep "state not captured" distinct from "empty state".

Args:
state: The session-state snapshot to filter.

Returns:
A filtered copy of the snapshot, or ``None`` when ``state`` is ``None``.
"""
if state is None:
return None
return {key: value for key, value in state.items() if not (isinstance(key, str) and key.startswith("_"))}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题: 新过滤器按 key.startswith("_") 把所有下划线开头的顶层键一律丢弃,_SESSION_MEMORY_STATE_KEY = "_trpc_agent:summary"(trpc_agent_sdk/sessions/compact/advanced/_formats.py:28,由 _compaction_memory_extractor.py:672 通过 update_session_state 写入 session.state)也属于用户可读的会话记忆数据(示例 examples/session_summarizer_with_advanced/run_agent.py 直接从 session.state 读取并打印),并非纯框架簿记;它被一并从所有 state.begin/.end/.partial 属性中删除。

触发条件: 启用 Session Compact/记忆摘要的会话每次运行后都会产生 _trpc_agent:summary 键;过滤发生在 _trace.py:197-203 等全部 10 处 _safe_json_serialize(_filter_state_for_trace(...)) 调用中。

实际影响: 该键承载用户的会话目标、任务规格、关键结果等结构化记忆内容,是每次迭代快照中数据量最大的用户数据键;本次变更使其在 trace/数据平台(langfuse metadata 中的 state_begin/state_end)里完全不可见,同时 AG-UI 快照过滤(_event_translator.py:619,644 仅过滤 _trpc_graph_*)仍会把它发给客户端,形成同一 state 在不同出口互相矛盾,并造成用户记忆数据在观测链路的丢失。

修正方向: 在 _filter_state_for_trace 中对 _trpc_agent:summary(或更一般地,按 _trpc_agent:/__trpc_agent_* 与用户可见摘要键区分)做例外保留,或改为复用集中式判定(is_graph_internal_state_key/UNSAFE_STATE_KEYS)并显式列出要过滤的键集合,而不是一刀切删除所有下划线键。

Comment on lines +1317 to +1324
def test_keeps_user_scoped_keys(self):
filtered = _filter_state_for_trace(_INTERNAL_STATE)

assert filtered["user_key"] == "keep"
assert filtered["app:shared"] == "keep"
assert filtered["user:pref"] == "keep"
assert filtered["todos:root"] == ["keep"]
assert filtered["temp:skill:docs:demo"] == "keep"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题: 过滤器只处理顶层下划线键,框架内部状态的其他命名空间全部漏掉:temp: 前缀键(State.TEMP_PREFIX = "temp:",_base_session_service.py:117-127 明确将其视为临时内部状态、不持久化)——其中 temp:skill:docs:*、temp:skill:loaded:*、temp:skill:artifacts 等(skills/_constants.py:26-58)恰恰是提交说明和 docstring 声称要解决的"大对象撑爆 span"的那类数据;此外 UNSAFE_STATE_KEYS(dsl/graph/_constants.py:174-190)中的非下划线键 session、exec_context、current_node_id、tool_callbacks 等仍原样进入 trace。

触发条件: 任何使用 skill 加载/技能选择(写入 temp:skill:docs:<skill> 等键)、或多智能体/图场景(session.state 中含 session/exec_context)的会话,进行 runner/agent/tool span 快照时。

实际影响: 修复目标只实现了一小半:真正的超大内部负载(skill 文档/工具缓存等 temp: 键)仍然每个 span 都上报;同时新的测试(test_trace.py:1324 断言 temp:skill:docs:demo 被保留)把这一遗漏固化为预期行为,且活 Session 对象等非下划线内部键序列化后以 "<not serializable>" 或整对象 dump 形式泄露。

修正方向: 扩展过滤器以覆盖 temp: 前缀和 UNSAFE_STATE_KEYS 集合(合并为单一判定函数),并在测试中覆盖 temp:skill:*、session 键被过滤的场景,修正 test_keeps_user_scoped_keys 对 temp: 键的断言。

Comment on lines +125 to +127
if state is None:
return None
return {key: value for key, value in state.items() if not (isinstance(key, str) and key.startswith("_"))}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题: 变更把对 state 快照的处理从 _safe_json_serialize(state_*)(可接受任意对象,失败时降级为字符串哨兵)改为先调用 _filter_state_for_trace(内部执行 state.items(),对非 dict 直接抛 AttributeError)。所有调用方(runners.py:438/646/710、_base_agent.py:282/363、_tools_processor.py:211/389/447 等)都来自 dict(session.state) 并混入 event.actions.state_delta(dict[str, object]),用户工具/状态补丁可以把任意非 dict 值写进这些键,旧代码可容忍,新代码会崩溃。

触发条件: 用户工具或事件将 session.state 的某个顶层键设为非 dict 值(或 session.state 本身被替换为非 dict)后,任何一次 runner/agent/tool span 的 state 快照序列化。

实际影响: trace_* 在 runners.py 的 except RunCancelledException: 与 finally: 块内被调用——_filter_state_for_trace 抛出的 AttributeError 不在 _safe_json_serialize 的 except (TypeError, OverflowError) 覆盖范围内,会从取消处理器/清理路径直接冒泡,把一次正常的用户取消变成未处理异常(500),或静默丢掉整条 span 属性;旧版本在此类输入下只会得到 "" 字符串。

修正方向: 在 _filter_state_for_trace 内对非 dict 输入做兜底(如 if not isinstance(state, dict): return state),或把过滤合并进 _safe_json_serialize 的 try/except 保护范围内,保证追踪路径永不因 state 形状异常而抛异常。

Comment on lines +1412 to +1427
def test_trace_merged_tool_calls_filters_state(self, mock_get_span):
span = _mock_span()
mock_get_span.return_value = span

event = MagicMock()
event.model_dumps_json = MagicMock(return_value="{}")

trace_merged_tool_calls(
response_event_id="re-1",
function_response_event=event,
state_begin=_INTERNAL_STATE,
state_end=_INTERNAL_STATE,
)

assert _state_attribute(span, "state.begin") == _VISIBLE_STATE
assert _state_attribute(span, "state.end") == _VISIBLE_STATE

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题: test_trace_merged_tool_calls_filters_state(test_trace.py:1412-1427)以 MagicMock 作为 function_response_event 调用 trace_merged_tool_calls;真实路径(_tools_processor.py:250)传入的是 merged_event.actions.state_delta 参与构建的 state_end,且 trace_merged_tool_calls 内部会调用 event.model_dumps_json(exclude_none=True) 与 event.id。MagicMock 会自动满足这些调用,测试只验证了过滤函数本身,没有覆盖真实合并路径上 state 快照与事件混合的场景。

触发条件: 当并行工具调用合并(len(function_response_events) > 1)触发 trace_merged_tool_calls,且 state_end 包含事件 state_delta 中的非 dict 值等真实数据时,本测试无法发现回归。

实际影响: 该测试与 test_trace_tool_call_filters_state 覆盖路径重叠但掩盖了 trace_merged_tool_calls 的真实传参形态;将来若该函数其他参数契约变化(如 model_dumps_json 失败分支),回归不会被发现。

修正方向: 用真实的 Event 构造(可参考 _tools_processor 的 _merge_parallel_function_response_events 产物)或至少显式设置 model_dumps_json 返回非法 JSON 的分支断言,替换 MagicMock。

Comment on lines 197 to +199
if state_begin is not None:
span.set_attribute(f"{_trpc_agent_span_name}.state.begin", _safe_json_serialize(state_begin))
span.set_attribute(f"{_trpc_agent_span_name}.state.begin",
_safe_json_serialize(_filter_state_for_trace(state_begin)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题: 过滤函数及 10 处调用点各自重复 _safe_json_serialize(_filter_state_for_trace(x)) 和 if x is not None: 守卫(_trace.py:197-203, 278-283, 343-349, 417-423, 474-480),且 _filter_state_for_trace 无条件为每次 span 快照新建整个字典(O(n) 键拷贝),即使没有任何下划线键可过滤时也照做。

触发条件: 每个 runner/agent/工具/合并工具 span 各创建 2 份过滤拷贝(runners.py:671/723、_tools_processor.py:253/456/618/645 等全部调用点),会话 state 较大时每轮多份分配。

实际影响: 代码量重复(约 40 行可收敛为 ~10 行),且热路径上产生无谓分配;对大型 state(多 .items() 迭代 + 新 dict)虽不构成量级问题,但与修复目标"避免大对象"相悖。

修正方向: 抽出单一辅助函数(如 _serialize_state_for_trace(state),内部含 None 守卫与过滤),并加无下划线键时的快速返回(调用方传入的 dict(session.state) 拷贝在调用后不再被修改,可安全复用原字典)。

"""
if state is None:
return None
return {key: value for key, value in state.items() if not (isinstance(key, str) and key.startswith("_"))}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

代码评审结论
建议:Request Changes,修正过滤规则后再合入。

实现结构简单,接入点完整,CI 的 test、lint、build、安全扫描也全部通过。但目前“框架内部 state”的识别规则不可靠:既会漏删,也会误删。

  1. 中等:真正的大体积内部状态仍会上报
    过滤函数只删除 _ 开头的 key,但仓库中存在明确的非下划线内部状态:

temp:skill:docs:*
temp:skill:tools:*
temp:skill:artifacts
advanced_memory_pending_request_context_fingerprint
特别是 temp:skill:docs:* 可能包含完整技能文档,正是最容易造成 Span 膨胀的数据。然而测试还明确断言它应当保留:

assert filtered["temp:skill:docs:demo"] == "keep"
这也和函数注释中“过滤 skill caches”的描述直接矛盾。因此当前修复只能过滤 Graph checkpoint 等下划线状态,不能完整实现 PR 声称的目标。

建议至少过滤:

State.TEMP_PREFIX,即 temp:
Advanced Memory fingerprint
GraphAgent 已定义的内部/unsafe key
2. 中等:会误删合法用户状态
当前规则是:

key.startswith("_")
因此 _custom_flag、_retry_count 等用户自定义状态也会从 Trace 中消失。框架的 State 类型只规定了 app:、user:、temp: 等作用域,并没有规定所有下划线 key 都属于框架。

这与“保留用户设置 state 的变化”存在冲突。建议基于明确的内部 key/prefix 判定,而不是通配所有下划线 key,例如:

trpc_graph
_trpc_agent
temp:
明确列出的内部 key
至于 _trpc_agent:summary 是否应过滤,需要产品语义确认:它由框架生成,但内容对用户可读。当前测试选择过滤它,应把这一行为明确写进 Trace 契约。

@helloopenworld
helloopenworld merged commit 3098916 into main Nov 18, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants