Repository navigation
Expand file tree
/
Copy pathtracker_diagnose_scan.go
More file actions
198 lines (188 loc) · 6.35 KB
/
Copy pathtracker_diagnose_scan.go
File metadata and controls
198 lines (188 loc) · 6.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// ABOUTME: Activity-log scanning helpers for Diagnose — line loop, per-line
// ABOUTME: decoding, anomaly recording, and per-node failure enrichment.
package tracker
import (
"bufio"
"context"
"encoding/json"
"strings"
"time"
"github.com/2389-research/tracker/pipeline"
)
// scanActivityLoop drives the bufio scan of the activity log, delegating each
// line to processActivityLine. It returns early (without touching scanner.Err)
// when the context is cancelled, so the caller can distinguish cancellation
// from a scanner read error.
func scanActivityLoop(ctx context.Context, scanner *bufio.Scanner, secureUsed bool, anomalies *runtimeAnomalies, failures map[string]*NodeFailure, stageStarts map[string]time.Time, failSignatures map[string][]string) (*BudgetHalt, error) {
var halt *BudgetHalt
seq := 0
for scanner.Scan() {
if err := ctx.Err(); err != nil {
return nil, err
}
if h := processActivityLine(scanner.Text(), secureUsed, &seq, anomalies, failures, stageStarts, failSignatures); h != nil {
halt = h
}
}
return halt, nil
}
// processActivityLine folds one raw activity-log line into the running
// diagnosis state. The injection counter is bumped BEFORE the blank-line skip
// so blank padding on the secure log is still counted — matching
// ScanActivityLog.consumeLine (#213, #517). Returns a non-nil BudgetHalt only
// for a budget_exceeded line.
func processActivityLine(raw string, secureUsed bool, seq *int, anomalies *runtimeAnomalies, failures map[string]*NodeFailure, stageStarts map[string]time.Time, failSignatures map[string][]string) *BudgetHalt {
body, hasSentinel := stripActivitySentinel(raw)
if secureUsed && !hasSentinel {
anomalies.InjectedLines++
}
line := strings.TrimSpace(body)
if line == "" {
return nil
}
var entry diagnoseEntry
if err := json.Unmarshal([]byte(line), &entry); err != nil {
return nil
}
var halt *BudgetHalt
if pipeline.PipelineEventType(entry.Type) == pipeline.EventBudgetExceeded {
halt = &BudgetHalt{
TotalTokens: entry.TotalTokens,
TotalCostUSD: entry.TotalCostUSD,
WallElapsedMs: entry.WallElapsedMs,
Message: entry.Message,
}
}
recordAnomalyEvent(entry, seq, anomalies)
enrichFromEntry(entry, failures, stageStarts, failSignatures)
return halt
}
// recordAnomalyEvent appends the runtime anomaly (if any) carried by entry to
// anomalies, assigning each a monotonically increasing seq so the suggestion
// builder can merge the anomaly streams in chronological order.
func recordAnomalyEvent(entry diagnoseEntry, seq *int, anomalies *runtimeAnomalies) {
switch pipeline.PipelineEventType(entry.Type) {
case pipeline.EventToolOutputTruncated:
*seq++
anomalies.Truncations = append(anomalies.Truncations, truncObservation{
Seq: *seq,
NodeID: entry.NodeID,
Stream: entry.TruncStream,
Limit: entry.TruncLimit,
CapturedBytes: entry.TruncCaptured,
DroppedBytes: entry.TruncDropped,
TotalBytes: entry.TruncTotal,
})
case pipeline.EventConditionalFallthrough:
*seq++
anomalies.Fallthroughs = append(anomalies.Fallthroughs, fallthroughObservation{
Seq: *seq,
NodeID: entry.NodeID,
EdgeTo: entry.EdgeTo,
ConditionsTried: entry.ConditionsTried,
})
case pipeline.EventStageStarted:
// Mark a visit boundary so the suggestion builder can flush
// pending truncations from a prior visit before pairing
// within the new visit.
if entry.NodeID != "" {
*seq++
anomalies.VisitStarts = append(anomalies.VisitStarts, visitBoundary{
Seq: *seq,
NodeID: entry.NodeID,
})
}
case pipeline.EventToolMarkerMissing:
*seq++
anomalies.MarkerMissings = append(anomalies.MarkerMissings, markerMissingObservation{
Seq: *seq,
NodeID: entry.NodeID,
Pattern: entry.MarkerPattern,
CapturedTail: entry.MarkerTail,
Error: entry.MarkerError,
})
case pipeline.EventToolRouteMissing:
*seq++
anomalies.RouteMissings = append(anomalies.RouteMissings, routeMissingObservation{
Seq: *seq,
NodeID: entry.NodeID,
CapturedTail: entry.RouteTail,
})
case pipeline.EventAutoStatusMissing:
*seq++
anomalies.StatusMissings = append(anomalies.StatusMissings, statusMissingObservation{
Seq: *seq,
NodeID: entry.NodeID,
ResponseTail: entry.AutoStatusTail,
FailClosed: entry.AutoStatusFailClosed,
})
}
}
func enrichFromEntry(entry diagnoseEntry, failures map[string]*NodeFailure, stageStarts map[string]time.Time, failSignatures map[string][]string) {
ts, _ := parseActivityTimestamp(entry.Timestamp)
applyStageTiming(entry, failures, stageStarts, failSignatures, ts)
if entry.NodeID == "" {
return
}
f, ok := failures[entry.NodeID]
if !ok {
return
}
if entry.Error != "" {
f.Errors = append(f.Errors, entry.Error)
}
if entry.ToolErr != "" && f.Stderr == "" {
f.Stderr = entry.ToolErr
}
}
// applyStageTiming updates stage-timing bookkeeping (stageStarts) and, for
// failures, records the elapsed duration and the error signature used for
// retry analysis.
func applyStageTiming(entry diagnoseEntry, failures map[string]*NodeFailure, stageStarts map[string]time.Time, failSignatures map[string][]string, ts time.Time) {
switch entry.Type {
case "stage_started":
if !ts.IsZero() {
stageStarts[entry.NodeID] = ts
}
case "stage_failed":
updateFailureTiming(failures[entry.NodeID], stageStarts, entry, ts)
sig := entry.Error + "\x00" + entry.ToolErr
failSignatures[entry.NodeID] = append(failSignatures[entry.NodeID], sig)
case "stage_completed":
updateFailureTiming(failures[entry.NodeID], stageStarts, entry, ts)
}
}
func updateFailureTiming(f *NodeFailure, stageStarts map[string]time.Time, entry diagnoseEntry, ts time.Time) {
if f == nil {
return
}
if start, ok := stageStarts[entry.NodeID]; ok && !start.IsZero() && !ts.IsZero() {
f.Duration = ts.Sub(start)
}
if entry.Handler != "" {
f.Handler = entry.Handler
}
}
func applyRetryAnalysis(failures map[string]*NodeFailure, failSignatures map[string][]string) {
for nodeID, sigs := range failSignatures {
f, ok := failures[nodeID]
if !ok {
continue
}
f.RetryCount = len(sigs)
if len(sigs) >= 2 {
f.IdenticalRetries = allIdenticalStrings(sigs)
}
}
}
func allIdenticalStrings(ss []string) bool {
if len(ss) < 2 {
return false
}
for i := 1; i < len(ss); i++ {
if ss[i] != ss[0] {
return false
}
}
return true
}