obsprobe

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package obsprobe holds binary probe event decoders re-exported by x/obs/diag.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Track

func Track(ctx context.Context, source ProbeSource, tracker *Tracker) error

Track consumes source into tracker until target exit (io.EOF). A decode, ordering, cancellation or source error marks the interval incomplete and is returned with context. Track does not own or close the source's attachments. It retains only the tracker's bounded set of unmatched allocations.

Example
package main

import (
	"context"
	"encoding/binary"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
	"io"
)

// exampleSource stands in for a collector replaying a completed capture.
type exampleSource struct{ records []obsprobe.ProbeCapture }

func (s *exampleSource) Next(ctx context.Context) (obsprobe.ProbeCapture, error) {
	if err := ctx.Err(); err != nil {
		return obsprobe.ProbeCapture{}, err
	}
	if len(s.records) == 0 {
		return obsprobe.ProbeCapture{}, io.EOF
	}
	c := s.records[0]
	s.records = s.records[1:]
	return c, nil
}

func main() {
	c := obsprobe.ProbeCapture{Identity: obsprobe.ProbeIdentity{
		Process: obsprobe.Process{PID: 42, Generation: 123}, AddressSpace: 1,
		Library: "fixture.so", BuildID: "synthetic", Version: "fixture-v1",
		Symbol: "cudaMalloc", ABI: "linux-amd64-sysv-v1",
	}}
	binary.LittleEndian.PutUint16(c.Data[:], 1)
	binary.LittleEndian.PutUint16(c.Data[2:], 7)
	binary.LittleEndian.PutUint64(c.Data[8:], 1)
	binary.LittleEndian.PutUint64(c.Data[40:], 64)
	binary.LittleEndian.PutUint64(c.Data[120:], 0x8000)
	t, err := obsprobe.NewTracker(c.Identity.Process, 100)
	if err != nil {
		fmt.Println(err)
		return
	}
	if err := obsprobe.Track(context.Background(), &exampleSource{[]obsprobe.ProbeCapture{c}}, t); err != nil {
		fmt.Println(err)
		return
	}
	unmatched, incomplete := t.Report()
	fmt.Println("unmatched at exit:", len(unmatched), "incomplete:", incomplete)
}
Output:
unmatched at exit: 1 incomplete: false

Types

type AsyncMemory

type AsyncMemory struct {
	Address, Bytes, Stream uint64
	Free                   bool
}

AsyncMemory records stream-ordered allocation/free API arguments. A returned address does not establish device lifetime completion or allocation ordering.

Example
m := AsyncMemory{Address: 4096, Stream: 7, Free: true}
fmt.Println(m.Address, m.Stream, m.Free)
Output:
4096 7 true

type Binding

type Binding struct {
	Process                                               Process
	AddressSpace, Function, ModuleGeneration, First, Last uint64
	Evidence                                              string
	Artifact                                              *kernel.Artifact
}

Binding is a collector's explicit registration of a function to a loaded artifact. First and Last bound the inclusive process observation sequence interval during which the registration held. ModuleGeneration identifies the loaded module lifetime; Evidence identifies the registration receipt. A symbol-name match or disassembly alone cannot establish a Binding.

type Comparison

type Comparison struct {
	Probe, Independent Count
	Excess, Missing    uint64
}

Comparison retains independent counts and their unreconciled difference. Exactly one of Excess or Missing can be nonzero; subtraction cannot overflow.

func CompareCounts

func CompareCounts(probe, independent Count) (Comparison, error)

CompareCounts compares distinct sources over the same process and interval. It does not use agreement as proof that either source has complete coverage.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
)

func main() {
	p := obsprobe.Process{PID: 42, Generation: 123}
	a := obsprobe.Count{Process: p, Interval: "fixture-1", Source: "uprobe", Value: 4}
	b := obsprobe.Count{Process: p, Interval: "fixture-1", Source: "application", Value: 5}
	c, err := obsprobe.CompareCounts(a, b)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(c.Probe.Value, c.Independent.Value, c.Missing)
}
Output:
4 5 1

type Control

type Control struct {
	Scope, Operation string
	Handle           uint64
	Flags            uint32
	Device           int32
}

Control records explicit context or stream API handles. Handles are opaque; these observations do not establish an allocation address-space lifetime.

Example
c := Control{Scope: "context", Operation: "set_current", Handle: 7}
fmt.Println(c.Scope, c.Operation, c.Handle)
Output:
context set_current 7

type Copy

type Copy struct {
	Destination, Source, Bytes, Stream uint64
	Kind                               int32
	Direction                          string
	Async                              bool
}

Copy describes API copy arguments. Addresses are opaque observations, not dereferenceable Go pointers. Direction is explicit for Driver API calls; Runtime API calls retain Kind without resolving cudaMemcpyDefault addresses. Async identifies the API variant, not device completion or host blocking.

Example
e := Event{Decoded: true, Copy: &Copy{Bytes: 4096, Direction: "host_to_device", Async: true}}
fmt.Println(e.Copy.Bytes, e.Copy.Direction, e.Copy.Async)
Output:
4096 host_to_device true

type Count

type Count struct {
	Process          Process
	Interval, Source string
	Value            uint64
}

Count is a caller-supplied count of launch API observations, including failed launches, from one source and one explicitly identified measurement interval. It is not a count of GPU executions. Interval must identify the same boundaries for both sources, not just two similarly named workloads.

type DemangleReceipt

type DemangleReceipt struct{ Path, Version, Failure string }

DemangleReceipt identifies the actual toolkit executable and its version. A failure leaves symbols unchanged and records why. Results are not evidence that the corresponding kernel was loaded or executed.

type Demangler

type Demangler struct {
	// contains filtered or unexported fields
}

Demangler batches cu++filt calls through cudasass and retains a bounded cache. It is not safe for concurrent use. Call Batch after draining capture records; it executes an external process and must not be part of the drain loop.

func NewDemangler

func NewDemangler(path string, capacity int) (*Demangler, error)

NewDemangler creates a cache of at most capacity symbols. path selects cu++filt; an empty path uses the CUDA toolkit lookup in cudasass. Each batch admits at most capacity names of at most 4096 bytes each.

func (*Demangler) Batch

func (d *Demangler) Batch(ctx context.Context, symbols []string) ([]Name, DemangleReceipt, error)

Batch returns one name for each input, preserving order and duplicates. On a toolkit error it returns unchanged names for uncached symbols, a failure receipt and the error. Failures are not cached. Cancellation is propagated.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
	"os"
)

func main() {
	// This deliberately unavailable tool illustrates the offline fallback.
	d, err := obsprobe.NewDemangler(os.DevNull+"/cu++filt", 4)
	if err != nil {
		fmt.Println(err)
		return
	}
	names, receipt, err := d.Batch(context.Background(), []string{"_Z1fv"})
	fmt.Println(names[0].Display, names[0].Demangled, receipt.Failure != "", err != nil)
}
Output:
_Z1fv false true true

func (*Demangler) Records

func (d *Demangler) Records(ctx context.Context, records []iket.Record) ([]iket.Record, error)

Records demangles the identified kernel names in a drained batch, returning copies with toolkit receipts in their labels. It does not read from Source or push to the recorder. Unidentified records remain unidentified. On failure names are retained and the returned records carry the failure reason.

type Event

type Event struct {
	Identity            ProbeIdentity
	Sequence, Timestamp uint64
	Decoded             bool
	Reason              string
	ReturnKnown         bool
	Status              int32
	Launch              *ProbeLaunch
	Copy                *Copy
	Sync                *Sync
	Graph               *Graph
	AsyncMemory         *AsyncMemory
	Control             *Control
	Address, Bytes      uint64
}

Event is a decoded observation. Reason is nonempty when Decoded is false. Timestamp is in the collector's host monotonic clock, not GPU time or Unix time. ReturnKnown distinguishes success from an unobserved return value.

func DecodeProbe

func DecodeProbe(c ProbeCapture) (Event, error)

Decode decodes capture format version 1, a 128-byte little-endian record: version u16 at 0, flags u16 at 2, reserved zero u32 at 4, process sequence u64 at 8, host monotonic timestamp u64 at 16, return status i32 at 24, reserved zero u32 at 28, eleven u64 argument slots at 32, and the API output pointer value u64 at 120. Flags are arguments captured (1), return captured (2), and output captured after a successful return (4).

For ABI "linux-amd64-sysv-v1", argument slots are rdi, rsi, rdx, rcx, r8, r9, then five stack arguments starting at entry rsp+8. For ABI "linux-arm64-aapcs64-v1", slots are x0..x7 followed by three stack arguments starting at entry sp. Both ABIs normalize complete slots before encoding; decoding does not select an ABI from the replay host. The collector must never dereference kernelParams to infer kernel arguments. For cudaMalloc and cuMemAlloc_v2, stream-ordered allocation, context/stream creation and current-context queries, the output value is read from the saved first argument only on successful return. This format is a cudaprobe contract, not the unversioned Strobelight gpukern_sample structure.

Malformed records return an error. Unknown versions, ABIs, symbols and incomplete captures return an undecoded Event retaining its identity.

Example
package main

import (
	"encoding/binary"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
)

func main() {
	c := obsprobe.ProbeCapture{Identity: obsprobe.ProbeIdentity{
		Process: obsprobe.Process{PID: 42, Generation: 123},
		Library: "fixture.so", BuildID: "synthetic", Version: "fixture-v1",
		Symbol: "cuLaunchKernel", ABI: "linux-amd64-sysv-v1",
	}}
	binary.LittleEndian.PutUint16(c.Data[:], 1)
	binary.LittleEndian.PutUint16(c.Data[2:], 1)
	binary.LittleEndian.PutUint64(c.Data[8:], 1)
	for i, arg := range []uint64{0x100, 2, 3, 4, 32, 1, 1} {
		binary.LittleEndian.PutUint64(c.Data[32+8*i:], arg)
	}
	e, err := obsprobe.DecodeProbe(c)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(e.Launch.Grid, e.Launch.Block, e.ReturnKnown)
}
Output:
[2 3 4] [32 1 1] false

func (Event) Record

func (e Event) Record(received time.Time) (iket.Record, error)

Record converts an event to a flight-recorder observation. received is the collector's Unix receipt time used for retention; the source's monotonic timestamp remains in labels. Neither timestamp measures GPU execution. Call recorder.Push with the result after draining the capture source. Kernel names, tensor shapes/dtypes and device duration remain unavailable.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
	"time"
)

func main() {
	e := obsprobe.Event{Identity: obsprobe.ProbeIdentity{Provenance: "synthetic", Symbol: "cuLaunchKernel"}, Timestamp: 123}
	r, err := e.Record(time.Unix(1, 0))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(r.TimestampNs, r.Labels["probe.timestamp_ns"], r.Labels["duration_status"])
}
Output:
1000000000 123 unavailable

func (Event) RecordWithBindings

func (e Event) RecordWithBindings(received time.Time, bindings []Binding) (iket.Record, error)

RecordWithBindings records a launch with an explicit artifact registration. When Identify fails it returns the unjoined record and the error, so callers can retain the observation without claiming a kernel identity. An identified kernel still has no measured device duration.

type Graph

type Graph struct {
	Exec, Stream uint64
}

Graph describes a graph executable submission. Exec is an opaque handle; it does not identify individual graph nodes or their launch geometry.

Example
e := Event{Decoded: true, Graph: &Graph{Exec: 9, Stream: 7}}
fmt.Println(e.Graph.Exec, e.Graph.Stream)
Output:
9 7

type Interposition

type Interposition struct {
	Status   string
	Evidence string
}

Interposition is a caller-reported declaration for one exact probe target. Status is unknown (also the zero value), declared_active or declared_inactive. Evidence describes the declaration's source, not independently verified activity.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
	"time"
)

func main() {
	declaration := obsprobe.Interposition{Status: "declared_active", Evidence: "operator run manifest"}
	event := obsprobe.Event{Identity: obsprobe.ProbeIdentity{Interposition: declaration}}
	record, err := event.Record(time.Unix(100, 0))
	fmt.Println(err, record.Labels["probe.interposition"], record.Labels["probe.interposition_source"])
}
Output:
<nil> declared_active caller_reported

func (Interposition) Validate

func (i Interposition) Validate() error

Validate checks the declaration's syntax and bounds. It does not verify it.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
)

func main() {
	fmt.Println((obsprobe.Interposition{}).Validate())
}
Output:
<nil>

type KernelIdentity

type KernelIdentity struct {
	Digest, EntryPoint, Target, Evidence string
	ModuleGeneration                     uint64
}

KernelIdentity is an artifact join supported by a caller-supplied binding. It identifies code; it does not establish successful GPU execution.

func IdentifyProbe

func IdentifyProbe(e Event, bindings []Binding) (KernelIdentity, error)

Identify joins a decoded launch to exactly one explicit function registration. It validates the artifact digest and ABI descriptor and refuses ambiguous, stale or absent bindings. It does not infer registrations from kernel names.

type Name

type Name struct {
	Symbol, Display string
	Demangled       bool
}

type ProbeAllocation

type ProbeAllocation struct {
	AddressSpace, Address, Bytes, Sequence uint64
}

Allocation is an observed allocation without a matched successful free. It is not a leak diagnosis; unobserved paths can allocate or free memory.

type ProbeCapture

type ProbeCapture struct {
	Identity ProbeIdentity
	Data     [128]byte
}

Capture contains one completed API call, or one entry-only observation. Data is the fixed record accepted by Decode. Identity is resolved by the collector; it is retained even when decoding is unavailable.

type ProbeIdentity

type ProbeIdentity struct {
	ThreadGenerationKnown bool
	// ThreadGeneration is a verified Linux task birth identity; zero is unknown.
	ThreadID         uint32
	ThreadGeneration uint64
	Process          Process
	// Provenance identifies the capture source, for example "uprobe" or
	// "synthetic". Interposition retains a caller declaration, not proof of shim activity.
	Provenance    string
	Interposition Interposition
	// AddressSpace identifies a CUDA address-space lifetime, including context
	// reuse. Zero means unavailable; it must not join allocation observations.
	AddressSpace                           uint64
	Library, BuildID, Version, Symbol, ABI string
}

Identity records the provenance of a probe target. ABI is a capture contract, not an inferred property of a symbol name. Version identifies the observed CUDA library; BuildID identifies its exact image.

type ProbeLaunch

type ProbeLaunch struct {
	Function            uint64
	Grid, Block         [3]uint32
	SharedBytes, Stream uint64
}

Launch describes API launch arguments, not kernel execution or tensor shapes.

type ProbeSource

type ProbeSource interface {
	Next(context.Context) (ProbeCapture, error)
}

Source supplies observations in process sequence order. Next returns io.EOF after target exit and honors context cancellation. The collector owns attach, detach and drop accounting; sequence gaps must include dropped observations.

type Process

type Process struct {
	PID        uint32
	Generation uint64
}

Process identifies a process lifetime. Generation is a collector-supplied start identity, not merely a PID, so PID reuse cannot join allocations.

type Resolution

type Resolution struct {
	Target           Target
	BuildID          string
	Offset, FileSize uint64
	Function, PLT    bool
}

Resolution describes a file offset, not an ELF virtual address or a process address. Resolver must positively identify executable function code; PLT stubs, indirect resolvers and ambiguous symbols are not probe targets.

func Resolve

func Resolve(ctx context.Context, resolver Resolver, target Target) (Resolution, error)

Resolve verifies that the collector found the requested CUDA function in the specified file. It refuses PLT and out-of-file offsets and missing build IDs. Symbol parsing and version selection remain the resolver's responsibility.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
)

type exampleResolver struct{}

func (exampleResolver) Resolve(_ context.Context, target obsprobe.Target) (obsprobe.Resolution, error) {

	return obsprobe.Resolution{Target: target, BuildID: "synthetic", Offset: 64, FileSize: 128, Function: true}, nil
}

func main() {
	r, err := obsprobe.Resolve(context.Background(), exampleResolver{}, obsprobe.Target{Library: "fixture.so", Symbol: "cuLaunchKernel"})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(r.Target.Symbol, r.BuildID, r.Offset)
}
Output:
cuLaunchKernel synthetic 64

type Resolver

type Resolver interface {
	Resolve(context.Context, Target) (Resolution, error)
}

Resolver supplies host-generic symbol resolution. Implementations belong to the collector and must handle dynamic symbols, versioning and ELF translation. cudaprobe does not parse symbol tables itself.

type Sync

type Sync struct {
	Scope  string
	Stream uint64
}

Sync describes the synchronization scope requested by an API call. A decoded request does not establish device completion; retain ReturnKnown and Status.

Example
e := Event{Decoded: true, Sync: &Sync{Scope: "stream", Stream: 7}}
fmt.Println(e.Sync.Scope, e.Sync.Stream)
Output:
stream 7

type Target

type Target struct {
	Library, Symbol, SymbolVersion string
}

Target identifies a CUDA entry point in a specific library file. A nonempty SymbolVersion requests that exact ELF symbol version, not a CUDA version.

func Targets

func Targets() []Target

Targets lists the supported launch, copy, synchronization and allocation entry points. The library names are lookup hints; replace them with resolved absolute paths before attaching probes. Runtime and driver probes have distinct provenance.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
)

func main() {
	for _, target := range obsprobe.Targets() {
		fmt.Println(target.Library, target.Symbol)
	}
}
Output:
libcuda.so.1 cuLaunchKernel
libcuda.so.1 cuMemAlloc_v2
libcuda.so.1 cuMemFree_v2
libcudart.so cudaLaunchKernel
libcudart.so cudaMalloc
libcudart.so cudaFree
libcuda.so.1 cuMemcpyHtoD_v2
libcuda.so.1 cuMemcpyDtoH_v2
libcuda.so.1 cuMemcpyDtoD_v2
libcuda.so.1 cuMemcpyHtoDAsync_v2
libcuda.so.1 cuMemcpyDtoHAsync_v2
libcuda.so.1 cuMemcpyDtoDAsync_v2
libcuda.so.1 cuCtxSynchronize
libcuda.so.1 cuStreamSynchronize
libcuda.so.1 cuGraphLaunch
libcudart.so cudaMemcpy
libcudart.so cudaMemcpyAsync
libcudart.so cudaDeviceSynchronize
libcudart.so cudaStreamSynchronize
libcudart.so cudaGraphLaunch
libcuda.so.1 cuMemAllocAsync
libcuda.so.1 cuMemFreeAsync
libcuda.so.1 cuCtxCreate_v2
libcuda.so.1 cuCtxGetCurrent
libcuda.so.1 cuCtxSetCurrent
libcuda.so.1 cuCtxDestroy_v2
libcuda.so.1 cuStreamCreate
libcuda.so.1 cuStreamDestroy_v2
libcudart.so cudaMallocAsync
libcudart.so cudaFreeAsync
libcudart.so cudaStreamCreate
libcudart.so cudaStreamDestroy

type Tracker

type Tracker struct {
	// contains filtered or unexported fields
}

Tracker models synchronous CUDA allocation calls for one process lifetime. It is not safe for concurrent use. Construct it with NewTracker. It retains at most the configured number of allocations, with no history of freed ones. Runtime and driver probes for the same operation must not both feed it: nested calls are separate observations, not independent allocations.

func NewTracker

func NewTracker(process Process, capacity int) (*Tracker, error)

NewTracker creates a bounded allocation tracker for process.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
)

func main() {
	t, err := obsprobe.NewTracker(obsprobe.Process{PID: 42, Generation: 123}, 100)
	if err != nil {
		fmt.Println(err)
		return
	}
	t.Gap()
	t.Exit()
	unmatched, incomplete := t.Report()
	fmt.Println(len(unmatched), incomplete)
}
Output:
0 true

func (*Tracker) Exit

func (t *Tracker) Exit()

Exit closes the process lifetime. Remaining allocations are unmatched at exit, not leaks. Subsequent observations are rejected even if the PID is reused.

func (*Tracker) Gap

func (t *Tracker) Gap()

Gap marks the tracking interval incomplete when the collector reports loss without a subsequent event, for example a dropped tail before process exit.

func (*Tracker) Observe

func (t *Tracker) Observe(e Event) error

Observe applies one process-ordered observation. Sequence gaps, undecoded calls, duplicate live addresses, unknown frees and cap exhaustion make the report incomplete. Errors do not advance the sequence or alter allocations. Failed API calls do not allocate or free. Async allocation API observations are not applied because API return is not their lifetime completion boundary.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
)

func main() {
	p := obsprobe.Process{PID: 42, Generation: 123}
	t, err := obsprobe.NewTracker(p, 100)
	if err != nil {
		fmt.Println(err)
		return
	}
	e := obsprobe.Event{
		Identity: obsprobe.ProbeIdentity{Process: p, AddressSpace: 1, Symbol: "cudaMalloc"},
		Sequence: 1, Decoded: true, ReturnKnown: true, Address: 0x8000, Bytes: 64,
	}
	if err := t.Observe(e); err != nil {
		fmt.Println(err)
		return
	}
	a, incomplete := t.Report()
	fmt.Println(a[0].Bytes, incomplete)
}
Output:
64 false

func (*Tracker) Report

func (t *Tracker) Report() (unmatched []ProbeAllocation, incomplete bool)

Report copies the current unmatched allocations in address order. Incomplete remains true after any observation gap, even if all known allocations free.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL