larry-zy commented on code in PR #1618:
URL: https://github.com/apache/dubbo-admin/pull/1618#discussion_r4522316585


##########
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

Review Comment:
   [P2] Preserve serial dependencies when reporting the critical path
   
   This new traversal selects only the last-finishing child at each level. For 
a complete, synchronous trace with `root=[0,100]ms`, then child `A=[0,90]ms` 
followed by child `B=[90,100]ms`, it returns `root -> B` and marks A as 
`onCriticalPath:false`. I reproduced this with `BuildTraceAnalysis`: the 
selected entries have only 10 ms of self time, although A accounts for 90% of 
the sequential request. A remains in `slowSpans`, but its critical-path flag is 
misleading for serial RPCs and multi-round agent execution. This occurs without 
truncation or parallel branches, so the documented caveat about omitted 
parallel work does not cover it. Please account for serial dependencies when 
identifying the latency-critical path, or expose this as a 
last-finishing-branch heuristic instead of promising a critical-path verdict.



##########
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),

Review Comment:
   [P2] Do not treat a recovered descendant failure as propagated root failure
   
   The new root-cause rule assumes any failed descendant explains the 
ancestor's failure, even across an explicitly successful span. A reproducible 
counterexample is `request(ERROR, SerializationError) -> retry-operation(OK)`, 
where the retry operation contains a failed first attempt and a successful 
second attempt; the request later fails independently while serializing its 
response. The current result sets the request's `RootCause` to false and emits 
`root cause: ...first-attempt ERROR TransientTimeout` in the summary. The 
statuses and tree establish neither that propagation nor that causal 
conclusion. Please preserve independent failure candidates, avoid inferring 
propagation through a successfully recovered operation, and qualify the summary 
when the available evidence cannot establish causality.



##########
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))

Review Comment:
   [P2] Do not use display-truncated data as complete diagnostic evidence
   
   The 32-attribute and 500-span limits in `GetTraceByID` predate this PR; the 
new issue is using that lossy representation as the input to 
`BuildTraceAnalysis`. With a single span containing 32 ordinary tags followed 
by `gen_ai.operation.name`, token usage and `error.type`, I reproduced 
`search_traces` returning `traceKind:"genai"` while analysis omitted `genai` 
entirely and reported `errorType:"unknown"`. In a separate 501-span case, 
clipping the failed child made the retained failed parent become 
`RootCause:true`, and the summary asserted that parent as the root cause. The 
top-level truncation flag does not prevent those affirmative classifications. 
Please preserve diagnostic attributes and relationships before applying 
presentation limits, and represent conclusions that depend on missing data as 
unknown/candidates. This concerns the new analysis input contract, not the 
already-fixed full-trace duration denominator or the existence of the old 
lookup limits.



##########
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

Review Comment:
   [P2] Preserve reference semantics before calculating blocking wait
   
   This is an integration issue in the new analyzer: the pre-existing 
`parentSpanID()` falls back to the first reference, including `FOLLOWS_FROM`, 
and this calculation now interprets every normalized child interval as time the 
parent waited. With a parent at `[0,100]ms` and a background span at 
`[10,910]ms` linked only by `FOLLOWS_FROM`, the analysis reports 90 ms of 
parent wait and includes the background span in the critical path. However, 
[OpenTracing defines 
FollowsFrom](https://opentracing.io/specification/#references-between-spans) 
for causal relationships where the parent does not depend on the child's 
result. Please retain the reference type in the analysis input and distinguish 
asynchronous links from blocking dependencies before computing wait time or the 
critical path. The existing lookup's normalization predates this PR; the new 
diagnostic interpretation is the behavior that needs adapting here.



##########
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)

Review Comment:
   [P2] Define how trace-ID lookup combines with search filters
   
   This new adapter forwards `traceID` alongside `service`, `operation`, `tags` 
and `minDuration`, but [Jaeger 1.70's 
handler](https://github.com/jaegertracing/jaeger/blob/v1.70.0/cmd/query/app/http_handler.go#L235)
 switches to `tracesByIDs` whenever a trace ID is present. That branch fetches 
the trace directly instead of running `FindTraces`, so the service, operation, 
tag and minimum-duration predicates are not applied. For example, 
`service=orders,tags=error=true,traceId=<healthy trace>` can return the healthy 
trace, despite the tool accepting these arguments as a combined search. Please 
either make ID lookup and filtered search explicit mutually exclusive modes, or 
apply the requested predicates after lookup. The current request-shape tests 
verify that parameters are sent but do not verify their actual combined 
semantics.



##########
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]

Review Comment:
   [P2] Drop the oldest probe result rather than the newest trace
   
   The new search requests `limit+1` traces, sorts their start times ascending, 
then keeps `summaries[:limit]`. With `limit=1` and the backend returning the 
latest and previous trace, this deterministically returns the previous trace 
and discards the latest one. I reproduced this directly with 
`summarizeJaegerTraces`. This also reverses the selection intended by [Jaeger's 
memory 
backend](https://github.com/jaegertracing/jaeger/blob/v1.70.0/internal/storage/v1/memory/memory.go),
 which retains the newest traces when applying its limit. An investigation of 
the most recent request can therefore miss exactly that request. Please select 
the newest N results before applying any ascending display order, and add a 
regression case for which trace survives the extra-result probe.



-- 
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