AlexStocks commented on code in PR #1618:
URL: https://github.com/apache/dubbo-admin/pull/1618#discussion_r4501922402


##########
pkg/mcp/tools/trace/analyzer.go:
##########
@@ -0,0 +1,831 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package trace
+
+import (
+       "context"
+       "fmt"
+       "math"
+       "sort"
+       "strconv"
+       "strings"
+       "time"
+       "unicode/utf8"
+
+       consolectx "github.com/apache/dubbo-admin/pkg/console/context"
+       "github.com/apache/dubbo-admin/pkg/mcp/common"
+)
+
+const (
+       // Bounded output limits. They keep the tool payload small enough to 
stay inside
+       // the model context window while still describing the most relevant 
spans.
+       maxCriticalPath     = 32
+       maxServiceBreakdown = 50
+       maxSlowSpans        = 10
+       maxErrorSpans       = 20
+       maxDependencyEdges  = 50
+       maxGenAICalls       = 20
+
+       maxAnalysisSummaryChars = 300
+       maxErrorTypeChars       = 96
+       maxErrorMessageChars    = 256
+)
+
+const (
+       errorTypeAttribute        = "error.type"
+       errorMessageAttribute     = "error.message"
+       exceptionTypeAttribute    = "exception.type"
+       exceptionMessageAttribute = "exception.message"
+       spanEventNameAttribute    = "event"
+       standardExceptionEvent    = "exception"
+       genAIExceptionEvent       = "gen_ai.client.operation.exception"
+)
+
+// analysisSpan is the analyzer's internal view of a span with a resolved 
timeline.
+type analysisSpan struct {
+       span        *Span
+       position    int
+       startMicros int64
+       endMicros   int64
+       timeValid   bool
+       selfMicros  int64
+       waitMicros  int64
+       parent      *analysisSpan
+       children    []*analysisSpan
+}
+
+// timelineInterval is a half-open interval on the absolute microsecond 
timeline.
+type timelineInterval struct {
+       start int64
+       end   int64
+}
+
+// AnalyzeTrace diagnoses a single distributed trace and returns a structured 
report.
+func AnalyzeTrace(ctx consolectx.Context, args map[string]any) 
(*common.ToolResult, error) {
+       helper := common.NewArgsHelper(args)
+       traceID := helper.GetString("traceId", "")
+       if !traceIDPattern.MatchString(traceID) {
+               return common.ErrorResult(fmt.Errorf("traceId must be a 16 or 
32 character hexadecimal value")), nil
+       }
+       providerConfig, err := providerConfigFromContext(ctx, 
helper.GetString("provider", ""))
+       if err != nil {
+               return common.ErrorResult(err), nil
+       }
+       provider, err := newProvider(providerConfig)
+       if err != nil {
+               return common.ErrorResult(err), nil
+       }
+       trace, err := provider.GetTraceByID(traceRequestContext(ctx), traceID)
+       if err != nil {
+               return common.ErrorResult(err), nil
+       }
+       return common.JsonResult(BuildTraceAnalysis(trace))
+}
+
+// AnalyzeProperties returns the MCP input schema properties for trace 
diagnosis.
+func AnalyzeProperties() map[string]common.PropertyDef {
+       return map[string]common.PropertyDef{
+               "traceId":  {Type: "string", Description: "Jaeger 64-bit or 
128-bit hexadecimal TraceID"},
+               "provider": {Type: "string", Description: "Optional trace 
provider name; defaults to defaultProvider"},
+       }
+}
+
+// BuildTraceAnalysis turns a normalized trace into a structured diagnosis.
+// It is a pure function so the diagnosis rules can be verified without a 
backend.
+func BuildTraceAnalysis(trace *Trace) *TraceAnalysis {
+       analysis := &TraceAnalysis{}
+       if trace == nil {
+               analysis.Summary = "no trace data available"
+               return analysis
+       }
+       analysis.TraceID = trace.TraceID
+       analysis.Truncated = trace.Truncated
+
+       nodes := buildAnalysisTree(trace.Spans)
+       computeSelfTimes(nodes, analysis)
+       criticalPath, criticalPathSet := buildCriticalPath(nodes, analysis)
+       analysis.CriticalPath = criticalPath
+
+       wallClock, traceStart := analysisEnvelope(nodes, trace)
+       analysis.DurationMicros = wallClock
+       analysis.StartTime = traceStart
+       analysis.SpanCount = maxInt(trace.SpanCount, len(trace.Spans))
+
+       breakdown := buildServiceBreakdown(nodes, wallClock, analysis)
+       analysis.ServiceBreakdown = breakdown
+       analysis.ServiceCount = maxInt(trace.ServiceCount, len(breakdown))
+
+       slowSpans := buildSlowSpans(nodes, wallClock, criticalPathSet)
+       analysis.SlowSpans = make([]SlowSpan, 0, len(slowSpans))
+       for _, entry := range slowSpans {
+               analysis.SlowSpans = append(analysis.SlowSpans, entry.slow)
+       }
+
+       errorSpans, errorCount := buildErrorSpans(nodes, analysis)
+       analysis.ErrorSpans = errorSpans
+       // The provider already counted errors over the complete trace; that 
count must not
+       // be hidden by the bounded error span list.
+       analysis.ErrorSpanCount = maxInt(trace.ErrorSpanCount, errorCount)
+
+       analysis.Dependencies = buildDependencyEdges(nodes, analysis)
+
+       if genai := BuildGenAISummary(trace.Spans); genai.Present {
+               analysis.GenAI = genai
+       }
+
+       analysis.Summary = buildAnalysisSummary(analysis, slowSpans)
+       return analysis
+}
+
+// buildAnalysisTree links the spans into a parent/child forest. A span whose 
parent
+// is missing from the trace degrades into an orphan root: it still 
contributes to the
+// aggregate statistics but it cannot extend a parent chain.
+func buildAnalysisTree(spans []Span) []*analysisSpan {
+       nodes := make([]*analysisSpan, 0, len(spans))
+       index := make(map[string]*analysisSpan, len(spans))
+       for i := range spans {
+               span := &spans[i]
+               node := &analysisSpan{span: span, position: i}
+               if parsed, err := time.Parse(time.RFC3339Nano, 
strings.TrimSpace(span.StartTime)); err == nil {
+                       node.timeValid = true
+                       node.startMicros = parsed.UnixMicro()
+                       node.endMicros = node.startMicros + span.DurationMicros
+               } else {
+                       node.endMicros = span.DurationMicros
+               }
+               nodes = append(nodes, node)
+               if span.SpanID != "" {
+                       index[span.SpanID] = node
+               }
+       }
+       for _, node := range nodes {
+               parentID := node.span.ParentSpanID
+               if parentID == "" {
+                       continue
+               }
+               parent, ok := index[parentID]
+               if !ok || parent == node {
+                       continue
+               }
+               node.parent = parent
+               parent.children = append(parent.children, node)
+       }
+       return nodes
+}
+
+// computeSelfTimes derives the exclusive time of every span. The covered time 
is the
+// union of the clipped child intervals, so concurrent children are not 
counted twice.
+func computeSelfTimes(nodes []*analysisSpan, analysis *TraceAnalysis) {
+       for _, node := range nodes {
+               if !node.timeValid {
+                       // Without a trustworthy start time the span degrades 
to a leaf. It
+                       // cannot be placed on the timeline, so it must not 
claim any time
+                       // of its own: counting its full duration here would 
let the parent
+                       // account for the same time a second time.
+                       node.selfMicros = 0
+                       node.waitMicros = 0
+                       analysis.Truncated = true

Review Comment:
   🟡 **`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。



##########
pkg/mcp/tools/trace/analyzer.go:
##########
@@ -0,0 +1,831 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package trace
+
+import (
+       "context"
+       "fmt"
+       "math"
+       "sort"
+       "strconv"
+       "strings"
+       "time"
+       "unicode/utf8"
+
+       consolectx "github.com/apache/dubbo-admin/pkg/console/context"
+       "github.com/apache/dubbo-admin/pkg/mcp/common"
+)
+
+const (
+       // Bounded output limits. They keep the tool payload small enough to 
stay inside
+       // the model context window while still describing the most relevant 
spans.
+       maxCriticalPath     = 32
+       maxServiceBreakdown = 50
+       maxSlowSpans        = 10
+       maxErrorSpans       = 20
+       maxDependencyEdges  = 50
+       maxGenAICalls       = 20
+
+       maxAnalysisSummaryChars = 300
+       maxErrorTypeChars       = 96
+       maxErrorMessageChars    = 256
+)
+
+const (
+       errorTypeAttribute        = "error.type"
+       errorMessageAttribute     = "error.message"
+       exceptionTypeAttribute    = "exception.type"
+       exceptionMessageAttribute = "exception.message"
+       spanEventNameAttribute    = "event"
+       standardExceptionEvent    = "exception"
+       genAIExceptionEvent       = "gen_ai.client.operation.exception"
+)
+
+// analysisSpan is the analyzer's internal view of a span with a resolved 
timeline.
+type analysisSpan struct {
+       span        *Span
+       position    int
+       startMicros int64
+       endMicros   int64
+       timeValid   bool
+       selfMicros  int64
+       waitMicros  int64
+       parent      *analysisSpan
+       children    []*analysisSpan
+}
+
+// timelineInterval is a half-open interval on the absolute microsecond 
timeline.
+type timelineInterval struct {
+       start int64
+       end   int64
+}
+
+// AnalyzeTrace diagnoses a single distributed trace and returns a structured 
report.
+func AnalyzeTrace(ctx consolectx.Context, args map[string]any) 
(*common.ToolResult, error) {
+       helper := common.NewArgsHelper(args)
+       traceID := helper.GetString("traceId", "")
+       if !traceIDPattern.MatchString(traceID) {
+               return common.ErrorResult(fmt.Errorf("traceId must be a 16 or 
32 character hexadecimal value")), nil
+       }
+       providerConfig, err := providerConfigFromContext(ctx, 
helper.GetString("provider", ""))
+       if err != nil {
+               return common.ErrorResult(err), nil
+       }
+       provider, err := newProvider(providerConfig)
+       if err != nil {
+               return common.ErrorResult(err), nil
+       }
+       trace, err := provider.GetTraceByID(traceRequestContext(ctx), traceID)
+       if err != nil {
+               return common.ErrorResult(err), nil
+       }
+       return common.JsonResult(BuildTraceAnalysis(trace))
+}
+
+// AnalyzeProperties returns the MCP input schema properties for trace 
diagnosis.
+func AnalyzeProperties() map[string]common.PropertyDef {
+       return map[string]common.PropertyDef{
+               "traceId":  {Type: "string", Description: "Jaeger 64-bit or 
128-bit hexadecimal TraceID"},
+               "provider": {Type: "string", Description: "Optional trace 
provider name; defaults to defaultProvider"},
+       }
+}
+
+// BuildTraceAnalysis turns a normalized trace into a structured diagnosis.
+// It is a pure function so the diagnosis rules can be verified without a 
backend.
+func BuildTraceAnalysis(trace *Trace) *TraceAnalysis {
+       analysis := &TraceAnalysis{}
+       if trace == nil {
+               analysis.Summary = "no trace data available"
+               return analysis
+       }
+       analysis.TraceID = trace.TraceID
+       analysis.Truncated = trace.Truncated
+
+       nodes := buildAnalysisTree(trace.Spans)
+       computeSelfTimes(nodes, analysis)
+       criticalPath, criticalPathSet := buildCriticalPath(nodes, analysis)
+       analysis.CriticalPath = criticalPath
+
+       wallClock, traceStart := analysisEnvelope(nodes, trace)
+       analysis.DurationMicros = wallClock
+       analysis.StartTime = traceStart
+       analysis.SpanCount = maxInt(trace.SpanCount, len(trace.Spans))
+
+       breakdown := buildServiceBreakdown(nodes, wallClock, analysis)
+       analysis.ServiceBreakdown = breakdown
+       analysis.ServiceCount = maxInt(trace.ServiceCount, len(breakdown))
+
+       slowSpans := buildSlowSpans(nodes, wallClock, criticalPathSet)
+       analysis.SlowSpans = make([]SlowSpan, 0, len(slowSpans))
+       for _, entry := range slowSpans {
+               analysis.SlowSpans = append(analysis.SlowSpans, entry.slow)
+       }
+
+       errorSpans, errorCount := buildErrorSpans(nodes, analysis)
+       analysis.ErrorSpans = errorSpans
+       // The provider already counted errors over the complete trace; that 
count must not
+       // be hidden by the bounded error span list.
+       analysis.ErrorSpanCount = maxInt(trace.ErrorSpanCount, errorCount)
+
+       analysis.Dependencies = buildDependencyEdges(nodes, analysis)
+
+       if genai := BuildGenAISummary(trace.Spans); genai.Present {
+               analysis.GenAI = genai
+       }
+
+       analysis.Summary = buildAnalysisSummary(analysis, slowSpans)
+       return analysis
+}
+
+// buildAnalysisTree links the spans into a parent/child forest. A span whose 
parent
+// is missing from the trace degrades into an orphan root: it still 
contributes to the
+// aggregate statistics but it cannot extend a parent chain.
+func buildAnalysisTree(spans []Span) []*analysisSpan {
+       nodes := make([]*analysisSpan, 0, len(spans))
+       index := make(map[string]*analysisSpan, len(spans))
+       for i := range spans {
+               span := &spans[i]
+               node := &analysisSpan{span: span, position: i}
+               if parsed, err := time.Parse(time.RFC3339Nano, 
strings.TrimSpace(span.StartTime)); err == nil {
+                       node.timeValid = true
+                       node.startMicros = parsed.UnixMicro()
+                       node.endMicros = node.startMicros + span.DurationMicros
+               } else {
+                       node.endMicros = span.DurationMicros
+               }
+               nodes = append(nodes, node)
+               if span.SpanID != "" {
+                       index[span.SpanID] = node
+               }
+       }
+       for _, node := range nodes {
+               parentID := node.span.ParentSpanID
+               if parentID == "" {
+                       continue
+               }
+               parent, ok := index[parentID]
+               if !ok || parent == node {
+                       continue
+               }
+               node.parent = parent
+               parent.children = append(parent.children, node)
+       }
+       return nodes
+}
+
+// computeSelfTimes derives the exclusive time of every span. The covered time 
is the
+// union of the clipped child intervals, so concurrent children are not 
counted twice.
+func computeSelfTimes(nodes []*analysisSpan, analysis *TraceAnalysis) {
+       for _, node := range nodes {
+               if !node.timeValid {
+                       // Without a trustworthy start time the span degrades 
to a leaf. It
+                       // cannot be placed on the timeline, so it must not 
claim any time
+                       // of its own: counting its full duration here would 
let the parent
+                       // account for the same time a second time.
+                       node.selfMicros = 0
+                       node.waitMicros = 0
+                       analysis.Truncated = true
+                       continue
+               }
+               intervals := make([]timelineInterval, 0, len(node.children))
+               for _, child := range node.children {
+                       if !child.timeValid {
+                               analysis.Truncated = true
+                               continue
+                       }
+                       start := maxInt64(child.startMicros, node.startMicros)
+                       end := minInt64(child.endMicros, node.endMicros)
+                       if end <= start {
+                               continue
+                       }
+                       intervals = append(intervals, timelineInterval{start: 
start, end: end})
+               }
+               covered := unionLength(intervals)
+               node.waitMicros = covered
+               node.selfMicros = node.span.DurationMicros - covered
+               if node.selfMicros < 0 {
+                       node.selfMicros = 0
+               }
+       }
+}
+
+// unionLength returns the length of the union of the given intervals.
+func unionLength(intervals []timelineInterval) int64 {
+       if len(intervals) == 0 {
+               return 0
+       }
+       sort.Slice(intervals, func(i, j int) bool {
+               if intervals[i].start != intervals[j].start {
+                       return intervals[i].start < intervals[j].start
+               }
+               return intervals[i].end < intervals[j].end
+       })
+       total := int64(0)
+       current := intervals[0]
+       for _, next := range intervals[1:] {
+               if next.start > current.end {
+                       total += current.end - current.start
+                       current = next
+                       continue
+               }
+               if next.end > current.end {
+                       current.end = next.end
+               }
+       }
+       return total + current.end - current.start
+}
+
+// buildCriticalPath walks the latency determining root-to-leaf chain.
+// The second return value holds the analyzer internal positions of the spans 
on the
+// path. The position is used instead of the business span id because a span 
id can
+// be empty or duplicated, which would make two different spans overwrite each 
other.
+func buildCriticalPath(nodes []*analysisSpan, analysis *TraceAnalysis) 
([]CriticalPathEntry, map[int]struct{}) {
+       roots := make([]*analysisSpan, 0, len(nodes))
+       for _, node := range nodes {
+               if node.parent == nil {
+                       roots = append(roots, node)
+               }
+       }
+       entries := make([]CriticalPathEntry, 0, maxCriticalPath)
+       onPath := map[int]struct{}{}
+       visited := map[int]struct{}{}
+       current := selectCriticalRoot(roots)
+       for current != nil {
+               if len(entries) >= maxCriticalPath {
+                       // The budget is exhausted while the chain still 
continues, so the
+                       // remaining hops are dropped and the analysis is 
incomplete.
+                       analysis.Truncated = true
+                       break
+               }
+               if _, seen := visited[current.position]; seen {
+                       break
+               }
+               visited[current.position] = struct{}{}
+               onPath[current.position] = struct{}{}
+               entries = append(entries, CriticalPathEntry{
+                       SpanID:         current.span.SpanID,
+                       ServiceName:    current.span.ServiceName,
+                       OperationName:  current.span.OperationName,
+                       StartTime:      current.span.StartTime,
+                       DurationMicros: current.span.DurationMicros,
+                       SelfMicros:     current.selfMicros,
+                       WaitMicros:     current.waitMicros,
+               })
+               current = selectCriticalChild(current)
+       }
+       return entries, onPath
+}
+
+// selectCriticalRoot picks the root that finishes last, because that root 
determines
+// the end of the request.
+func selectCriticalRoot(roots []*analysisSpan) *analysisSpan {
+       var best *analysisSpan
+       for _, root := range roots {
+               if !root.timeValid {
+                       continue
+               }
+               if best == nil || betterCriticalRoot(root, best) {
+                       best = root
+               }
+       }
+       if best != nil {
+               return best
+       }
+       for _, root := range roots {
+               if best == nil || betterCriticalRoot(root, best) {
+                       best = root
+               }
+       }
+       return best
+}
+
+func betterCriticalRoot(candidate, current *analysisSpan) bool {
+       if candidate.endMicros != current.endMicros {
+               return candidate.endMicros > current.endMicros
+       }
+       if candidate.span.DurationMicros != current.span.DurationMicros {
+               return candidate.span.DurationMicros > 
current.span.DurationMicros
+       }
+       // The start time is derived from the end time and the duration, so it 
is
+       // already equal here and cannot be used as a tie breaker.
+       return candidate.span.SpanID < current.span.SpanID
+}
+
+// selectCriticalChild picks the child that finishes last, because it is the 
activity
+// that determined when the parent completed.
+func selectCriticalChild(node *analysisSpan) *analysisSpan {
+       var best *analysisSpan
+       for _, child := range node.children {
+               if !child.timeValid {
+                       // A span without a trustworthy timestamp degrades to a 
leaf and is not
+                       // allowed to extend the chain.
+                       continue
+               }
+               if best == nil || betterCriticalChild(child, best) {
+                       best = child
+               }
+       }
+       return best
+}
+
+func betterCriticalChild(candidate, current *analysisSpan) bool {
+       if candidate.endMicros != current.endMicros {
+               return candidate.endMicros > current.endMicros
+       }
+       if candidate.span.DurationMicros != current.span.DurationMicros {
+               return candidate.span.DurationMicros > 
current.span.DurationMicros
+       }
+       return candidate.span.SpanID < current.span.SpanID
+}
+
+// analysisEnvelope returns the wall clock duration and the start timestamp of 
the trace.
+func analysisEnvelope(nodes []*analysisSpan, trace *Trace) (int64, string) {
+       var minStart, maxEnd int64
+       hasStart := false
+       startText := trace.StartTime
+       for _, node := range nodes {
+               if !node.timeValid {
+                       continue
+               }
+               if !hasStart || node.startMicros < minStart {
+                       minStart = node.startMicros
+                       startText = node.span.StartTime
+                       hasStart = true
+               }
+               if node.endMicros > maxEnd {
+                       maxEnd = node.endMicros
+               }
+       }
+       if !hasStart {
+               return trace.DurationMicros, trace.StartTime
+       }
+       // The provider envelope covers every raw span, the node envelope only 
the
+       // retained ones. A clipped span list would make the node envelope 
shorter
+       // than the trace and inflate every latency percentage that uses it as 
the
+       // denominator, so the provider value is preferred whenever it is 
available.
+       if trace.DurationMicros > 0 {
+               return trace.DurationMicros, startText
+       }
+       return maxEnd - minStart, startText
+}
+
+// buildServiceBreakdown aggregates the spans per service.
+func buildServiceBreakdown(nodes []*analysisSpan, wallClock int64, analysis 
*TraceAnalysis) []ServiceLatency {
+       aggregates := map[string]*ServiceLatency{}
+       for _, node := range nodes {
+               span := node.span
+               entry, ok := aggregates[span.ServiceName]
+               if !ok {
+                       entry = &ServiceLatency{ServiceName: span.ServiceName}
+                       aggregates[span.ServiceName] = entry
+               }
+               entry.SpanCount++
+               if spanFailed(span) {
+                       entry.ErrorSpanCount++
+               }
+               entry.TotalMicros += span.DurationMicros
+               if span.DurationMicros > entry.MaxMicros {
+                       entry.MaxMicros = span.DurationMicros
+               }
+       }
+       result := make([]ServiceLatency, 0, len(aggregates))
+       for _, entry := range aggregates {
+               if entry.SpanCount > 0 {
+                       entry.AvgMicros = entry.TotalMicros / 
int64(entry.SpanCount)
+               }
+               // The share is the service workload relative to the wall clock 
of the trace.
+               // Concurrent spans can push it above 100 percent on purpose.
+               entry.SharePercent = percentOf(entry.TotalMicros, wallClock)
+               result = append(result, *entry)
+       }
+       sort.SliceStable(result, func(i, j int) bool {
+               if result[i].TotalMicros != result[j].TotalMicros {
+                       return result[i].TotalMicros > result[j].TotalMicros
+               }
+               return result[i].ServiceName < result[j].ServiceName
+       })
+       if len(result) > maxServiceBreakdown {
+               result = result[:maxServiceBreakdown]
+               analysis.Truncated = true
+       }
+       return result
+}
+
+// slowSpanEntry pairs a slow span with the analyzer internal identity of the 
span
+// it was derived from. The position is used instead of the business span id so
+// that spans without an id, or with duplicated ids, cannot overwrite each 
other.
+type slowSpanEntry struct {
+       slow       SlowSpan
+       position   int
+       selfMicros int64
+}
+
+// buildSlowSpans ranks the spans by the time they consumed on their own.
+// The exclusive time is returned alongside the report so the summary can 
quote it
+// even for spans that are not part of the critical path.
+func buildSlowSpans(nodes []*analysisSpan, wallClock int64, criticalPath 
map[int]struct{}) []slowSpanEntry {
+       candidates := make([]slowSpanEntry, 0, len(nodes))
+       for _, node := range nodes {
+               span := node.span
+               _, onPath := criticalPath[node.position]
+               candidates = append(candidates, slowSpanEntry{
+                       slow: SlowSpan{
+                               SpanID:         span.SpanID,
+                               ServiceName:    span.ServiceName,
+                               OperationName:  span.OperationName,
+                               DurationMicros: span.DurationMicros,
+                               SharePercent:   percentOf(node.selfMicros, 
wallClock),
+                               OnCriticalPath: onPath,
+                       },
+                       position:   node.position,
+                       selfMicros: node.selfMicros,
+               })
+       }
+       sort.SliceStable(candidates, func(i, j int) bool {
+               if candidates[i].selfMicros != candidates[j].selfMicros {
+                       return candidates[i].selfMicros > 
candidates[j].selfMicros
+               }
+               return candidates[i].position < candidates[j].position
+       })
+       // The list is a ranking, so cutting it to the top entries does not 
lose any
+       // analysis data. The truncated flag stays untouched: it would tell the 
agent
+       // that the diagnosis is based on incomplete data, and a ranking is 
complete
+       // even when only its best entries are reported.
+       if len(candidates) > maxSlowSpans {
+               candidates = candidates[:maxSlowSpans]
+       }
+       return candidates
+}
+
+// errorSpanEntry pairs an error span with the analyzer node it was derived 
from.
+// The node is kept so the ordering can use the start time of the span without
+// indexing the table by the business span id.
+type errorSpanEntry struct {
+       span ErrorSpan
+       node *analysisSpan
+}
+
+// buildErrorSpans collects the failed spans and marks the root causes.
+func buildErrorSpans(nodes []*analysisSpan, analysis *TraceAnalysis) 
([]ErrorSpan, int) {
+       failed := make([]*analysisSpan, 0, len(nodes))
+       for _, node := range nodes {
+               if spanFailed(node.span) {
+                       failed = append(failed, node)
+               }
+       }
+       entries := make([]errorSpanEntry, 0, len(failed))
+       for _, node := range failed {
+               span := node.span
+               errorType, errorMessage := errorDetails(span)
+               entries = append(entries, errorSpanEntry{
+                       span: ErrorSpan{
+                               SpanID:        span.SpanID,
+                               ServiceName:   span.ServiceName,
+                               OperationName: span.OperationName,
+                               ErrorType:     errorType,
+                               ErrorMessage:  errorMessage,
+                               Status:        errorStatus(span),
+                               RootCause:     !hasFailedDescendant(node),
+                       },
+                       node: node,
+               })
+       }
+       // Root causes come first so the agent sees the deepest failure before 
the
+       // ancestors that only propagate it.
+       sort.SliceStable(entries, func(i, j int) bool {
+               left, right := entries[i], entries[j]
+               if left.span.RootCause != right.span.RootCause {
+                       return left.span.RootCause
+               }
+               if left.node.startMicros != right.node.startMicros {
+                       return left.node.startMicros < right.node.startMicros
+               }
+               return left.node.position < right.node.position
+       })
+       count := len(entries)
+       if len(entries) > maxErrorSpans {
+               entries = entries[:maxErrorSpans]
+               analysis.Truncated = true
+       }
+       result := make([]ErrorSpan, 0, len(entries))
+       for _, entry := range entries {
+               result = append(result, entry.span)
+       }
+       return result, count
+}
+
+// errorDetails resolves the error classification and the human readable 
description.
+//
+// The sources are ordered "generative AI first, standard second, non standard
+// last":
+//   - The span attribute error.type stays the leading source because the 
OpenTelemetry
+//     error registry defines it as the stable error type of a span.
+//   - The generative AI exception event comes before the standard exception 
event
+//     because this project serves the generative AI execution of the agent 
loop, so
+//     the typed error of the model call is the more relevant classification.
+//   - error.message is only the last resort because it is not an OpenTelemetry
+//     standard attribute: the registry only defines error.type, and the stable
+//     attribute for the exception text is exception.message. error.message is 
a
+//     habit of the Java ecosystem and of some collectors, so it is used only 
when
+//     no typed error is available, and it then degrades into the error type.
+func errorDetails(span *Span) (string, string) {
+       errorType := ""
+       if value, ok := lookupAttributeOK(span.Attributes, errorTypeAttribute); 
ok {
+               errorType = strings.TrimSpace(value)
+       }
+       exceptionType, exceptionMessage := exceptionDetails(span)
+       if errorType == "" {
+               errorType = exceptionType
+       }
+       errorMessage := exceptionMessage
+       if errorMessage == "" {
+               if value, ok := lookupAttributeOK(span.Attributes, 
errorMessageAttribute); ok {
+                       errorMessage = strings.TrimSpace(value)
+               }
+       }
+       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

Review Comment:
   🟡 **把错误正文降级成 `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 干净。



##########
pkg/mcp/tools/trace/jaeger.go:
##########
@@ -184,6 +204,237 @@ func (p *jaegerProvider) GetTraceByID(ctx 
context.Context, traceID string) (*Tra
        return result, nil
 }
 
+// SearchTraces discovers candidate traces through the Jaeger v1 query API.
+// The summaries are computed from the raw spans so that no information is 
lost to
+// the normalization applied by the single trace lookup.
+func (p *jaegerProvider) SearchTraces(ctx context.Context, query 
TraceSearchQuery) (*TraceSearchResult, error) {
+       if strings.TrimSpace(query.Service) == "" {
+               return nil, fmt.Errorf("service is required for trace search")
+       }
+       values := url.Values{}
+       values.Set("service", query.Service)
+       if query.Operation != "" {
+               values.Set("operation", query.Operation)
+       }
+       if query.TraceID != "" {
+               values.Set("traceID", query.TraceID)
+       }
+       if len(query.Tags) > 0 {
+               encoded, err := json.Marshal(query.Tags)
+               if err != nil {
+                       return nil, fmt.Errorf("failed to encode trace search 
tags: %w", err)
+               }
+               values.Set("tags", string(encoded))
+       }
+       if !query.StartTime.IsZero() {
+               values.Set("start", 
strconv.FormatInt(query.StartTime.UnixMicro(), 10))
+       }
+       if !query.EndTime.IsZero() {
+               values.Set("end", strconv.FormatInt(query.EndTime.UnixMicro(), 
10))
+       }
+       if query.MinDuration > 0 {
+               // Jaeger parses minDuration with time.ParseDuration, so the 
value has to
+               // carry a unit. A bare microsecond count is rejected with a 400
+               // ("missing unit in duration"), so the duration is sent in its 
string
+               // form ("250ms") instead.
+               values.Set("minDuration", query.MinDuration.String())
+       }
+       if query.Limit > 0 {
+               // One trace more than the caller asked for is requested. A 
full result
+               // then proves that more traces match than were returned, which 
is what
+               // the truncated flag has to tell the agent.
+               values.Set("limit", strconv.Itoa(query.Limit+1))
+       }
+
+       endpoint := *p.baseURL
+       endpoint.Path = strings.TrimRight(endpoint.Path, "/") + "/api/traces"
+       endpoint.RawQuery = values.Encode()
+       startedAt := time.Now()
+       req, err := http.NewRequestWithContext(ctx, http.MethodGet, 
endpoint.String(), nil)
+       if err != nil {
+               return nil, fmt.Errorf("failed to create jaeger search request: 
%w", err)
+       }
+       req.Header.Set("Accept", "application/json")
+       if p.config.BearerToken != "" {
+               req.Header.Set("Authorization", "Bearer "+p.config.BearerToken)
+       }
+       if p.config.Tenant != "" {
+               req.Header.Set(tenantHeader, p.config.Tenant)
+       }
+
+       resp, err := p.client.Do(req)
+       if err != nil {
+               p.logSearchFailure(query, startedAt, 0, "transport", err)
+               // The transport error embeds the request URL, which repeats 
the configured
+               // endpoint and carries the retrieval conditions. It is 
sanitized before it
+               // reaches the tool result and the model context. The service 
anchor is
+               // kept, because the model chose it and has to be able to 
report which
+               // lookup failed.
+               return nil, fmt.Errorf("jaeger trace search failed for service 
%s: %w", query.Service, sanitizedTransportError(err))
+       }
+       defer resp.Body.Close()
+       if resp.StatusCode < http.StatusOK || resp.StatusCode >= 
http.StatusMultipleChoices {
+               body, _ := io.ReadAll(io.LimitReader(resp.Body, 
maxTraceErrorBodyBytes))
+               p.logSearchFailure(query, startedAt, resp.StatusCode, 
"upstream_status", nil)
+               return nil, fmt.Errorf("jaeger trace search failed with status 
%d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
+       }
+       body, err := readTraceBody(resp.Body)
+       if err != nil {
+               p.logSearchFailure(query, startedAt, resp.StatusCode, 
"response_limit", err)
+               return nil, err
+       }
+       var upstream jaegerResponse
+       if err := json.Unmarshal(body, &upstream); err != nil {
+               p.logSearchFailure(query, startedAt, resp.StatusCode, "decode", 
err)
+               return nil, fmt.Errorf("failed to decode jaeger search 
response: %w", err)
+       }
+       if len(upstream.Errors) > 0 {
+               p.logSearchFailure(query, startedAt, resp.StatusCode, 
"upstream_error", nil)
+               return nil, fmt.Errorf("jaeger trace search failed: %s", 
upstream.Errors[0].Message)
+       }
+       result := summarizeJaegerTraces(upstream.Data, query.Limit)
+       logger.Sugar().Infow("trace search completed", "provider", 
p.config.Name, "engine", p.config.Type, "service", query.Service, "elapsed_ms", 
time.Since(startedAt).Milliseconds(), "traces", len(result.Traces), "total", 
result.Total, "truncated", result.Truncated)
+       return result, nil
+}
+
+// jaegerTraceSummary keeps the numeric start time next to the summary so the 
result
+// can be ordered on the absolute timeline instead of on the formatted 
timestamp.
+type jaegerTraceSummary struct {
+       summary     TraceSummary
+       startMicros int64
+}
+
+// summarizeJaegerTraces converts the raw traces into bounded per-trace 
summaries.
+func summarizeJaegerTraces(traces []jaegerTrace, limit int) *TraceSearchResult 
{
+       result := &TraceSearchResult{Traces: []TraceSummary{}, SourceEngine: 
"jaeger"}
+       summaries := make([]jaegerTraceSummary, 0, len(traces))
+       for _, trace := range traces {
+               summary, startMicros := summarizeJaegerTrace(trace)
+               summaries = append(summaries, jaegerTraceSummary{summary: 
summary, startMicros: startMicros})
+       }
+       sort.SliceStable(summaries, func(i, j int) bool {
+               if summaries[i].startMicros != summaries[j].startMicros {
+                       return summaries[i].startMicros < 
summaries[j].startMicros
+               }
+               return summaries[i].summary.TraceID < 
summaries[j].summary.TraceID
+       })
+       // The provider was asked for one trace more than the caller wants, so a
+       // result that reached that limit proves that more traces match than 
were
+       // returned. Without the extra trace a full result would look complete.
+       total := len(traces)
+       if limit > 0 && len(summaries) > limit {
+               result.Truncated = true
+               summaries = summaries[:limit]
+               total = limit
+       }
+       if len(summaries) > maxSearchTraceSummaries {
+               summaries = summaries[:maxSearchTraceSummaries]
+               result.Truncated = true
+       }
+       for _, item := range summaries {
+               result.Traces = append(result.Traces, item.summary)
+       }
+       result.Total = total

Review Comment:
   🟡 **`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 一次。



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to