Skip to content

feat(ai): add trace discovery and diagnosis tools for the AI assistant - #1618

Open
ambiguous-pointer wants to merge 3 commits into
apache:aifrom
ambiguous-pointer:feat/ai_trace_diagnosis
Open

ambiguous-pointer wants to merge 3 commits into
apache:aifrom
ambiguous-pointer:feat/ai_trace_diagnosis

Conversation

@ambiguous-pointer

@ambiguous-pointer ambiguous-pointer commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

概要

让 AI 助手能自主发现并诊断 Dubbo 业务的分布式链路:不需要人先提供 traceId,助手自己按服务与时间窗找出候选链路,再算出关键路径、服务维度耗时、错误根因与调用依赖。

这是周会条目「trace 的观测加强」中 Agent 去诊断业务链路 的那一半。
Agent 自身行为的可观测性(怎么调用的、用了哪些 tools、思考过程、输入输出)是另一件事,见 #1616。


为什么需要

助手能查日志、能查指标,唯独不能查链路——只要问题停在「最近 X 服务有没有失败请求」这一层,它就必须先把问题退回给用户索要 traceId,观测能力形同虚设。

即使拿到了 traceId,原始 span 也是事实而不是结论:

  • 哪个 span 真正消耗了时间?原始 span 只有各自的 duration,看不出父子之间的等待关系;
  • 慢在哪个服务?并发场景下各服务耗时会重叠,不能直接相加;
  • 错误是根因还是被冒泡?上游往往因为下游失败而一起标红,但根因只有一个;
  • 服务之间的调用关系?隐含在 parentSpanId 里,没有被提炼出来。

Agent 需要的是结论,否则它拿到一堆 span 还是要自己做一遍精确的时间轴推理,而 LLM 做这件事非常不可靠。


改了什么

能力 说明
search_traces 按服务、操作、traceId、标签、时间窗、最小耗时检索链路,返回有界的逐条摘要(根服务与操作、耗时、span 数、错误 span 数、服务数、是否含错误、是否 GenAI 链路)
analyze_trace 把一条链路变成结论:延迟关键路径(每跳的 self time 与 wait time)、服务维度耗时分解、最慢 span、失败 span 及其错误分类与根因标记、调用依赖边
Provider.SearchTraces Provider 接口新增检索方法,接入新后端不需要动工具层

关键设计

先发现,后分析。 助手能查日志、能查指标,唯独不能查链路——只要问题停在「最近 X 服务有没有失败请求」这一层,它就必须先把问题退回给用户索要 traceId,观测能力形同虚设。所以第一件事是让 provider 支持检索,而不是先去做更复杂的分析。

诊断逻辑做成纯函数。 BuildTraceAnalysis(trace *Trace) *TraceAnalysis 输入是已归一化的 Trace,输出是结论。好处有三个:算法可以完全脱离后端做单测;将来接入 Tempo 时分析逻辑一行不用改;算法与传输解耦,不会被某个 provider 的特殊行为污染。

self time 用区间并集算,不重���。 一个 span 的总时长里大部分可能是它在等子 span。self time = 总时长减去子 span 覆盖区间的并集(重叠的子 span 不能重复计数)。

关键路径走「结束时间最晚」的那一支。 从「结束最晚的根」出发,每一跳走向「结束最晚的子节点」——那是父 span 内最后完成的活动,决定了父 span 的完成时刻。

错误根因 = 没有失败后代的失败 span。 上游 span 往往因为下游失败而一起标红,但根因只有一个。判据是「它的子树里还有没有别的失败 span」。

摘要基于全部原始 span,细节路径维持原样。 get_trace_by_id 的归一化会把 span 裁剪到 500 条并丢弃属性——那是它作为「取原始链路」工具的合理取舍。但检索摘要若复用这条路径,根操作名、错误数、服务集合就都不可信了。所以摘要单独实现,遍历全部原始 span;而 get_trace_by_id 的行为完全未变,避免对已发布工具造成回归。

有界响应。 Agent 的上下文是有限的。所有列表都有上限,所有截断都会在 payload 里显式标记,让 Agent 能区分「数据完整」与「数据不完整」。

凭据不进工具结果。 传输错误在写日志前解包(Go 的 *url.Error 会把完整请求 URL 写进 message,其中含检索条件与 traceId),只保留 dial tcp ... 这类诊断信息。


验证

go build ./... && go vet ./pkg/... && go test ./pkg/... 全绿,trace 包 71 个用例。

覆盖:检索的参数映射与摘要归一化、genai kind 识别、上游错误、结果截断;诊断的线性链、分支场景关键路径落在慢分支、根因归属、服务分解、依赖边、孤儿 span、父子引用成环不挂死、畸形时间戳、错误计数不被列表上限截断;GenAI 归类与 token 口径。


不在本 PR 范围


关联

The assistant could only look up a distributed trace by ID and could not read
one without already knowing the ID. That makes every investigation start with
a question to the user instead of an observation by the agent.

- search_traces queries the provider by service, operation, trace ID, tags,
  time window and minimum duration, and returns bounded per-trace summaries.
  The provider interface gains SearchTraces so another backend can be added
  without touching the tool layer.
- analyze_trace turns a trace into a diagnosis: the latency critical path
  with self time versus wait time per hop, the per-service latency
  breakdown, the slowest spans, the failed spans with their error
  classification and root-cause flag, and the caller to callee dependency
  edges.
- The analyser is a pure function over an already normalized trace, so the
  algorithms are testable without a backend and stay independent of the
  transport.
- Summaries are computed over every raw span. The detail path keeps its
  existing span budget because it backs get_trace_by_id, whose behaviour is
  unchanged.

Every list and attribute value the tools return is capped, truncation is
reported in the payload, and no credential reaches a tool result.
@ambiguous-pointer
ambiguous-pointer marked this pull request as ready for review October 31, 2026 11:57
@robocanic
robocanic requested a max review from Copilot November 2, 2026 01:20

Copilot AI left a comment

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.

🟡 Changes recommended

The hooks tests fail to compile, and unresolved defects allow reasoning-policy bypass, expose endpoint credentials, and cause Jaeger searches with minimum-duration filters to fail.

12 open issues
What changed in this PR

Adds MCP trace discovery and structured diagnosis so the AI assistant can investigate distributed traces without first receiving a trace ID.

Changes:

  • Adds search_traces, Jaeger search support, and a provider-level search contract.
  • Adds analyze_trace with latency-path, service, error-root-cause, dependency, and GenAI usage analysis.
  • Adds tool registration, tests, documentation, sanitized failure logging, and standalone reasoning-policy helpers.

This pull request requires changes. Unresolved findings include non-compiling hook tests, Jaeger rejecting duration-filtered searches, credential exposure through analysis errors, and a reasoning-filter bypass. Further findings concern analysis accuracy, search semantics, truncation and response bounds, GenAI accounting, and documentation consistency.

File Description
pkg/​mcp/​tools/​trace/​tools_test.go Tests trace search and diagnosis handlers.
pkg/​mcp/​tools/​trace/​search.go Defines search arguments, validation, and the tool handler.
pkg/​mcp/​tools/​trace/​search_test.go Tests query mapping, summaries, limits, and errors; currently asserts the invalid duration format.
pkg/​mcp/​tools/​trace/​provider.go Extends the provider interface with trace search.
pkg/​mcp/​tools/​trace/​model.go Adds search, analysis, and GenAI response models.
pkg/​mcp/​tools/​trace/​jaeger.go Implements Jaeger search, raw-span summaries, and sanitized failure logging; has outstanding query, bounds, truncation, and comment findings.
pkg/​mcp/​tools/​trace/​jaeger_logging_test.go Tests failure-log sanitization; includes an imported-package shadowing nit.
pkg/​mcp/​tools/​trace/​genai.go Classifies GenAI spans and aggregates usage; findings cover scientific-notation parsing and potential token double-counting.
pkg/​mcp/​tools/​trace/​genai_test.go Tests classification, token totals, bounded details, and content exclusion.
pkg/​mcp/​tools/​trace/​analyzer.go Implements diagnosis; findings cover error sanitization, trace envelopes, critical paths, cycles, service timing, truncation, error classification, and helper documentation.
pkg/​mcp/​tools/​trace/​analyzer_test.go Tests analysis algorithms, malformed traces, and boundary cases.
pkg/​mcp/​register.go Registers search_traces and analyze_trace.
pkg/​mcp/​register_test.go Checks tool registration and required arguments.
pkg/​mcp/​DEVELOPMENT.md Documents tools and response limits; several stated limits differ from implementation.
docs/​ai-trace-observability-design.md Describes architecture and contracts; findings address broken formatting, stale implementation status, and overstated critical-path guarantees.
ai/​component/​hooks/​reasoning.go Adds unwired reasoning-policy helpers; escaped JSON can bypass filtering.
ai/​component/​hooks/​reasoning_test.go Adds policy and intended integration tests that reference unavailable APIs and fail to compile.

Review effort: Max

Comment thread ai/component/hooks/reasoning.go Resolved
Comment thread ai/component/hooks/reasoning_test.go Resolved
Comment thread pkg/mcp/tools/trace/analyzer.go Resolved
Comment thread pkg/mcp/tools/trace/jaeger.go Resolved
Comment thread pkg/mcp/tools/trace/search_test.go Resolved
Comment thread pkg/mcp/tools/trace/genai.go Resolved
Comment thread pkg/mcp/tools/trace/jaeger.go Resolved
Comment thread ai/component/hooks/reasoning.go Resolved
Comment thread pkg/mcp/DEVELOPMENT.md Resolved
Comment thread pkg/mcp/tools/trace/analyzer.go Resolved
@ambiguous-pointer

ambiguous-pointer commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

评审意见的处理结果

感谢 @copilot-pull-request-reviewer 的评审。12 条意见我逐条复核过,全部成立、无误报,已按 P0 → P1 → P2 处理完毕(修复见 bcaf745)。另外从评审正文的逐文件说明里又找出 3 处没有单列行内评论的问题,一并处理了。

复核时把每条都落到了代码与上游行为上,下面按优先级列出「结论 → 依据 → 处理」。

P0-1 编译失败(#2)+ 死代码(#10)+ 策略绕过(#1)—— 一并处理

这三条指向同一个动作:把 ai/component/hooks/reasoning.go 与 reasoning_test.go 整体移回 #1616。

P0-2 minDuration 缺单位(#4、#5)—— 真实 Jaeger 上必然 400

  • 复核依据:Jaeger v1.38.0 cmd/query/app/query_parser.go 里 minDuration 走 newDurationStringParser(),即 time.ParseDuration(s);裸数字 250000 会得到 time: missing unit in duration → 400。本 PR 发出的正是 strconv.FormatInt(Microseconds(), 10),无单位。
  • 处理:改为发 duration 字符串(query.MinDuration.String() → 250ms)。Jaeger v1 与 v3(durationMin)都用 time.ParseDuration,字符串形式两边都兼容。
  • 断言同步改为 "250ms",并额外加了 time.ParseDuration 往返校验——原来的 httptest stub 不校验参数,加了这条以后同类问题不会再被 stub 掩盖。

P0-3 凭据进入模型上下文(#3)

  • 复核依据:newJaegerProvider 对 endpoint 只做 url.Parse,不带 query 的校验,baseURL 可以带 ?api_key=...;GetTraceByID 复制 URL 时保留了 RawQuery,*url.Error 的 message 内嵌完整 URL,而 sanitizeTransportError() 只用在失败日志上(L622/L640),返回值是直接 %w 进工具结果的。
  • 处理,两层:
    1. 源头:newJaegerProvider 现在校验 scheme 必须是 http/https、host 非空,并拒绝带 query / fragment 的 endpoint,凭据只允许走 bearerToken。拒绝信息里不回显 endpoint(endpoint 本身才可能是密钥所在)。
    2. 出口:工具返回路径也过 sanitizeTransportError。按原设计意图保留了可诊断性——错误里仍带 traceId(模型自己选的,需要能向用户复述)和 dial tcp ...: connection refused 这类诊断信息,去掉的是请求 URL(endpoint 路径 + 全部检索条件 + 可能内嵌的凭据)。对应地更新了原设计文档 §10 与那条 TODO。
    3. 评审未覆盖的补充:原 SearchTraces 里 endpoint.RawQuery = values.Encode() 会覆盖 endpoint 自带的 query——也就是同一份配置,search 路径把凭据丢了(401),by-id 路径把凭据泄漏了。源头拒绝之后这两条路径行为一致了。

P1 正确性

意见 处理
#6 裁剪后总时长用错 analysisEnvelope 优先用 provider 的 trace.DurationMicros(它在全部原始 span 上算),只在没有 provider 值时回退到保留 span 的包络。否则被裁剪的链路会用更短的总时长做分母,把各服务延迟占比整体虚高。补了 TestBuildTraceAnalysisUsesProviderEnvelopeForClippedSpans
#8 token 被科学计数法吞掉 genAIIntAttribute 改走 parseIntegralAttribute,先 Atoi,失败再按 float 解析并要求是整数值。已实测 1000000 → "1e+06" → Atoi 失败 → 0,阈值恰为 ≥1e6(999999 正常)
#9 触达后端 limit 时 truncated 误报 false Provider 侧按调用方条数再多取一条做探测,命中即 truncated=true 并裁回调用方条数。这样「刚好装满」不再被误读为「已看全」,同时避免了「达到上限就报截断」带来的假阳性。补了 TestJaegerProviderSearchTracesReportsTruncationAtTheBackendLimit
#7 slowSpans 排名截断误置 truncated 排名结果不丢分析数据,因此不再置位。与同文件 critical path 的既有规则一致(TestBuildCriticalPathStopsAtBudgetWithoutTruncation:链条正好在预算处结束不算截断)。补了 TestBuildTraceAnalysisDoesNotReportTruncationForTheSlowSpanRanking

P2 一致性

额外发现(评审未提)

  1. CI 从不在 ai 分支上跑。.github/workflows/ci.yml 与 riscv-build.yml 的触发分支只有 develop,PR 目标分支是 ai,所以这两个 workflow 都不会触发——这也是编译失败能进到 PR 的直接原因。

    打开之后暴露出一批从未在这条分支上校验过的历史缺陷(lockfile 镜像失效、ai 模块缺 license header、三个文件不是 gofmt 干净、前端源码不是 prettier 干净、license 配置把 **/tools/** 整条忽略)。这些与本 PR 的改动无关,已经拆到独立分支 fix/ai-branch-ci(目标分支 ai),不在本 PR 里,免得把一个功能 PR 撑成 60 多个文件。

  2. PR 描述里的验证口径漏了 ai 模块。ai/ 是独立 go.mod,go build ./... && go vet ./pkg/... && go test ./pkg/... 只覆盖根模块,所以「全绿」是假象。本 PR 补充验证为两个模块分别 go build / go vet / go test -short。

评审正文里另外提到、但没有单列行内评论的三处

评审正文的「What changed in this PR」逐文件说明里还提到了三处,本 PR 一并处理:

  • jaeger_logging_test.go 的 import 遮蔽 nit:errors := traceLogErrorFields(t, lines) 遮蔽了 errors 包。已改名为 recordedErrors。
  • 设计文档的实现状态过期:§14.2 的 T7 仍写着「工具返回按设计保留上游错误原文」,与本次对传输错误的净化不符。已更新为「传输错误已净化(请求 URL 不进入工具返回),仍未净化的是上游响应体与 span 内容」。
  • 设计文档对关键路径的保证说过头:§5.3.3 原写「恰好满足……链尾的 end 等于 trace 的墙钟终点。链路上的 selfMicros 之和是这条 trace 的不可压缩耗时」。两处都收紧了:span 列表被 maxTraceSpans 裁剪时关键路径只在保留的 span 上计算,链尾可能早于 provider 的墙钟终点;selfMicros 之和是这条关键路径上的不可压缩耗时,并行分支的 self time 不计入,是工作量的下界而非上界。§14.3 的 maxTraceSpans 风险行同步更新(裁剪不再让占比虚高,但关键路径仍只在保留的 span 上计算)。

评审正文还提到 genai.go 的「token 重复计数」与 analyzer.go 的「环 / 服务计时 / 错误分类」,这两处复核后确认实现本身是对的,无需改动:

  • token 重复计数:gen_ai.usage.total_tokens 是非标准属性,设计上只作为单次调用的参考值出现在明细里,聚合的 total 恒等于 input + output,避免出现两种 total 定义;已有用例 TestBuildGenAISummaryKeepsProviderTokenTotalAsCallDetailOnly 覆盖。
  • 环:computeSelfTimes 是迭代实现,hasFailedDescendant 用显式栈 + visited,buildCriticalPath 用 visited 集合,三处都不会在父子引用成环时挂死;已有用例 TestBuildTraceAnalysisSurvivesCyclicReferences 覆盖。
  • 服务计时 / 错误分类:与 §5.3.2、§5.4 的设计一致,error.type 优先级与根因规则(无失败后代)均按文档实现。

验证

两个模块均通过:

go build ./... && go vet ./... && go test ./... -short -gcflags=-l   # 根模块
cd ai && go build ./... && go vet ./... && go test ./... -short -gcflags=-l

本 PR 新增 6 个回归用例(endpoint 校验 2、minDuration wire format、后端 limit 截断、provider 包络、slow span 排名、科学计数法 token),#1616 另加 1 个(JSON 转义绕过),每个都在对应修复前会失败。

未处理

The review found one defect that blocks the build, one that breaks every
duration filtered search against a real Jaeger, one that lets a configured
credential reach the model context, and a set of correctness issues in the
diagnosis.

- The hook tests referenced APIs that do not exist on this branch, so the ai
  module did not compile. The reasoning policy helpers belong to the
  companion observability change, where their wiring lives, so they move
  there. The companion branch also fixes the policy bypass through a JSON
  escape of the type discriminator.
- minDuration is sent as a duration string. Jaeger parses it with
  time.ParseDuration, so the unit-less microsecond count was rejected with
  a 400 and every filtered search failed against a real backend.
- A credential configured on the endpoint query would reach the tool result
  through the transport error. The endpoint is validated, the transport
  error is sanitized for the tool result as well as for the failure log, and
  the request URL no longer enters the model context.
- The diagnosis takes the duration of the complete trace from the provider
  instead of recomputing it from the retained spans, so a clipped span list
  no longer shortens the trace and inflates the latency shares.
- A search that reached the limit of the provider is now marked as
  truncated, so the agent does not conclude that it saw every match.
- The slow span ranking no longer marks the analysis as truncated, because
  a ranking loses no analysis data.
- Token counts are read from the integral scientific notation too, so a
  million token call no longer reports zero tokens.
- The documented response limits, the helper name and the design document
  match the implementation again.
AlexStocks

This comment was marked as low quality.

// account for the same time a second time.
node.selfMicros = 0
node.waitMicros = 0
analysis.Truncated = true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Truncated 混了两种含义

其它地方的 Truncated 都是「数据被预算切掉」(服务 >50、错误 span >20、依赖边 >50、关键路径 >32),这里却用它表示「startTime 解析不了」。对读 payload 的 Agent 来说,这两件事对应完全不同的动作:

  • 前者:「样本不全,别下总体结论」;
  • 后者:「时间轴不可信,self/wait 那一栏别用」。

现在两者都是 truncated: true,Agent 会对一份 span 其实齐全、只是时间字段坏的诊断打折。这和你自己在 buildSlowSpans 里立的规则(排名截断不丢分析数据,所以不算截断)也不一致——既然那条边界值得单独论证,timeValid 这条也该单独表达。

建议加独立字段(timeInvalidSpans 计数或 degraded: true),Truncated 只留给预算裁剪。TestBuildTraceAnalysisSkipsSelfTimeForUnparsableStartTime 现在只断言 self time 为 0,正好可以一并钉住这个 flag。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

当前状态:这一条尚未处理,先在此说明现状与后续打算,不在本轮 push 里假装已修。

背景:这条 review 针对的是 bcaf745。你说的现象现在仍然成立:pkg/mcp/tools/trace/analyzer.go:267 与 :273 在 span 的 startTime 解析不出来时,仍然把 analysis.Truncated 置为 true,所以「时间轴不可信」和「数据被预算裁剪」在输出里还是同一个标志位。Agent 读到一份 span 其实齐全、只是时间字段坏的诊断时,确实会按「样本不全」打折。

需要澄清一点本轮的变化:3133936 新增的 SpansTruncated(pkg/mcp/tools/trace/model.go:39 与 :228)解决的是第三种情况 —— span 列表本身被裁剪,导致父子关系不完整(这条对应 larry-zy 在 analyzer.go 的另一条 P2)。它不覆盖你说的「时间字段不可信」这一种,所以你的建议依然成立。

打算:给「时间不可信」单独一个字段(例如 timeInvalidSpans 计数,或一个 degraded 标志),让 Truncated 只保留预算裁剪这一个语义。同时把 TestBuildTraceAnalysisSkipsSelfTimeForUnparsableStartTime 补成把这个标志一起断言住 —— 你说得对,它现在只断言 self time 为 0,正好可以把 flag 钉进去。

这一条需要单独的改动(会动 TraceAnalysis 的对外结构),我会在后续的 push 里一并给出,并在这里把状态更新为已修。

if errorType == "" && errorMessage != "" {
// Degraded classification: without a typed error the message is the only
// signal left, so it degrades into the error type.
errorType = errorMessage

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 把错误正文降级成 error.type,产出高基数「类型」

后果是 errorType 里会出现 rpc error: code = Unavailable desc = connection error: ... 的前 96 个字符:

  1. 同一种故障每次请求的消息都不同(含端口、trace 片段),Agent 按 type 分组时会把一类错误拆成几十类;
  2. 与紧随其后的 errorMessage 内容重复(同一个串的前 256 字符),payload 占两份预算。

这个降级对人读是合理的(总比 unknown 有信息),对要聚类的模型是反向的。而且 errorStatus / hasFailedDescendant 已经用「规范化状态 + 根因标记」表达结构了。

建议 errorType 落 _OTHER(OpenTelemetry 的 well-known fallback)或 unknown,正文只留在 errorMessage;确实想保留「无类型但有正文」这个信号,就加 errorTypeSource: "attribute"|"event"|"message",比污染 type 干净。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

当前状态:这一条尚未处理,先说明现状,不在本轮 push 里假装已修。

背景:这条 review 针对的是 bcaf745。你指出的高基数问题现在仍然存在:pkg/mcp/tools/trace/analyzer.go:707 仍然是「errorType 为空且 errorMessage 非空时,把正文降级成 type」:

if errorType == "" && errorMessage != "" {
    // Degraded classification: without a typed error the message is the only
    // signal left, so it degrades into the error type.
    errorType = errorMessage
}

于是 errorType 里会出现 rpc error: code = Unavailable desc = connection error: ... 的前 96 个字符,同一类故障按 type 分组会被拆成几十类,而且与 errorMessage 重复占两份预算 —— 这两点都和你的分析一致。

打算:按你建议的方向改 —— errorType 落 unknown(或 OTel 的 _OTHER),正文只保留在 errorMessage;同时加 errorTypeSource(attribute / event / message)来保留「无类型但有正文」这个信号,比污染 type 干净。这样 errorStatus / hasFailedDescendant 继续用「规范化状态 + 根因标记」表达结构,type 字段回到可聚合的取值空间。

这一条会动 ErrorSpan 的对外结构,和上面那条 Truncated 语义分离我打算放在同一个 push 里做,届时会在这里把状态更新为已修。

for _, item := range summaries {
result.Traces = append(result.Traces, item.summary)
}
result.Total = total

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Total 是「返回条数」,不是「命中总数」

total 在任何路径上都等于 len(result.Traces)(截断时 total = limit,未截断时 total = len(traces)),不携带 len() 之外的信息。但一个正在诊断的模型读到 {"total":20,"truncated":true},会复述成「这个服务有 20 条链路」,实际含义是「还有更多,我只给了 20」。model.go:88 上这个字段也没有注释。

Jaeger /api/traces 本身不返回命中总数,所以真实总数拿不到——那就更不该用一个看起来像总数的名字。

建议改名 returned / returnedCount,或补 hasMore: bool 并在结构体注释里写死「本次返回条数,不等于命中总数」。TraceSummary.ReturnedSpanCount 已经是同类命名的先例。

顺带:Limit == 0 时不发 limit,Jaeger 用默认值,而下面的 if limit > 0 && ... 不成立,Truncated 保持 false,等于「后端截断了但报告说完整」。工具层总能归一化到 20,所以当前不可达,但既然这是给「接入新后端」准备的边界,建议 provider 内部也 clamp 一次。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

当前状态:这一条尚未处理,先说明现状,不在本轮 push 里假装已修。

背景:这条 review 针对的是 bcaf745。你指出的语义问题现在仍然存在:pkg/mcp/tools/trace/model.go:98 的字段仍叫 Total int \json:"total"`,没有注释、没有改名、也没有 hasMore;pkg/mcp/tools/trace/jaeger.go:424的total := len(traces)在截断时被覆写成total = limit,所以这个数字在两条路径上都只是「本次返回条数」。模型读到 {"total":20,"truncated":true}` 确实会复述成「这个服务有 20 条链路」。

limit == 0 的 clamp 也还没做:pkg/mcp/tools/trace/jaeger.go:425 仍然是 if limit > 0 && len(summaries) > limit,provider 内部不归一化。你说得对,工具层目前总会归一化到 20,所以这条路径当前不可达 —— 但这是给「接入新后端」预留的边界。

打算:按你的建议改 —— 字段改名为 returned / returnedCount(TraceSummary.ReturnedSpanCount 已经是同类命名的先例),或保留 total 但补 hasMore: bool 并在结构体注释里写死「本次返回条数,不等于命中总数」;同时在 provider 内部把 limit clamp 一次,避免 limit == 0 时把「后端截断了但报告说完整」这件事漏过去。

改名会改变 MCP 工具的输出结构,属于对外契约变更,我会和上一条(errorType / errorTypeSource)一起在同一个 push 里做,并在这里把状态更新为已修。

@larry-zy larry-zy left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewed bcaf745f6e8419ccd147f6fad54e3b54e3023495 against the latest ai base, e6cef77666b6eb709867c92eba7c5a0fb8de0ec6, including the existing review discussions.

Four inline findings concern logic added directly by this PR: serial critical-path selection, error propagation/root-cause classification, search result selection, and the combination of trace-ID lookup with filters. Two findings concern the new analyzer's integration with existing normalization: asynchronous reference semantics and diagnostic evidence lost to display limits. Those normalization rules already exist on the base branch; the comments are attached to the newly added consumers and do not attribute the old rules to this PR.

The existing go test ./pkg/mcp/tools/trace ./pkg/mcp suite passed in a temporary checkout containing this PR merged into the latest base. Six additional counterexamples reproduced the analysis/normalization/sorting behavior described inline. The Jaeger filter interaction was checked against upstream source for the 1.70 version referenced by the repository's deployment manifest, not a live Jaeger integration test.

Comment thread pkg/mcp/tools/trace/analyzer.go Resolved
Comment thread pkg/mcp/tools/trace/analyzer.go Resolved
Comment thread pkg/mcp/tools/trace/analyzer.go Resolved
Comment thread pkg/mcp/tools/trace/analyzer.go Resolved
Comment thread pkg/mcp/tools/trace/jaeger.go Resolved
Comment thread pkg/mcp/tools/trace/jaeger.go Resolved
The review of the trace tools raised six points, all of them about the
diagnosis drawing conclusions the available evidence cannot support.

The critical path now follows the serial contribution of a child when the
children run one after another. The last span of a serial request is
usually the shortest one, so the last finishing child did not identify the
latency determining work. Children that run in parallel keep the old rule,
and a child that runs one after another is marked as part of the critical
path as well.

The reference type survives the normalization now. A follows_from link only
records a causal relationship, so the child is no longer counted as
blocking time of the parent, it no longer extends the critical path and it
no longer propagates a failure into it.

A failure does not propagate through an operation that succeeded. A retry
that recovered from its own failure did not pass that failure on, so the
caller that failed for its own reason stays an independent candidate. The
summary names the candidates when the evidence does not establish which of
them caused the outcome.

The diagnostic attributes survive the attribute limit. The error
classification, the failure status and the generative AI conventions are
added first, because dropping one of them silently changes the diagnosis.

The search keeps the newest traces. The provider is asked for one trace
more than the caller wants, and the ascending display order applied before
the limit discarded the newest one, so an investigation of the most recent
request could miss exactly that request.

A trace identifier is no longer forwarded to the Jaeger search API. As soon
as a trace id is present the backend switches to its tracesByIDs branch and
stops applying the other predicates. The identifier selects the trace and
the remaining conditions are applied locally, so the combined semantics of
the tool arguments hold.

When the span list was clipped no failure is named as the root cause: the
deepest failure that survived the clip is not necessarily the origin of the
error.
@sonarqubecloud

sonarqubecloud Bot commented Dec 2, 2026

Copy link
Copy Markdown

@robocanic robocanic left a comment

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.

总体评价

整体设计清晰:BuildTraceAnalysis 做成纯函数、self time 用区间并集、follows_from 不计入阻塞时间、传输错误脱敏、搜索摘要基于全部原始 span,这些取舍都合理,测试覆盖也比较扎实(含环引用、畸形时间戳、错误计数不被截断等)。以下是我在阅读代码后确认的几个需要处理的问题,未发现 Critical 级别问题。

Critical

未发现。

Important

  1. 根因判定与设计/PR 描述不一致,仅检查直接子节点

    • 位置:pkg/mcp/tools/trace/analyzer.go:781(hasFailedDescendant),调用处 analyzer.go:637
    • 问题:设计文档 §5.4 与 PR 描述均写明"子树中没有任何后代 span 失败才是根因",但实现只遍历 node.children(直接子节点),且遇到未失败的子节点就 continue、不再下探。对于 A(error) → B(OK) → C(error),A 与 C 都会被标记 rootCause=true,摘要里会变成 "root cause candidates",把仅传播错误的 A 当作候选根因。
    • 影响:实际链路中,中间的框架/内部/网关 span 往往没有被打上 error 标记(错误只在最内层与最外层被标红),这种形态很常见,会导致 Agent 得到多个"根因"、结论变得含糊甚至误导;而函数名与注释("descendant")也与行为不符。
    • 建议:要么按文档递归检查整个子树(注意用 visited 防环,沿用 blockingChildren 语义),要么明确把"中间 span 成功即视为已恢复"的语义写进设计文档/工具描述,并补一个 A→B(OK)→C(error) 的用例固定预期行为。
  2. search_traces 向 Jaeger 拉取完整 span 数据,8MB 上限易被触发且报错不可操作

    • 位置:pkg/mcp/tools/trace/jaeger.go:264(limit+1)、jaeger.go:313、readTraceBody(jaeger.go:802,maxTraceResponseBytes = 8MB)
    • 问题:Jaeger /api/traces 搜索接口返回每条 trace 的全部 span 与 tag。默认 limit=20(实际请求 21)、最大 100(实际 101),对于 span 较多的繁忙服务很容易超过 8MB,此时整个检索直接失败,返回 jaeger response exceeds 8388608 bytes,Agent 无从得知应缩小 limit/时间窗/加 minDurationMs。
    • 建议:在搜索路径上对该错误包装为可操作的提示(例如"结果过大,请缩小时间窗、降低 limit 或增加过滤条件"),并/或对搜索使用更保守的默认 limit;至少应增加一个覆盖该路径的测试。
  3. GenAI token 汇总对所有带 gen_ai.* 的 span 求和,可能重复计数

    • 位置:pkg/mcp/tools/trace/genai.go:208-209
    • 问题:summary.InputTokens/OutputTokens 在第一轮循环中对所有带 gen_ai 属性的 span 累加(含 agent、tool 类 span),而 ModelCalls 只按 model 类 span 展示。部分 agent 框架会在 invoke_agent span 上写入聚合后的 usage,此时与其下 chat span 的 usage 重复,汇总值会虚高,且与 modelCalls 明细之和不一致。
    • 建议:仅对 classifyGenAISpan(...) == genAIClassModel 的 span 累加 token,并补测试(agent span 带 usage + 子 chat span 带 usage 的场景)。
  4. normalizeKeyValues 优先保留 gen_ai.* 内容类属性,改变了 get_trace_by_id 的输出(与 PR 声明不符,且有 PII 风险)

    • 位置:pkg/mcp/tools/trace/jaeger.go:719-728(isDiagnosticAttribute)
    • 问题:isDiagnosticAttribute 对任意 gen_ai.* key 返回 true,其中包括 gen_ai.input.messages、gen_ai.output.messages、gen_ai.tool.call.arguments/result 等 Opt-In 的内容属性(genai.go 自己也声明它们"可能含 PII,值永远不读取")。这些属性现在会被优先保留进 span 的 Attributes 并随 get_trace_by_id 原样返回给模型,而此前在属性数量超限时可能被丢弃。这与 PR 描述中"get_trace_by_id 行为完全未变"不符。
    • 建议:优先集合中排除 genAIContentAttributes(只保留 gen_ai.* 的非内容属性),或在 Attributes 输出层对内容属性做过滤/脱敏,并补测试。

其他说明(非阻塞)

  • search.go:66 中 operation 描述为 "root operation name filter",但 Jaeger 语义(以及 matchesTraceSearch 的实现)是"trace 内任意 span 的 operation 匹配",描述会误导 Agent,建议改成与实际一致。
  • newJaegerProvider 现在会拒绝带 query string/fragment 或非 http(s) 的 endpoint(jaeger.go:127-140),这会让已有、endpoint 带 query 的配置在升级后无法使用;建议在发布说明/文档里明确这是不兼容变更。

结论

是否可合并:修复后可合并(With fixes)

核心算法与测试质量较好;建议先处理第 1 点(根因语义与文档不一致,直接影响诊断结论)与第 4 点(影响已发布工具的输出/隐私承诺),第 2、3 点也建议在合并前修复或明确说明取舍。

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.

5 participants