Debian Codegraph @

trace/internal/testtrace/validation.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Code generated by "gen.bash" from internal/trace; DO NOT EDIT.
6
7 //go:build go1.23
8
9 package testtrace
10
11 import (
12 "errors"
13 "fmt"
14 "golang.org/x/exp/trace"
15 "golang.org/x/exp/trace/internal/version"
16 "slices"
17 "strings"
18 )
19
20 // Validator is a type used for validating a stream of trace.Events.
21 type Validator struct {
22 lastTs trace.Time
23 gs map[trace.GoID]*goState
24 ps map[trace.ProcID]*procState
25 ms map[trace.ThreadID]*schedContext
26 ranges map[trace.ResourceID][]string
27 tasks map[trace.TaskID]string
28 lastSync trace.Sync
29 GoVersion version.Version
30
31 // Flags to modify validation behavior.
32 skipClockSnapshotChecks bool // Some platforms can't guarantee a monotonically increasing clock reading.
33 }
34
35 type schedContext struct {
36 M trace.ThreadID
37 P trace.ProcID
38 G trace.GoID
39 }
40
41 type goState struct {
42 state trace.GoState
43 binding *schedContext
44 }
45
46 type procState struct {
47 state trace.ProcState
48 binding *schedContext
49 }
50
51 // NewValidator creates a new Validator.
52 func NewValidator() *Validator {
53 return &Validator{
54 gs: make(map[trace.GoID]*goState),
55 ps: make(map[trace.ProcID]*procState),
56 ms: make(map[trace.ThreadID]*schedContext),
57 ranges: make(map[trace.ResourceID][]string),
58 tasks: make(map[trace.TaskID]string),
59 GoVersion: version.Current,
60 }
61 }
62
63 // SkipClockSnapshotChecks causes the validator to skip checks on the clock snapshots.
64 //
65 // Some platforms like Windows, with a small enough trace period, are unable to produce
66 // monotonically increasing timestamps due to very coarse clock granularity.
67 func (v *Validator) SkipClockSnapshotChecks() {
68 v.skipClockSnapshotChecks = true
69 }
70
71 // Event validates ev as the next event in a stream of trace.Events.
72 //
73 // Returns an error if validation fails.
74 func (v *Validator) Event(ev trace.Event) error {
75 e := new(errAccumulator)
76
77 // Validate timestamp order.
78 if v.lastTs != 0 {
79 if ev.Time() <= v.lastTs {
80 e.Errorf("timestamp out-of-order (want > %v) for %+v", v.lastTs, ev)
81 } else {
82 v.lastTs = ev.Time()
83 }
84 } else {
85 v.lastTs = ev.Time()
86 }
87
88 // Validate event stack.
89 checkStack(e, ev.Stack())
90
91 switch ev.Kind() {
92 case trace.EventSync:
93 s := ev.Sync()
94 if s.N != v.lastSync.N+1 {
95 e.Errorf("sync count is not sequential: expected %d, got %d", v.lastSync.N+1, s.N)
96 }
97 // The trace reader currently emits synthetic sync events at the end of
98 // a trace. Those don't contain clock snapshots data, so we don't try
99 // to validate them.
100 //
101 // TODO(felixge): Drop the synthetic syncs as discussed in CL 653576.
102 if v.GoVersion >= version.Go125 && !(s.N > 1 && s.ClockSnapshot == nil) {
103 if s.ClockSnapshot == nil {
104 e.Errorf("sync %d has no clock snapshot", s.N)
105 } else {
106 if s.ClockSnapshot.Wall.IsZero() {
107 e.Errorf("sync %d has zero wall time", s.N)
108 }
109 if s.ClockSnapshot.Mono == 0 {
110 e.Errorf("sync %d has zero mono time", s.N)
111 }
112 if s.ClockSnapshot.Trace == 0 {
113 e.Errorf("sync %d has zero trace time", s.N)
114 }
115 if !v.skipClockSnapshotChecks {
116 if s.N >= 2 && !s.ClockSnapshot.Wall.After(v.lastSync.ClockSnapshot.Wall) {
117 e.Errorf("sync %d has non-increasing wall time: %v vs %v", s.N, s.ClockSnapshot.Wall, v.lastSync.ClockSnapshot.Wall)
118 }
119 if s.N >= 2 && !(s.ClockSnapshot.Mono > v.lastSync.ClockSnapshot.Mono) {
120 e.Errorf("sync %d has non-increasing mono time: %v vs %v", s.N, s.ClockSnapshot.Mono, v.lastSync.ClockSnapshot.Mono)
121 }
122 if s.N >= 2 && !(s.ClockSnapshot.Trace > v.lastSync.ClockSnapshot.Trace) {
123 e.Errorf("sync %d has non-increasing trace time: %v vs %v", s.N, s.ClockSnapshot.Trace, v.lastSync.ClockSnapshot.Trace)
124 }
125 }
126 }
127 }
128 v.lastSync = s
129 case trace.EventMetric:
130 m := ev.Metric()
131 if !strings.Contains(m.Name, ":") {
132 // Should have a ":" as per runtime/metrics convention.
133 e.Errorf("invalid metric name %q", m.Name)
134 }
135 // Make sure the value is OK.
136 if m.Value.Kind() == trace.ValueBad {
137 e.Errorf("invalid value")
138 }
139 switch m.Value.Kind() {
140 case trace.ValueUint64:
141 // Just make sure it doesn't panic.
142 _ = m.Value.Uint64()
143 }
144 case trace.EventLabel:
145 l := ev.Label()
146
147 // Check label.
148 if l.Label == "" {
149 e.Errorf("invalid label %q", l.Label)
150 }
151
152 // Check label resource.
153 if l.Resource.Kind == trace.ResourceNone {
154 e.Errorf("label resource none")
155 }
156 switch l.Resource.Kind {
157 case trace.ResourceGoroutine:
158 id := l.Resource.Goroutine()
159 if _, ok := v.gs[id]; !ok {
160 e.Errorf("label for invalid goroutine %d", id)
161 }
162 case trace.ResourceProc:
163 id := l.Resource.Proc()
164 if _, ok := v.ps[id]; !ok {
165 e.Errorf("label for invalid proc %d", id)
166 }
167 case trace.ResourceThread:
168 id := l.Resource.Thread()
169 if _, ok := v.ms[id]; !ok {
170 e.Errorf("label for invalid thread %d", id)
171 }
172 }
173 case trace.EventStackSample:
174 // Not much to check here. It's basically a sched context and a stack.
175 // The sched context is also not guaranteed to align with other events.
176 // We already checked the stack above.
177 case trace.EventStateTransition:
178 // Validate state transitions.
179 //
180 // TODO(mknyszek): A lot of logic is duplicated between goroutines and procs.
181 // The two are intentionally handled identically; from the perspective of the
182 // API, resources all have the same general properties. Consider making this
183 // code generic over resources and implementing validation just once.
184 tr := ev.StateTransition()
185 checkStack(e, tr.Stack)
186 switch tr.Resource.Kind {
187 case trace.ResourceGoroutine:
188 // Basic state transition validation.
189 id := tr.Resource.Goroutine()
190 old, new := tr.Goroutine()
191 if new == trace.GoUndetermined {
192 e.Errorf("transition to undetermined state for goroutine %d", id)
193 }
194 if v.lastSync.N > 1 && old == trace.GoUndetermined {
195 e.Errorf("undetermined goroutine %d after first global sync", id)
196 }
197 if new == trace.GoNotExist && v.hasAnyRange(trace.MakeResourceID(id)) {
198 e.Errorf("goroutine %d died with active ranges", id)
199 }
200 state, ok := v.gs[id]
201 if ok {
202 if old != state.state {
203 e.Errorf("bad old state for goroutine %d: got %s, want %s", id, old, state.state)
204 }
205 state.state = new
206 } else {
207 if old != trace.GoUndetermined && old != trace.GoNotExist {
208 e.Errorf("bad old state for unregistered goroutine %d: %s", id, old)
209 }
210 state = &goState{state: new}
211 v.gs[id] = state
212 }
213 // Validate sched context.
214 if new.Executing() {
215 ctx := v.getOrCreateThread(e, ev, ev.Thread())
216 if ctx != nil {
217 if ctx.G != trace.NoGoroutine && ctx.G != id {
218 e.Errorf("tried to run goroutine %d when one was already executing (%d) on thread %d", id, ctx.G, ev.Thread())
219 }
220 ctx.G = id
221 state.binding = ctx
222 }
223 } else if old.Executing() && !new.Executing() {
224 if tr.Stack != ev.Stack() {
225 // This is a case where the transition is happening to a goroutine that is also executing, so
226 // these two stacks should always match.
227 e.Errorf("StateTransition.Stack doesn't match Event.Stack")
228 }
229 ctx := state.binding
230 if ctx != nil {
231 if ctx.G != id {
232 e.Errorf("tried to stop goroutine %d when it wasn't currently executing (currently executing %d) on thread %d", id, ctx.G, ev.Thread())
233 }
234 ctx.G = trace.NoGoroutine
235 state.binding = nil
236 } else {
237 e.Errorf("stopping goroutine %d not bound to any active context", id)
238 }
239 }
240 case trace.ResourceProc:
241 // Basic state transition validation.
242 id := tr.Resource.Proc()
243 old, new := tr.Proc()
244 if new == trace.ProcUndetermined {
245 e.Errorf("transition to undetermined state for proc %d", id)
246 }
247 if v.lastSync.N > 1 && old == trace.ProcUndetermined {
248 e.Errorf("undetermined proc %d after first global sync", id)
249 }
250 if new == trace.ProcNotExist && v.hasAnyRange(trace.MakeResourceID(id)) {
251 e.Errorf("proc %d died with active ranges", id)
252 }
253 state, ok := v.ps[id]
254 if ok {
255 if old != state.state {
256 e.Errorf("bad old state for proc %d: got %s, want %s", id, old, state.state)
257 }
258 state.state = new
259 } else {
260 if old != trace.ProcUndetermined && old != trace.ProcNotExist {
261 e.Errorf("bad old state for unregistered proc %d: %s", id, old)
262 }
263 state = &procState{state: new}
264 v.ps[id] = state
265 }
266 // Validate sched context.
267 if new.Executing() {
268 ctx := v.getOrCreateThread(e, ev, ev.Thread())
269 if ctx != nil {
270 if ctx.P != trace.NoProc && ctx.P != id {
271 e.Errorf("tried to run proc %d when one was already executing (%d) on thread %d", id, ctx.P, ev.Thread())
272 }
273 ctx.P = id
274 state.binding = ctx
275 }
276 } else if old.Executing() && !new.Executing() {
277 ctx := state.binding
278 if ctx != nil {
279 if ctx.P != id {
280 e.Errorf("tried to stop proc %d when it wasn't currently executing (currently executing %d) on thread %d", id, ctx.P, ctx.M)
281 }
282 ctx.P = trace.NoProc
283 state.binding = nil
284 } else {
285 e.Errorf("stopping proc %d not bound to any active context", id)
286 }
287 }
288 }
289 case trace.EventRangeBegin, trace.EventRangeActive, trace.EventRangeEnd:
290 // Validate ranges.
291 r := ev.Range()
292 switch ev.Kind() {
293 case trace.EventRangeBegin:
294 if v.hasRange(r.Scope, r.Name) {
295 e.Errorf("already active range %q on %v begun again", r.Name, r.Scope)
296 }
297 v.addRange(r.Scope, r.Name)
298 case trace.EventRangeActive:
299 if !v.hasRange(r.Scope, r.Name) {
300 v.addRange(r.Scope, r.Name)
301 }
302 case trace.EventRangeEnd:
303 if !v.hasRange(r.Scope, r.Name) {
304 e.Errorf("inactive range %q on %v ended", r.Name, r.Scope)
305 }
306 v.deleteRange(r.Scope, r.Name)
307 }
308 case trace.EventTaskBegin:
309 // Validate task begin.
310 t := ev.Task()
311 if t.ID == trace.NoTask || t.ID == trace.BackgroundTask {
312 // The background task should never have an event emitted for it.
313 e.Errorf("found invalid task ID for task of type %s", t.Type)
314 }
315 if t.Parent == trace.BackgroundTask {
316 // It's not possible for a task to be a subtask of the background task.
317 e.Errorf("found background task as the parent for task of type %s", t.Type)
318 }
319 // N.B. Don't check the task type. Empty string is a valid task type.
320 v.tasks[t.ID] = t.Type
321 case trace.EventTaskEnd:
322 // Validate task end.
323 // We can see a task end without a begin, so ignore a task without information.
324 // Instead, if we've seen the task begin, just make sure the task end lines up.
325 t := ev.Task()
326 if typ, ok := v.tasks[t.ID]; ok {
327 if t.Type != typ {
328 e.Errorf("task end type %q doesn't match task start type %q for task %d", t.Type, typ, t.ID)
329 }
330 delete(v.tasks, t.ID)
331 }
332 case trace.EventLog:
333 // There's really not much here to check, except that we can
334 // generate a Log. The category and message are entirely user-created,
335 // so we can't make any assumptions as to what they are. We also
336 // can't validate the task, because proving the task's existence is very
337 // much best-effort.
338 _ = ev.Log()
339 }
340 return e.Errors()
341 }
342
343 func (v *Validator) hasRange(r trace.ResourceID, name string) bool {
344 ranges, ok := v.ranges[r]
345 return ok && slices.Contains(ranges, name)
346 }
347
348 func (v *Validator) addRange(r trace.ResourceID, name string) {
349 ranges, _ := v.ranges[r]
350 ranges = append(ranges, name)
351 v.ranges[r] = ranges
352 }
353
354 func (v *Validator) hasAnyRange(r trace.ResourceID) bool {
355 ranges, ok := v.ranges[r]
356 return ok && len(ranges) != 0
357 }
358
359 func (v *Validator) deleteRange(r trace.ResourceID, name string) {
360 ranges, ok := v.ranges[r]
361 if !ok {
362 return
363 }
364 i := slices.Index(ranges, name)
365 if i < 0 {
366 return
367 }
368 v.ranges[r] = slices.Delete(ranges, i, i+1)
369 }
370
371 func (v *Validator) getOrCreateThread(e *errAccumulator, ev trace.Event, m trace.ThreadID) *schedContext {
372 lenient := func() bool {
373 // Be lenient about GoUndetermined -> GoSyscall transitions if they
374 // originate from an old trace. These transitions lack thread
375 // information in trace formats older than 1.22.
376 if v.GoVersion >= version.Go122 {
377 return false
378 }
379 if ev.Kind() != trace.EventStateTransition {
380 return false
381 }
382 tr := ev.StateTransition()
383 if tr.Resource.Kind != trace.ResourceGoroutine {
384 return false
385 }
386 from, to := tr.Goroutine()
387 return from == trace.GoUndetermined && to == trace.GoSyscall
388 }
389 if m == trace.NoThread && !lenient() {
390 e.Errorf("must have thread, but thread ID is none")
391 return nil
392 }
393 s, ok := v.ms[m]
394 if !ok {
395 s = &schedContext{M: m, P: trace.NoProc, G: trace.NoGoroutine}
396 v.ms[m] = s
397 return s
398 }
399 return s
400 }
401
402 func checkStack(e *errAccumulator, stk trace.Stack) {
403 // Check for non-empty values, but we also check for crashes due to incorrect validation.
404 for i, f := range slices.Collect(stk.Frames()) {
405 if i == 0 {
406 // Allow for one fully zero stack.
407 //
408 // TODO(mknyszek): Investigate why that happens.
409 continue
410 }
411 if f.Func == "" || f.File == "" || f.PC == 0 || f.Line == 0 {
412 e.Errorf("invalid stack frame %#v: missing information", f)
413 }
414 }
415 }
416
417 type errAccumulator struct {
418 errs []error
419 }
420
421 func (e *errAccumulator) Errorf(f string, args ...any) {
422 e.errs = append(e.errs, fmt.Errorf(f, args...))
423 }
424
425 func (e *errAccumulator) Errors() error {
426 return errors.Join(e.errs...)
427 }