obsworkload

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: 12 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 obsworkload holds host-device workload correlation and activity join primitives re-exported by x/obs/diag.

Example
package main

import (
	"context"
	"fmt"

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

type exampleHook struct{ id uint64 }

func (h *exampleHook) Push(kind cupti.ExternalCorrelationKind, id uint64) error {
	h.id = id
	return nil
}

func (h *exampleHook) Pop(kind cupti.ExternalCorrelationKind) (uint64, error) {
	return h.id, nil
}

func main() {
	// Initialize workload annotator for process PID 1234, generation 1
	proc := obsworkload.ProcessGenID{PID: 1234, Generation: 1}
	annotator := obsworkload.NewAnnotator(proc, "inference-pipeline",
		obsworkload.WithCorrelationHook(&exampleHook{}),
	)

	ctx := context.Background()
	_, op := annotator.Begin(ctx, "prompt_prefill")
	defer op.End()

	// Perform scoped native CUDA call
	var nativeCorrID uint32 = 1001
	stream := obsworkload.ContextStreamID{Context: 0xCAFE, Stream: 0x1}
	sub, err := op.NativeCallWithSubmission(stream, obsworkload.GraphReplayGeneration{}, "cudaLaunchKernel", "kernel_ref", func() (uint32, error) {
		// Native CUDA driver/runtime launch occurs here on pinned OS thread.
		return nativeCorrID, nil
	})
	if err != nil {
		fmt.Printf("NativeCall error: %v\n", err)
		return
	}

	// Joiner correlates host submissions with incoming device activity records
	joiner := obsworkload.NewJoiner(obsworkload.JoinConfig{})
	joiner.SubmitHost(sub)

	// Simulate device activity record collected from CUPTI
	act := obsworkload.DeviceActivity{
		Process:               proc,
		NativeCorrelationID:   nativeCorrID,
		ExternalCorrelationID: uint64(op.ID()),
		Kind:                  "kernel",
		Name:                  "gemm_prefill_sm121",
		Context:               stream,
		StartNs:               10000,
		EndNs:                 15000,
	}

	results := joiner.SubmitDevice(act)
	for _, res := range results {
		fmt.Printf("Outcome: %s, Reason: %s, Workload: %s, operation matches: %t\n",
			res.Outcome, res.Reason, res.Workload.WorkloadName, res.OpID == op.ID())
	}

}
Output:
Outcome: exact, Reason: explicit_external_correlation_match, Workload: inference-pipeline, operation matches: true

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrPopMismatch = errors.New("cudaworkload: correlation pop ID mismatch")

ErrPopMismatch indicates that a correlation pop returned an ID different from the one pushed, signaling an unbalanced stack or unexpected thread migration.

Functions

func WithOperation

func WithOperation(ctx context.Context, s *Scope) context.Context

WithOperation returns a context that carries the given operation Scope.

Types

type ActivityBatch

type ActivityBatch struct {
	Session, Run, ClockEpoch, EvidenceRef string
	Process                               ProcessGenID
	ExternalKind                          cupti.ExternalCorrelationKind
	Records                               []cuptix.ActivityRecord
	// MaxRecords bounds records and annotations together; zero means 4096.
	MaxRecords int
}

ActivityBatch is a frozen CUPTI collection. ClockEpoch identifies the actual producer timestamp epoch; it is never derived from host wall time. Records and their ordering remain unchanged in the returned evidence.

type ActivityJoin

type ActivityJoin struct {
	Record                                       cuptix.ActivityRecord
	Session, Run, Clock, ClockEpoch, EvidenceRef string
	Join                                         JoinResult
}

ActivityJoin retains a raw record and its operation classification. Exact means an explicit external-ID link, not clock alignment or causal diagnosis.

func JoinActivities

func JoinActivities(batch ActivityBatch, annotations []HostSubmission) ([]ActivityJoin, error)

JoinActivities joins a completed batch against operation annotations. It scans the entire batch before emitting results, so later contradictory links cannot retroactively invalidate an emitted exact result. Native IDs alone and timestamp proximity never identify operations. Graph replay needs a separate explicit replay producer and is deliberately not inferred here.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/cupti"
	"github.com/tmc/lib/nvidia/x/obs/cuptix"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsworkload"
)

func main() {
	p := obsworkload.ProcessGenID{PID: 1, Generation: 2}
	sub := obsworkload.HostSubmission{Process: p, OpID: 9, Symbol: "native", Workload: obsworkload.WorkloadIdentity{Process: p, RunID: "run"}, Provenance: obsworkload.ProvenanceCUPTI, EvidenceRef: "annotation", Context: obsworkload.ContextStreamID{Context: 3, Stream: 4}}
	b := obsworkload.ActivityBatch{Session: "session", Run: "run", Process: p, ClockEpoch: "producer-epoch", EvidenceRef: "capture", ExternalKind: cupti.ExternalCorrelationKindCustom0, Records: []cuptix.ActivityRecord{
		{Kind: cupti.ActivityKindConcurrentKernel, CorrelationID: 7, ContextID: 3, StreamID: 4},
		{Kind: cupti.ActivityKindExternalCorrelation, CorrelationID: 7, ExternalKind: cupti.ExternalCorrelationKindCustom0, ExternalID: 9},
	}}
	joins, err := obsworkload.JoinActivities(b, []obsworkload.HostSubmission{sub})
	fmt.Println(joins[0].Join.Outcome, err)
}
Output:
exact <nil>

type Annotator

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

Annotator coordinates the allocation of operation identities and context propagation for application workloads.

func NewAnnotator

func NewAnnotator(proc ProcessGenID, workloadName string, opts ...AnnotatorOption) *Annotator

NewAnnotator creates a new Annotator bound to the given process generation.

func (*Annotator) Begin

func (a *Annotator) Begin(ctx context.Context, name string, opts ...ScopeOption) (context.Context, *Scope)

Begin initiates a new operation scope. If ctx already contains an active operation, the new operation is linked as a nested child.

type AnnotatorOption

type AnnotatorOption func(*Annotator)

AnnotatorOption configures an Annotator.

func WithCorrelationHook

func WithCorrelationHook(hook CorrelationHook) AnnotatorOption

WithCorrelationHook overrides the push/pop implementation used for native calls.

func WithCorrelationKind

func WithCorrelationKind(kind cupti.ExternalCorrelationKind) AnnotatorOption

WithCorrelationKind sets the CUPTI external correlation kind to use for native calls. Defaults to cupti.ExternalCorrelationKindCustom0 when enabled.

func WithDefaultLabels

func WithDefaultLabels(labels map[string]string) AnnotatorOption

WithDefaultLabels sets labels inherited by all operations created by the Annotator.

func WithRunID

func WithRunID(runID string) AnnotatorOption

WithRunID sets the run identifier for workloads created by the Annotator.

type ContextStreamID

type ContextStreamID struct {
	Context uint64 `json:"context"`
	Stream  uint64 `json:"stream"`
}

ContextStreamID identifies the target CUDA execution context and stream.

func (ContextStreamID) String

func (cs ContextStreamID) String() string

String formats the context and stream identifiers.

type CorrelationHook

type CorrelationHook interface {
	Push(kind cupti.ExternalCorrelationKind, id uint64) error
	Pop(kind cupti.ExternalCorrelationKind) (uint64, error)
}

CorrelationHook allows injecting custom correlation push/pop implementations for testing or alternative instrumentation providers.

type CorrelationProvenance

type CorrelationProvenance string

CorrelationProvenance records how the correlation link between host and device was established.

const (
	// ProvenanceUninstrumented indicates no external-correlation instrumentation
	// was enabled. It does not establish a runtime intercept or native ID link.
	ProvenanceUninstrumented CorrelationProvenance = "uninstrumented_native_call"
	// ProvenanceCUPTI indicates correlation was established via CUPTI external
	// correlation push/pop APIs.
	ProvenanceCUPTI CorrelationProvenance = "cupti_external_correlation"
	// ProvenanceUprobe indicates association via an independently verified host
	// uprobe call window with confirmed PID and TID during a locked thread interval.
	ProvenanceUprobe CorrelationProvenance = "uprobe_call_window"
	// ProvenanceRuntimeAPI indicates correlation established by a direct CUDA
	// runtime or driver API intercept shim.
	ProvenanceRuntimeAPI CorrelationProvenance = "runtime_api_intercept"
	// ProvenanceGraphNode indicates correlation linked through explicit CUDA
	// graph node capture and replay instance tracking.
	ProvenanceGraphNode CorrelationProvenance = "graph_node_instance"
	// ProvenanceSynthetic indicates a fixture or synthetic test event.
	ProvenanceSynthetic CorrelationProvenance = "synthetic_fixture"
)

type DeviceActivity

type DeviceActivity struct {
	Process               ProcessGenID          `json:"process"`
	NativeCorrelationID   uint32                `json:"native_correlation_id"`
	RuntimeCorrelationID  uint32                `json:"runtime_correlation_id,omitempty"`
	ExternalCorrelationID uint64                `json:"external_correlation_id,omitempty"`
	Kind                  string                `json:"kind"` // "kernel", "memcpy", "memset", "sync"
	Name                  string                `json:"name"`
	Context               ContextStreamID       `json:"context"`
	GraphReplay           GraphReplayGeneration `json:"graph_replay,omitempty"`
	StartNs               uint64                `json:"start_ns"`
	EndNs                 uint64                `json:"end_ns"`
	DeviceID              uint32                `json:"device_id"`
	EvidenceRef           string                `json:"evidence_ref,omitempty"`
}

DeviceActivity represents an executed GPU activity observed via CUPTI or driver.

type GraphReplayGeneration

type GraphReplayGeneration struct {
	GraphID          uint64 `json:"graph_id"`
	ExecGraphID      uint64 `json:"exec_graph_id"`
	ReplayGeneration uint64 `json:"replay_generation"`
}

GraphReplayGeneration identifies an execution instance of a captured CUDA graph. Capturing a graph assigns structure and node IDs; each execution of the graph via cudaGraphLaunch constitutes a discrete replay generation.

func (GraphReplayGeneration) IsZero

func (g GraphReplayGeneration) IsZero() bool

IsZero reports whether the GraphReplayGeneration indicates non-graph work.

func (GraphReplayGeneration) String

func (g GraphReplayGeneration) String() string

String formats the graph replay generation.

type HostSubmission

type HostSubmission struct {
	Process             ProcessGenID          `json:"process"`
	OpID                OpID                  `json:"op_id"`
	ParentOpID          OpID                  `json:"parent_op_id,omitempty"`
	Workload            WorkloadIdentity      `json:"workload"`
	NativeCorrelationID uint32                `json:"native_correlation_id"`
	Provenance          CorrelationProvenance `json:"provenance"`
	Context             ContextStreamID       `json:"context"`
	GraphReplay         GraphReplayGeneration `json:"graph_replay,omitempty"`
	TID                 uint64                `json:"tid,omitempty"`
	TimestampNs         uint64                `json:"timestamp_ns"`
	// TimestampClock and TimestampEpoch qualify TimestampNs. Omitted fields in
	// legacy records mean unknown; they must not be inferred from magnitude.
	TimestampClock string `json:"timestamp_clock,omitempty"`
	TimestampEpoch string `json:"timestamp_epoch,omitempty"`
	Symbol         string `json:"symbol"`
	EvidenceRef    string `json:"evidence_ref,omitempty"`
}

HostSubmission represents an API call or submission made on the host.

type JoinConfig

type JoinConfig struct {
	// MaxPendingRecords sets the maximum number of unmatched submissions or
	// activities retained in the pending FIFO buffer. Defaults to 4096 if <= 0.
	MaxPendingRecords int
	// LateAttachCutoffNs designates a timestamp before which unjoined activities
	// are immediately classified as OutcomeMissing with ReasonLateAttach.
	LateAttachCutoffNs uint64
}

JoinConfig configures the behavior and limits of a Joiner.

type JoinMetrics

type JoinMetrics struct {
	TotalSubmissions    uint64 `json:"total_submissions"`
	TotalActivities     uint64 `json:"total_activities"`
	ExactJoins          uint64 `json:"exact_joins"`
	AssociatedJoins     uint64 `json:"associated_joins"`
	AmbiguousJoins      uint64 `json:"ambiguous_joins"`
	MissingJoins        uint64 `json:"missing_joins"`
	MissingActivities   uint64 `json:"missing_activities"`
	AmbiguousActivities uint64 `json:"ambiguous_activities"`
	FalseExactJoins     uint64 `json:"false_exact_joins"`
}

JoinMetrics reports observed submissions, activities, and emitted results. MissingJoins and AmbiguousJoins include host-only results; the activity counters include only results carrying a device activity.

func (JoinMetrics) AmbiguousFraction

func (m JoinMetrics) AmbiguousFraction() float64

AmbiguousFraction reports the fraction of observed device activities emitted as ambiguous.

func (JoinMetrics) MissingFraction

func (m JoinMetrics) MissingFraction() float64

MissingFraction reports the fraction of observed device activities emitted as missing. Pending activities are not counted until they produce a result.

Example
m := JoinMetrics{TotalActivities: 2, MissingActivities: 1, MissingJoins: 4}
fmt.Println(m.MissingFraction())
Output:
0.5

func (JoinMetrics) Precision

func (m JoinMetrics) Precision() float64

Precision reports the fraction of exact joins that were true positives. In verified test harnesses tracking FalseExactJoins, any false exact join degrades precision.

func (JoinMetrics) Recall

func (m JoinMetrics) Recall() float64

Recall reports the fraction of total device activities successfully joined with exact certainty.

type JoinResult

type JoinResult struct {
	Outcome        WorkloadOutcome       `json:"outcome"`
	Reason         Reason                `json:"reason"`
	OpID           OpID                  `json:"op_id,omitempty"`
	ParentOpID     OpID                  `json:"parent_op_id,omitempty"`
	Workload       WorkloadIdentity      `json:"workload"`
	HostSubmission *HostSubmission       `json:"host_submission,omitempty"`
	DeviceActivity *DeviceActivity       `json:"device_activity,omitempty"`
	Provenance     CorrelationProvenance `json:"provenance,omitempty"`
	RawIDs         RawIDs                `json:"raw_ids"`
	EvidenceRef    string                `json:"evidence_ref,omitempty"`
}

JoinResult holds the classification, reason, and preserved evidence of a join.

type Joiner

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

Joiner coordinates evidence-preserving correlation between host submissions and device activities. Explicit native, runtime and external correlations may arrive in either order; all observed candidates must agree. A result consumes one counterpart, so this API does not infer one-to-many fanout.

func NewJoiner

func NewJoiner(cfg JoinConfig) *Joiner

NewJoiner instantiates a Joiner with the provided configuration.

func (*Joiner) Flush

func (j *Joiner) Flush() (results []JoinResult)

Flush emits all remaining unmatched pending submissions and activities as Missing.

func (*Joiner) Metrics

func (j *Joiner) Metrics() JoinMetrics

Metrics returns a snapshot of current join metrics.

func (*Joiner) RecordFalseExact

func (j *Joiner) RecordFalseExact()

RecordFalseExact increments the count of false exact joins in validation harnesses.

func (*Joiner) SubmitDevice

func (j *Joiner) SubmitDevice(act DeviceActivity) (results []JoinResult)

SubmitDevice enqueues a device activity, attempting to join it against pending host submissions or queuing it in the bounded FIFO buffer.

func (*Joiner) SubmitHost

func (j *Joiner) SubmitHost(sub HostSubmission) (results []JoinResult)

SubmitHost enqueues a host submission, joining it against pending activities or queuing it in the bounded FIFO buffer.

type OpID

type OpID uint64

OpID is a non-zero, monotonically increasing identifier allocated for an application operation scope. Zero indicates an invalid or unassigned ID.

func (OpID) IsValid

func (id OpID) IsValid() bool

IsValid reports whether the OpID is non-zero.

func (OpID) String

func (id OpID) String() string

String formats the OpID as a decimal string.

type ProcessGenID

type ProcessGenID struct {
	PID        uint32 `json:"pid"`
	Generation uint64 `json:"generation"`
}

ProcessGenID identifies a specific process execution instance. Pairing the operating system PID with a monotonic generation counter (or boot timestamp) guarantees that PID recycling after process termination cannot cause false joins.

func (ProcessGenID) IsZero

func (p ProcessGenID) IsZero() bool

IsZero reports whether the ProcessGenID has default/zero values.

func (ProcessGenID) String

func (p ProcessGenID) String() string

String formats the ProcessGenID.

type RawIDs

type RawIDs struct {
	ProcessGenID          ProcessGenID          `json:"process_gen_id"`
	NativeCorrelationID   uint32                `json:"native_correlation_id"`
	RuntimeCorrelationID  uint32                `json:"runtime_correlation_id,omitempty"`
	ExternalCorrelationID uint64                `json:"external_correlation_id,omitempty"`
	ContextStream         ContextStreamID       `json:"context_stream"`
	GraphReplay           GraphReplayGeneration `json:"graph_replay,omitempty"`
	TID                   uint64                `json:"tid,omitempty"`
}

RawIDs preserves verbatim identifiers from capture sources without alteration.

type Reason

type Reason string

Reason provides an explanation for why a specific Outcome was reached.

const (
	// ReasonExplicitExternalMatch indicates an exact match on CUPTI external correlation ID.
	ReasonExplicitExternalMatch Reason = "explicit_external_correlation_match"
	// ReasonExplicitNativeMatch indicates an exact match on native correlation ID.
	ReasonExplicitNativeMatch Reason = "explicit_native_correlation_match"
	// ReasonGraphReplayMatch indicates an exact match on graph node and replay generation.
	ReasonGraphReplayMatch Reason = "explicit_graph_replay_match"
	// ReasonStreamContextMatch indicates circumstantial association on context/stream.
	ReasonStreamContextMatch Reason = "associated_stream_context_active_scope"
	// ReasonConflictingExternalID indicates conflicting external correlation IDs were observed.
	ReasonConflictingExternalID Reason = "conflicting_external_correlation_ids"
	// ReasonConflictingOperations indicates multiple host operations claimed the same correlation ID.
	ReasonConflictingOperations Reason = "multiple_operations_for_correlation_id"
	// ReasonNoHostSubmission indicates a device activity had no matching host submission.
	ReasonNoHostSubmission Reason = "no_matching_host_submission"
	// ReasonNoDeviceActivity indicates a host submission had no matching device activity.
	ReasonNoDeviceActivity Reason = "no_matching_device_activity"
	// ReasonLateAttach indicates the activity timestamp was prior to the collector attach window.
	ReasonLateAttach Reason = "late_attach_unobserved_host_submission"
	// ReasonExpiredFIFO indicates the record expired from the bounded pending FIFO queue.
	ReasonExpiredFIFO Reason = "pending_buffer_fifo_expired"
	// ReasonProcessGenMismatch indicates PIDs matched but process generations differed.
	ReasonProcessGenMismatch Reason = "process_generation_mismatch"
	// ReasonUnannotatedActivity indicates unannotated GPU execution.
	ReasonUnannotatedActivity Reason = "unannotated_device_activity"
)

type Scope

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

Scope represents an active operation execution scope.

func OperationFromContext

func OperationFromContext(ctx context.Context) (*Scope, bool)

OperationFromContext retrieves the current operation Scope from ctx, if present.

func (*Scope) End

func (s *Scope) End()

End closes the operation scope.

func (*Scope) ID

func (s *Scope) ID() OpID

ID returns the operation's unique identifier.

func (*Scope) Name

func (s *Scope) Name() string

Name returns the descriptive operation name.

func (*Scope) NativeCall

func (s *Scope) NativeCall(fn func() error) (err error)

NativeCall executes a native CUDA submission function on a pinned OS thread, pushing the scope's OpID onto the thread-local CUPTI correlation stack for the duration of the call and popping it on completion.

Thread pinning via runtime.LockOSThread is active only for the duration of fn, ensuring the calling Go goroutine is unpinned immediately upon exit. Cleanup is balanced across all return paths, including errors and panics.

func (*Scope) NativeCallWithSubmission

func (s *Scope) NativeCallWithSubmission(cs ContextStreamID, graph GraphReplayGeneration, symbol string, evidenceRef string, fn func() (uint32, error)) (HostSubmission, error)

NativeCallWithSubmission executes a native submission function on a pinned OS thread, pushing correlation to CUPTI, invoking fn to obtain the driver/runtime correlation ID, and returning a populated HostSubmission.

func (*Scope) NativeOperation

func (s *Scope) NativeOperation(ctx context.Context, cs ContextStreamID, symbol, evidence string, fn func() error) (HostSubmission, error)

NativeOperation calls fn with the operation's external ID on the pinned thread. The returned annotation does not invent a native correlation ID. ctx cancellation is checked before entry; cancellation does not interrupt native code or imply device completion. fn must arrange its own cancellation.

func (*Scope) NewSubmission

func (s *Scope) NewSubmission(nativeCorr uint32, cs ContextStreamID, graph GraphReplayGeneration, symbol string, evidenceRef string) HostSubmission

NewSubmission constructs a HostSubmission record associated with this scope.

func (*Scope) ParentID

func (s *Scope) ParentID() OpID

ParentID returns the enclosing parent operation's identifier, or 0 if root.

func (*Scope) Workload

func (s *Scope) Workload() WorkloadIdentity

Workload returns a snapshot of the operation's workload identity.

type ScopeOption

type ScopeOption func(*Scope)

ScopeOption configures an operation Scope.

func WithScopeLabels

func WithScopeLabels(labels map[string]string) ScopeOption

WithScopeLabels adds or overrides labels for a specific Scope.

type WorkloadIdentity

type WorkloadIdentity struct {
	Process      ProcessGenID      `json:"process"`
	WorkloadName string            `json:"workload_name"`
	RunID        string            `json:"run_id,omitempty"`
	Labels       map[string]string `json:"labels,omitempty"`
}

WorkloadIdentity encapsulates the identifying metadata of an execution context, including the process generation, workload name, run identifier, and tags.

func (WorkloadIdentity) Clone

Clone returns a deep copy of the WorkloadIdentity.

type WorkloadOutcome

type WorkloadOutcome string

Outcome represents the classification of a correlation join result.

const (
	// OutcomeExact denotes an unambiguous, 1-to-1 correlation link independently
	// established via explicit correlation IDs or verified provenance.
	OutcomeExact WorkloadOutcome = "exact"
	// OutcomeAssociated denotes a contextual link (such as context, stream, or thread
	// association) where explicit correlation was not recorded.
	OutcomeAssociated WorkloadOutcome = "associated"
	// OutcomeAmbiguous denotes multiple candidate matches or conflicting correlation links.
	OutcomeAmbiguous WorkloadOutcome = "ambiguous"
	// OutcomeMissing denotes an activity or submission with no observed counterpart.
	OutcomeMissing WorkloadOutcome = "missing"
)

Jump to

Keyboard shortcuts

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