Documentation
¶
Overview ¶
Package iket provides intra-kernel execution tracing (IKET), device ring buffers, CUDA phase markers, and GPU flight-recorder bundles.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example (Flightrecorder) ¶
package main
import (
"bytes"
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"log"
"time"
)
func main() {
rec, err := iket.New(iket.FlightConfig{
Window: 5 * time.Second,
Capacity: 1024,
})
if err != nil {
log.Fatal(err)
}
if err := rec.Start(); err != nil {
log.Fatal(err)
}
defer rec.Stop()
// Record an execution observation
rec.Push(iket.Record{
TimestampNs: time.Now().UnixNano(),
KernelName: "ds4_moe_expert_dispatch",
CorrelationID: 42,
DurationNs: 8500,
})
// Preserve recent observations at a workload boundary.
var buf bytes.Buffer
manifest, err := rec.Snapshot(context.Background(), &buf, "workload_boundary")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Snapshot reason: %s (records: %d)\n", manifest.Reason, manifest.GPURecords)
}
Output: Snapshot reason: workload_boundary (records: 1)
Example (Iket) ¶
package main
import (
"bytes"
"fmt"
iket "github.com/tmc/lib/nvidia/x/obs/iket"
)
func main() {
tr := &iket.RingTrace{
Config: iket.RingConfig{Rings: 1, Capacity: 4},
Events: []iket.Event{
{Start: 1000, End: 1000, SM: 0, Block: 0, Warp: 0, ID: 1},
{Start: 1000, End: 1800, SM: 0, Block: 0, Warp: 0, ID: 2},
},
}
var buf bytes.Buffer
err := iket.WriteSpanTrace(&buf, tr, "gemm_kernel", [3]int{1, 1, 1}, [3]int{32, 1, 1}, map[uint16]string{
1: "tma_arrive",
2: "mma_main",
})
if err != nil {
panic(err)
}
it, err := iket.ParseTrace(&buf)
if err != nil {
panic(err)
}
fmt.Printf("kernel=%s ranges=%d markers=%d strings=%v\n",
it.Launches[0].KernelName, len(it.Launches[0].Ranges), len(it.Launches[0].Markers), it.StringTable)
}
Output: kernel=gemm_kernel ranges=1 markers=1 strings=[tma_arrive mma_main]
Example (Ring) ¶
package main
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
)
func main() {
buf, err := iket.NewRingBuffer(iket.RingConfig{Rings: 2, Capacity: 4})
if err != nil {
panic(err)
}
// Simulate one sealed span recorded on SM 0, block 0, warp 0, id 1.
le := binary.LittleEndian
le.PutUint64(buf[32:], 1) // ring 0 count = 1
slot := buf[32+2*8:]
le.PutUint64(slot[0:], 1_000_000)
le.PutUint64(slot[8:], 1_002_500)
le.PutUint32(slot[16:], 0) // smid 0
le.PutUint32(slot[20:], 0) // block 0
le.PutUint16(slot[24:], 1) // id 1
le.PutUint16(slot[26:], 0) // warp 0
le.PutUint32(slot[28:], 0x4c414553) // "SEAL"
trace, err := iket.DecodeRing(buf)
if err != nil {
panic(err)
}
var out bytes.Buffer
if err := trace.WriteChromeTrace(&out, map[uint16]string{1: "train_p1"}); err != nil {
panic(err)
}
fmt.Printf("events=%d dropped=%d first_dur=%v has_name=%v\n",
len(trace.Events), trace.Dropped, trace.Events[0].Duration(),
bytes.Contains(out.Bytes(), []byte(`"train_p1"`)))
}
Output: events=1 dropped=0 first_dur=2.5µs has_name=true
Index ¶
- Constants
- Variables
- func AlignSpans(nowNs int64, windowNs int64, goStartNs int64, goHasData bool, records []Record, ...) (goSpanNs, gpuSpanNs, overlapSpanNs int64, overlapReliable bool)
- func AppendOTLPSpans(spans []OTLPSpan, parentKernelSpanID string, tr *Trace, cal *ClockCalibration, ...) ([]OTLPSpan, []OTLPStageSummary, error)
- func BuildHostClockRateControl(p0, p1 uint64, p2 []re_ikettrace.HostRateABBABlock, p3, p4, p5 uint64) (re_ikettrace.HostClockRateControl, error)
- func BuildKnownDurationControl(p0, p1, p2, p3, p4, p5, p6, p7, p8 uint64) (re_ikettrace.KnownDurationControl, error)
- func CalibrateFromSamples(p0 []re_ikettrace.ClockSample, p1 re_ikettrace.CalibrationConfig) (re_ikettrace.ClockCalibration, error)
- func CalibrateTrace(p0 *re_ikettrace.Trace, p1 re_ikettrace.ClockCalibration) (*re_ikettrace.Trace, error)
- func ClampEnabledCluster(p0, p1 [3]int) [3]int
- func CompareOverheadWithAA(p0 string, p1, p2 []re_ikettrace.ABBASpanBlock, p3 int) (re_ikettrace.ModeOverheadComparison, error)
- func CompareReplayJitterABBA(p0 []re_ikettrace.ABBAStep) (*timing.ReplayJitterReport, error)
- func ComputeABBAOverhead(p0 []re_ikettrace.ABBASpanBlock) (re_ikettrace.OverheadSummary, error)
- func CorruptBufferConstantTimestamps(p0 []byte, p1 uint64) ([]byte, error)
- func Decode(p0 []byte, p1 re_ikettrace.LaunchInfo) (*re_ikettrace.Trace, error)
- func DecodeFlightRecord(p0 []byte) (re_ikettrace.FlightRecord, error)
- func DecodeFlightRingHeader(p0 []byte) (re_ikettrace.FlightRingHeader, error)
- func DecodeRing(p0 []byte) (*re_ikettrace.RingTrace, error)
- func DefaultDAGCheckOptions() re_ikettrace.DAGCheckOptions
- func DiffTraces(p0, p1 *re_ikettrace.Trace) ([]re_ikettrace.RegionDiff, error)
- func EncodeFlightRecord(p0 []byte, p1 re_ikettrace.FlightRecord) error
- func EncodeFlightRingHeader(p0 []byte, p1 re_ikettrace.FlightRingHeader) error
- func ExportGPUVisTimeline(w io.Writer, s *FlightRingSnapshot) error
- func ExtractTraceMakespanNs(p0 *re_ikettrace.Trace) (uint64, error)
- func Float64Payload(p0 float64) re_ikettrace.Payload
- func FormatPTXMetadataSection(p0 int, p1 map[int]string) (string, error)
- func FromSpanTrace(p0 *re_ikettrace.RingTrace, p1 string, p2, p3 [3]int, p4 map[uint16]string) (*re_ikettrace.Trace, error)
- func FromSpanTraceWithInfo(p0 *re_ikettrace.RingTrace, p1 re_ikettrace.LaunchInfo) (*re_ikettrace.Trace, error)
- func InsertPTXMetadataSection(p0 []byte, p1 map[int]string) ([]byte, error)
- func Int64Payload(p0 int64) re_ikettrace.Payload
- func KVDigest(kv []byte) string
- func KnownDurationToleranceNs(p0, p1, p2 uint64) uint64
- func LookupGlobalTimerResolution(arch string) (re_ikettrace.GlobalTimerResolutionSpec, error)
- func MeasureClockCalibration(p0 re_ikettrace.CalibrationConfig, p1 func() (re_ikettrace.ClockSample, error)) (re_ikettrace.ClockCalibration, error)
- func MeasureDeviceClock(p0 re_ikettrace.CalibrationConfig, p1 func() (uint64, error)) (re_ikettrace.ClockCalibration, error)
- func MeasureIKETInstrumentationOverhead(p0, p1 []re_ikettrace.ABBASpanBlock) (re_ikettrace.OverheadReport, error)
- func MeasureInstrumentationOverhead(p0, p1 []re_ikettrace.ABBASpanBlock) (re_ikettrace.OverheadReport, error)
- func MeasureTraceTimerResolution(p0 *re_ikettrace.Trace) (uint64, int, error)
- func MeasuredGlobalTimerTickNs(arch string) (uint64, error)
- func MergeMultiRankTraces(p0 map[int]*re_ikettrace.Trace, p1 map[int]re_ikettrace.ClockCalibration) (*re_ikettrace.Trace, error)
- func MonotonicNanos() (uint64, error)
- func MonotonicRawNanos() (uint64, error)
- func NewBuffer(p0 re_ikettrace.Config) ([]byte, error)
- func NewClockSession(p0 re_ikettrace.CalibrationConfig) *re_ikettrace.ClockSession
- func NewClockTimeline(p0 []re_ikettrace.ClockCalibration, p1 re_ikettrace.CalibrationConfig) (*re_ikettrace.ClockTimeline, error)
- func NewDAG(p0 string) (*re_ikettrace.DAG, error)
- func NewFlightRing(p0 uint32, p1 re_ikettrace.FlightConfig) (*re_ikettrace.FlightRing, error)
- func NewFlightRingHeader(p0 uint32, p1 re_ikettrace.FlightConfig) re_ikettrace.FlightRingHeader
- func NewIKETLiveConsumer(p0 re_ikettrace.Config, p1 re_ikettrace.LaunchInfo) (*re_ikettrace.LiveConsumer, error)
- func NewLiveConsumer(p0 re_ikettrace.Config, p1 re_ikettrace.LaunchInfo) (*re_ikettrace.LiveConsumer, error)
- func NewLiveStreamConsumer(p0 re_ikettrace.RingConfig) (*re_ikettrace.LiveStreamConsumer, error)
- func NewNames(p0 ...string) (*re_ikettrace.Names, error)
- func NewRingBuffer(p0 re_ikettrace.RingConfig) ([]byte, error)
- func PTXMetadataLabel(p0 int) string
- func Parse(p0 io.Reader) ([]re_ikettrace.Summary, error)
- func ParseDAG(p0 io.Reader) (*re_ikettrace.DAG, error)
- func ParseEnabledCluster(p0 string) ([3]int, error)
- func ParseEnabledClusterConfig(p0 io.Reader) (map[string]re_ikettrace.EnabledClusterRule, error)
- func ParseFlightConfig(p0 []byte) (re_ikettrace.FlightConfig, error)
- func ParsePTXMetadataSection(p0 []byte) (map[int]string, error)
- func ParseTrace(p0 io.Reader) (*re_ikettrace.Trace, error)
- func ParseValidationReport(p0 io.Reader) (*re_ikettrace.ValidationReport, error)
- func PopulateAndValidateKnownDurations(p0 []re_ikettrace.KnownDurationControl) error
- func Ranges(p0 []byte, p1 re_ikettrace.LaunchInfo, ...) error
- func ReadHostInstant() (re_ikettrace.HostInstant, error)
- func ReadLoadedCUDALibraries(procRoot string, pid int) ([]string, error)
- func ResolveEnabledCluster(p0 map[string]re_ikettrace.EnabledClusterRule, p1 *[3]int, p2 string) ([3]int, bool)
- func ResolveTickQuantumFromTimestamps(p0 []uint64) uint64
- func Summarize(p0 string, p1 []uint64, p2 int, p3 []re_ikettrace.Phase, p4 int) (re_ikettrace.Summary, error)
- func SummarizeClock(p0 string, p1 []uint64, p2 int, p3 []re_ikettrace.Phase, p4 int, ...) (re_ikettrace.Summary, error)
- func SummarizeCrossSMSpread(p0 [][]uint64, p1 []uint32, p2 int, p3 uint64) (re_ikettrace.CrossSMConsistencyReport, error)
- func SummarizeDeviceTimerResolution(p0, p1, p2, p3 string, p4 []uint64) (re_ikettrace.DeviceTimerResolution, error)
- func SummarizeGlobalTimerDeltas(p0 []uint64) (uint64, uint64, uint64, uint64, map[uint64]int)
- func SummarizePerfettoTrace(p0 io.Reader) (string, error)
- func TraceToOTLPSpans(traceID, parentKernelSpanID string, tr *Trace, cal *ClockCalibration, ...) ([]OTLPSpan, []OTLPStageSummary, error)
- func Uint64Payload(p0 uint64) re_ikettrace.Payload
- func ValidateHostClockRateControl(p0 re_ikettrace.HostClockRateControl) error
- func ValidateKnownDurationControl(p0 re_ikettrace.KnownDurationControl) error
- func ValidateKnownDurations(p0 []re_ikettrace.KnownDurationControl) error
- func ValidateName(p0 string) error
- func VerifyKnownDurationMutants(p0 []re_ikettrace.KnownDurationControl) (string, string, error)
- func VerifyNegativeControlConstantTimestamp(p0 []byte, p1 re_ikettrace.LaunchInfo, p2, p3, p4, p5, p6 uint64) (re_ikettrace.NegativeControlResult, error)
- func VerifySharedDeviceTimerRateMutant(p0 []re_ikettrace.HostClockRateControl) (bool, string, error)
- func WriteBundle(w io.Writer, b *Bundle) (err error)
- func WritePerfettoFlowJSON(p0 io.Writer, p1 *re_ikettrace.Trace, p2 *re_ikettrace.DAG) error
- func WriteSpanTrace(p0 io.Writer, p1 *re_ikettrace.RingTrace, p2 string, p3, p4 [3]int, ...) error
- func WriteTrace(p0 io.Writer, p1 *re_ikettrace.Trace) error
- type ABBASpanBlock
- type ABBAStep
- type Budgets
- type BufferWriterFactory
- type Bundle
- func (b *Bundle) DecodeFaultEvidence() (FaultInfo, NegativeRewriteConstraint, error)
- func (b *Bundle) ExportGPUVisTimeline(w io.Writer) error
- func (b *Bundle) FlightRingSnapshot() (*FlightRingSnapshot, error)
- func (b *Bundle) GPUVisTimeline() (*GPUVisTimeline, error)
- func (b *Bundle) Reproducer() (*Reproducer, error)
- type CUPTIActivityCapture
- type CUPTIActivityCaptureConfig
- type CUPTINegotiator
- type CalibrationConfig
- type CandidateAssociation
- type CaptureReport
- type CaptureWriterFactory
- type CausalStepStitch
- type ClockCalibration
- type ClockSample
- type ClockSession
- type ClockTimeline
- type ClusterCoord
- type Config
- type CriticalPathNode
- type CriticalPathReport
- type CrossSMConsistencyReport
- type CrossSMSampleEntry
- type DAG
- type DAGCheckOptions
- type DAGEdge
- type DAGEdgeSummary
- type DAGScope
- type DAGViolation
- type DAGViolationKind
- type DecodedFlightRecord
- type DecodedFlightSpan
- type DefaultCUPTINegotiator
- type Detector
- type DetectorConfig
- type DetectorDecision
- type DetectorObservation
- type DeviceRing
- func (d *DeviceRing) Lookback(triggerNs int64, reason string) (*DeviceRingLookback, error)
- func (d *DeviceRing) ObserveStep(ctx context.Context, w io.Writer, step int, name string, startNs, endNs int64) (*Manifest, *DeviceRingLookback, error)
- func (d *DeviceRing) Poll() error
- func (d *DeviceRing) PollIKET(refTimestampNs int64) (int, error)
- func (d *DeviceRing) PushActivity(a cuptix.ActivityRecord)
- func (d *DeviceRing) PushIKETEvent(ev DeviceRingIKETEvent)
- func (d *DeviceRing) PushPMSample(sample cuptix.PMSample)
- func (d *DeviceRing) RecordStep(step int, name string, startNs, endNs int64) bool
- func (d *DeviceRing) Start() error
- func (d *DeviceRing) Stop() error
- type DeviceRingConfig
- type DeviceRingIKETEvent
- type DeviceRingLookback
- type DeviceRingStep
- type DeviceTimerResolution
- type DirectoryWriterFactory
- type DropError
- type EnabledClusterRule
- type EscalationCoordinator
- func (ec *EscalationCoordinator) Arm() error
- func (ec *EscalationCoordinator) Close() error
- func (ec *EscalationCoordinator) CooldownRemaining() time.Duration
- func (ec *EscalationCoordinator) Disarm() error
- func (ec *EscalationCoordinator) History() []IncidentReceipt
- func (ec *EscalationCoordinator) State() State
- func (ec *EscalationCoordinator) Stop() error
- func (ec *EscalationCoordinator) Trigger(ctx context.Context, req TriggerRequest) (*IncidentReceipt, error)
- func (ec *EscalationCoordinator) TriggerAsync(ctx context.Context, req TriggerRequest) (<-chan EscalationResult, error)
- func (ec *EscalationCoordinator) Wait(ctx context.Context) error
- type EscalationOption
- func WithCUPTINegotiator(n CUPTINegotiator) EscalationOption
- func WithCaptureWriterFactory(f CaptureWriterFactory) EscalationOption
- func WithClock(c FlightClock) EscalationOption
- func WithIncidentCapture(provider IncidentCapture) EscalationOption
- func WithResourceSampler(s ResourceSampler) EscalationOption
- type EscalationResult
- type Event
- type EventPos
- type FakeCUPTINegotiator
- type FakeClock
- type FakeResourceSampler
- type FaultInfo
- type FlightCfg
- type FlightClock
- type FlightConfig
- type FlightLayout
- type FlightRecord
- type FlightRing
- type FlightRingDecodeOptions
- type FlightRingHeader
- type FlightRingSnapshot
- type GPUVisEvent
- type GPUVisTimeline
- type GlobalTimerResolutionSpec
- type GoTraceRecorder
- type GoTraceValidation
- type GoTraceValidator
- type HostClockRateControl
- type HostDeviceGap
- type HostInstant
- type HostRateABBABlock
- type HostResourceSampler
- type IKETIncident
- type IKETLiveConsumer
- type IKETOverheadReport
- type IKETOverheadSummary
- type IKETTriggerPolicy
- type IncidentCapture
- type IncidentReceipt
- type InternalEvent
- type KnownDurationControl
- type KnownDurationTrial
- type Launch
- type LaunchInfo
- type LibExt
- type LiveConsumer
- type LiveStreamConsumer
- type LoadedModule
- type Location
- type Manifest
- type Marker
- type Meta
- type ModeOverheadComparison
- type ModuleDriver
- type ModuleHandle
- type ModuleHook
- func (h *ModuleHook) LoadModule(image []byte, kernelName string) (*LoadedModule, error)
- func (h *ModuleHook) LoadModuleData(image []byte) (*LoadedModule, error)
- func (h *ModuleHook) Module(mod ModuleHandle) (LoadedModule, bool)
- func (h *ModuleHook) SetConfig(mod ModuleHandle, cfg cudasass.PatchConfig) error
- func (h *ModuleHook) SetMode(mod ModuleHandle, mode uint32) error
- func (h *ModuleHook) SetModeAll(mode uint32) error
- func (h *ModuleHook) Stats() ModuleHookStats
- func (h *ModuleHook) UnloadModule(mod ModuleHandle) error
- type ModuleHookConfig
- type ModuleHookStats
- type Names
- type NegativeControlResult
- type NegativeRewriteConstraint
- type OTLPEdge
- type OTLPOptions
- type OTLPSpan
- type OTLPStageSummary
- type OverheadReport
- type OverheadSummary
- type PatchFunc
- type Payload
- type PayloadType
- type PerturbationReport
- type Phase
- type PhaseClock
- type PhaseStat
- type PreTriggerReport
- type Range
- type RangeScope
- type RangeType
- type RealClock
- type Record
- type Recorder
- func (r *Recorder) AttachFile(name string, data []byte)
- func (r *Recorder) CalibrateClock() error
- func (r *Recorder) CleanupErr() error
- func (r *Recorder) Close() error
- func (r *Recorder) DetachFile(name string)
- func (r *Recorder) FaultSnapshot(ctx context.Context, w io.Writer, fault FaultInfo) (*Manifest, error)
- func (r *Recorder) Handler() http.Handler
- func (r *Recorder) PreTriggerDiagnostics(triggerNs int64, window time.Duration) PreTriggerReport
- func (r *Recorder) Push(rec Record)
- func (r *Recorder) PushActivityRecord(activity cuptix.ActivityRecord)
- func (r *Recorder) PushPMSample(sample cuptix.PMSample)
- func (r *Recorder) PushPolicyRecord(timestampNs int64, hook string, labels map[string]string)
- func (r *Recorder) PushSASSMetric(timestampNs int64, correlationID uint64, sm cuptix.SASSMetric)
- func (r *Recorder) Register(mux *http.ServeMux)
- func (r *Recorder) SetCleanupErr(err error)
- func (r *Recorder) SetGPUPprofProvider(p func(context.Context) ([]byte, error))
- func (r *Recorder) SetGoTraceProvider(p func(context.Context) ([]byte, error))
- func (r *Recorder) SetPerfettoProvider(p func(context.Context) ([]byte, error))
- func (r *Recorder) SetSystemInfo(info *SystemInfo)
- func (r *Recorder) Snapshot(ctx context.Context, w io.Writer, reason string) (*Manifest, error)
- func (r *Recorder) SnapshotOnIKETIncident(ctx context.Context, w io.Writer, trace *Trace, policy IKETTriggerPolicy) (*Manifest, *IKETIncident, error)
- func (r *Recorder) Start() error
- func (r *Recorder) Stop()
- type RegionDiff
- type RegionSummary
- type Reproducer
- type ReproducerKernel
- type ReproducerRow
- type ResourceSampler
- type RingConfig
- type RingTrace
- type SleepBracketResult
- type SnapshotDiskManager
- type StageSpan
- type State
- type StitchedKernel
- type StuckRingError
- type StuckSegmentError
- type Summary
- type SystemInfo
- type TailConfig
- type TailDecision
- type TailRecorder
- func (t *TailRecorder) Complete(ctx context.Context, id string, ids []uint64, ttft, maxITL time.Duration, ...) (TailDecision, error)
- func (t *TailRecorder) Record(step TailStep) (bool, error)
- func (t *TailRecorder) Stats() TailStats
- func (t *TailRecorder) Trigger(ctx context.Context, reason string, ids []uint64) (TailDecision, error)
- type TailStats
- type TailStep
- type Trace
- type TriggerEvidence
- type TriggerRequest
- type ValidationReport
- type WarpLifetime
- type WorkloadTrigger
- type WorkloadTriggerConfig
- type WorkloadTriggerResult
- type WorkloadTriggerWindow
Examples ¶
- Package (Flightrecorder)
- Package (Iket)
- Package (Ring)
- Bundle.Reproducer
- Detector.Observe
- EscalationCoordinator
- EscalationCoordinator.TriggerAsync
- EvaluateIKETIncident
- FormatPTXMetadataSection
- InsertPTXMetadataSection
- NewCUPTIActivityCapture
- NewDAG
- NewDetector
- NewTailRecorder
- NewWorkloadTrigger
- ParsePTXMetadataSection
- Recorder.CalibrateClock
- Recorder.PushPMSample
- Recorder.PushPolicyRecord
- Recorder.PushSASSMetric
- Recorder.Snapshot (WithGoTrace)
- TailRecorder.Record
- TraceToOTLPSpans
- ValidateGoTrace
- WorkloadTrigger.Observe
Constants ¶
const ( FaultSchemaVersion = 1 FaultInfoSchemaVersion = FaultSchemaVersion NegativeRewriteConstraintSchemaVersion = FaultSchemaVersion )
FaultSchemaVersion is the current schema version for exported FaultInfo and NegativeRewriteConstraint replay and quarantine records.
const ( DefaultMaxRingActivities = 65536 DefaultMaxRingPMSamples = 16384 DefaultMaxRingIKETEvents = 65536 DefaultMaxRingSteps = 16384 )
Default limits for DeviceRingConfig.
const ( RefusalCooldownActive = "cooldown_active" RefusalCPUExceeded = "cpu_budget_exceeded" RefusalRSSExceeded = "rss_budget_exceeded" RefusalConcurrencyLimit = "concurrency_limit_exceeded" RefusalTenantConcurrency = "tenant_concurrency_exceeded" RefusalTenantRate = "tenant_rate_exceeded" RefusalCUPTIConflict = "cupti_ownership_conflict" RefusalHysteresisNotMet = "hysteresis_not_met" RefusalStopped = "stopped" RefusalDisarmed = "disarmed" )
Refusal reason codes.
const ( DefaultWindow = 10 * time.Second DefaultCapacity = 65536 DefaultEndpoint = "/debug/flightrecorder" )
Default settings for the flight recorder.
const ( RowDecode = "decode" RowPrompt = "prompt" )
Row kinds of a ReproducerRow.
const ( // KVPages means the KV pages the rows read are copied into the bundle // entry named by [Reproducer.KVFile]. KVPages = "pages" // KVPrefill means each row carries its prefix tokens and replay // rebuilds the KV pages by a deterministic prefill. KVPrefill = "prefill" )
Sources of a reproducer's KV state.
const CallerAssertedCandidateIdentity = "compiler_workload_input_reference_assertions"
CallerAssertedCandidateIdentity marks compiler identity and caller workload, input and reference assertions, rather than a native attribution proof.
const CandidateReferenceMismatch = "evaluator_candidate_reference_mismatch"
CandidateReferenceMismatch identifies an evaluator-observed candidate-arm comparison failure. It makes no claim about the cause of the wrong output.
const DefaultCalibrationSamples = re_ikettrace.DefaultCalibrationSamples
const DefaultCrossSMRepeats = re_ikettrace.DefaultCrossSMRepeats
const DefaultGlobalTimerToleranceNs = re_ikettrace.DefaultGlobalTimerToleranceNs
const DefaultHostRateABBAPairs = re_ikettrace.DefaultHostRateABBAPairs
const DefaultHostRateGateMaxRelDiff = re_ikettrace.DefaultHostRateGateMaxRelDiff
const DefaultMaxDriftPpm = re_ikettrace.DefaultMaxDriftPpm
const DefaultMaxEventsPerWarp = re_ikettrace.DefaultMaxEventsPerWarp
const DefaultMaxSessionCalibrations = re_ikettrace.DefaultMaxSessionCalibrations
const DefaultMaxStuckPolls = re_ikettrace.DefaultMaxStuckPolls
const DefaultMaxTimestamps = re_ikettrace.DefaultMaxTimestamps
const DefaultMaxUnsealedPolls = re_ikettrace.DefaultMaxUnsealedPolls
const DefaultMinFitSpanNs = re_ikettrace.DefaultMinFitSpanNs
const DefaultRawDriftFloorPPM = re_ikettrace.DefaultRawDriftFloorPPM
const DefaultRecalibrationIntervalNs = re_ikettrace.DefaultRecalibrationIntervalNs
const DefaultValidationABBAPairs = re_ikettrace.DefaultValidationABBAPairs
const EventPop = re_ikettrace.EventPop
const EventPosEnd = re_ikettrace.EventPosEnd
const EventPosInternal = re_ikettrace.EventPosInternal
const EventPosNone = re_ikettrace.EventPosNone
const EventPosStart = re_ikettrace.EventPosStart
const EventPosStartEnd = re_ikettrace.EventPosStartEnd
const EventSize = re_ikettrace.EventSize
const FlagRingWrap = re_ikettrace.FlagRingWrap
const FlagSubStages = re_ikettrace.FlagSubStages
const FlightCfgSize = re_ikettrace.FlightCfgSize
const FlightCfgSymbol = re_ikettrace.FlightCfgSymbol
const FlightFlagEntry = re_ikettrace.FlightFlagEntry
const FlightFlagExit = re_ikettrace.FlightFlagExit
const FlightFlagMark = re_ikettrace.FlightFlagMark
const FlightFlagOverflow = re_ikettrace.FlightFlagOverflow
const FlightModeEntryExit = re_ikettrace.FlightModeEntryExit
const FlightModeFull = re_ikettrace.FlightModeFull
const FlightModeOff = re_ikettrace.FlightModeOff
const FlightRecordSize = re_ikettrace.FlightRecordSize
const FlightRingCapacityOffset = re_ikettrace.FlightRingCapacityOffset
const FlightRingFlagPowerOfTwo = re_ikettrace.FlightRingFlagPowerOfTwo
const FlightRingFlagWrap = re_ikettrace.FlightRingFlagWrap
const FlightRingHeaderSize = re_ikettrace.FlightRingHeaderSize
const FlightRingMagic = re_ikettrace.FlightRingMagic
const FlightRingValidFlagsMask = re_ikettrace.FlightRingValidFlagsMask
const FlightRingVersion = re_ikettrace.FlightRingVersion
const FlightRingWriteIdxOffset = re_ikettrace.FlightRingWriteIdxOffset
const FlightValidFlagsMask = re_ikettrace.FlightValidFlagsMask
const GPUVisTimelineFormat = "gpuvis.timeline.v1"
GPUVisTimelineFormat is the canonical format string for gpuvis timeline JSON exports.
const GoTraceValidatorAuthority = "caller-selected validator assertion; not independent decoder authority; timing and population unvalidated"
GoTraceValidatorAuthority states the boundary of every GoTraceValidation.
const IKET_PAYLOAD_CYCLES = re_ikettrace.IKET_PAYLOAD_CYCLES
const InternalFlushEnd = re_ikettrace.InternalFlushEnd
const InternalFlushStart = re_ikettrace.InternalFlushStart
const Magic = re_ikettrace.Magic
const MaxClusterSelect = re_ikettrace.MaxClusterSelect
const MaxEventID = re_ikettrace.MaxEventID
const MaxEventNameLen = re_ikettrace.MaxEventNameLen
const MaxTraceMarkEventID = re_ikettrace.MaxTraceMarkEventID
const PayloadBF16 = re_ikettrace.PayloadBF16
const PayloadCycles = re_ikettrace.PayloadCycles
const PayloadFP16 = re_ikettrace.PayloadFP16
const PayloadFP32 = re_ikettrace.PayloadFP32
const PayloadFP4 = re_ikettrace.PayloadFP4
const PayloadFP64 = re_ikettrace.PayloadFP64
const PayloadFP8 = re_ikettrace.PayloadFP8
const PayloadFloat64 = re_ikettrace.PayloadFloat64
const PayloadI16 = re_ikettrace.PayloadI16
const PayloadI32 = re_ikettrace.PayloadI32
const PayloadI64 = re_ikettrace.PayloadI64
const PayloadI8 = re_ikettrace.PayloadI8
const PayloadInt64 = re_ikettrace.PayloadInt64
const PayloadNone = re_ikettrace.PayloadNone
const PayloadPTR = re_ikettrace.PayloadPTR
const PayloadPointer = re_ikettrace.PayloadPointer
const PayloadUI16 = re_ikettrace.PayloadUI16
const PayloadUI32 = re_ikettrace.PayloadUI32
const PayloadUI8 = re_ikettrace.PayloadUI8
const PayloadUint64 = re_ikettrace.PayloadUint64
const Prefix = re_ikettrace.Prefix
const RangeInvalid = re_ikettrace.RangeInvalid
const RangeMultiEvent = re_ikettrace.RangeMultiEvent
const RangePushPop = re_ikettrace.RangePushPop
const RangeStartEnd = re_ikettrace.RangeStartEnd
const ReproducerVersion = 1
ReproducerVersion is the only supported Reproducer version.
const ScopeBlock = re_ikettrace.ScopeBlock
const ScopeGPC = re_ikettrace.ScopeGPC
const ScopeGrid = re_ikettrace.ScopeGrid
const ScopeInterWarpCTA = re_ikettrace.ScopeInterWarpCTA
const ScopeIntraWarp = re_ikettrace.ScopeIntraWarp
const ScopeSM = re_ikettrace.ScopeSM
const ScopeTPC = re_ikettrace.ScopeTPC
const ScopeWarp = re_ikettrace.ScopeWarp
const StringTableWarnThreshold = re_ikettrace.StringTableWarnThreshold
const TraceMarkDomain = re_ikettrace.TraceMarkDomain
const ValidFlagsMask = re_ikettrace.ValidFlagsMask
const ValidationSchemaVersion = re_ikettrace.ValidationSchemaVersion
const Version = re_ikettrace.Version
const ViolationCountMismatch = re_ikettrace.ViolationCountMismatch
const ViolationOrdering = re_ikettrace.ViolationOrdering
const ViolationUnpairedEdge = re_ikettrace.ViolationUnpairedEdge
Variables ¶
var ( ErrDiskBudgetExceeded = errors.New("cudaflightrecorder: disk retention budget exhausted") ErrProviderBudgetExceeded = errors.New("cudaflightrecorder: provider output budget exceeded") ErrSnapshotBudgetExceeded = errors.New("cudaflightrecorder: snapshot size budget exceeded") ErrPlaceholderRejected = errors.New("cudaflightrecorder: placeholder payload rejected") ErrArtifactInvalid = errors.New("cudaflightrecorder: invalid artifact format") )
Budget and validation errors.
var ( ErrGoTraceValidatorUnselected = errors.New("cudaflightrecorder: go trace validator not selected") ErrGoTraceNotRetained = errors.New("cudaflightrecorder: go.trace not retained") ErrGoTraceValidatorResult = errors.New("cudaflightrecorder: go trace validator result invalid") )
Errors returned by ValidateGoTrace.
var ( // ErrModuleNotFound is returned when an operation references a module // handle not registered with the hook. ErrModuleNotFound = errors.New("cudaflightrecorder: module not found") // ErrInvalidFlightMode is returned when a requested FlightMode is outside // [cudasass.FlightModeOff, cudasass.FlightModeFull]. ErrInvalidFlightMode = errors.New("cudaflightrecorder: invalid flight mode") )
var DefaultHostRateTargetsNs = re_ikettrace.DefaultHostRateTargetsNs
var DefaultKnownDurationTargetsNs = re_ikettrace.DefaultKnownDurationTargetsNs
var ErrCausalStitchViolation = re_ikettrace.ErrCausalStitchViolation
var ErrEmptyDeviceRing = errors.New("cudaflightrecorder: empty device ring lookback")
ErrEmptyDeviceRing reports that a triggered device-ring lookback snapshot contained zero device activity records, PM counter samples, or IKET events while execution steps were observed in the lookback window.
var ErrEscalationQueueFull = errors.New("cudaflightrecorder: escalation queue full")
ErrEscalationQueueFull indicates that no bounded pending-job slot is available. The request was not admitted and will not produce a completion result.
var ErrEscalationRefused = fmt.Errorf("cudaflightrecorder: escalation refused: %w", cuda.ErrUnsupported)
ErrEscalationRefused indicates that an escalation trigger was examined and refused.
var ErrFlightRingInvalidLayout = re_ikettrace.ErrFlightRingInvalidLayout
var ErrFlightRingInvalidMagic = re_ikettrace.ErrFlightRingInvalidMagic
var ErrFlightRingShortBuffer = re_ikettrace.ErrFlightRingShortBuffer
var ErrFlightRingUnsupportedVersion = re_ikettrace.ErrFlightRingUnsupportedVersion
var ErrInvertedStageSpan = ikettrace.ErrInvertedStageSpan
ErrInvertedStageSpan reports that an IKET stage range has an end timestamp earlier than its start timestamp.
var ErrNoEvents = re_ikettrace.ErrNoEvents
var ErrNoPTXMetadataSection = re_ikettrace.ErrNoPTXMetadataSection
var ErrReproducerMismatch = errors.New("cudaflightrecorder: reproducer hash mismatch")
ErrReproducerMismatch reports that a reproducer's recorded input hash or KV hash does not match the inputs it was checked against. A replay that gets this error must refuse to run the step.
var ErrUnresolvedGap = re_ikettrace.ErrUnresolvedGap
var FlightHeader = re_ikettrace.FlightHeader
var Header = re_ikettrace.Header
var PhaseHeader = re_ikettrace.PhaseHeader
var Python = re_ikettrace.Python
var RingHeader = re_ikettrace.RingHeader
Functions ¶
func AlignSpans ¶
func AlignSpans( nowNs int64, windowNs int64, goStartNs int64, goHasData bool, records []Record, clockUncertaintyNs int64, ) (goSpanNs, gpuSpanNs, overlapSpanNs int64, overlapReliable bool)
AlignSpans computes observed time spans and alignment metrics across host Go tracing and GPU device observations relative to the snapshot time.
func AppendOTLPSpans ¶
func AppendOTLPSpans(spans []OTLPSpan, parentKernelSpanID string, tr *Trace, cal *ClockCalibration, opts *OTLPOptions) ([]OTLPSpan, []OTLPStageSummary, error)
AppendOTLPSpans converts tr into OTLP child spans nested under parentKernelSpanID and appends them to spans.
func BuildHostClockRateControl ¶
func BuildHostClockRateControl(p0, p1 uint64, p2 []re_ikettrace.HostRateABBABlock, p3, p4, p5 uint64) (re_ikettrace.HostClockRateControl, error)
func BuildKnownDurationControl ¶
func BuildKnownDurationControl(p0, p1, p2, p3, p4, p5, p6, p7, p8 uint64) (re_ikettrace.KnownDurationControl, error)
func CalibrateFromSamples ¶
func CalibrateFromSamples(p0 []re_ikettrace.ClockSample, p1 re_ikettrace.CalibrationConfig) (re_ikettrace.ClockCalibration, error)
func CalibrateTrace ¶
func CalibrateTrace(p0 *re_ikettrace.Trace, p1 re_ikettrace.ClockCalibration) (*re_ikettrace.Trace, error)
func ClampEnabledCluster ¶
func CompareOverheadWithAA ¶
func CompareOverheadWithAA(p0 string, p1, p2 []re_ikettrace.ABBASpanBlock, p3 int) (re_ikettrace.ModeOverheadComparison, error)
func CompareReplayJitterABBA ¶
func CompareReplayJitterABBA(p0 []re_ikettrace.ABBAStep) (*timing.ReplayJitterReport, error)
func ComputeABBAOverhead ¶
func ComputeABBAOverhead(p0 []re_ikettrace.ABBASpanBlock) (re_ikettrace.OverheadSummary, error)
func Decode ¶
func Decode(p0 []byte, p1 re_ikettrace.LaunchInfo) (*re_ikettrace.Trace, error)
func DecodeFlightRecord ¶
func DecodeFlightRecord(p0 []byte) (re_ikettrace.FlightRecord, error)
func DecodeFlightRingHeader ¶
func DecodeFlightRingHeader(p0 []byte) (re_ikettrace.FlightRingHeader, error)
func DecodeRing ¶
func DecodeRing(p0 []byte) (*re_ikettrace.RingTrace, error)
func DefaultDAGCheckOptions ¶
func DefaultDAGCheckOptions() re_ikettrace.DAGCheckOptions
func DiffTraces ¶
func DiffTraces(p0, p1 *re_ikettrace.Trace) ([]re_ikettrace.RegionDiff, error)
func EncodeFlightRecord ¶
func EncodeFlightRecord(p0 []byte, p1 re_ikettrace.FlightRecord) error
func EncodeFlightRingHeader ¶
func EncodeFlightRingHeader(p0 []byte, p1 re_ikettrace.FlightRingHeader) error
func ExportGPUVisTimeline ¶
func ExportGPUVisTimeline(w io.Writer, s *FlightRingSnapshot) error
ExportGPUVisTimeline writes s formatted as a gpuvis timeline JSON document to w.
func ExtractTraceMakespanNs ¶
func ExtractTraceMakespanNs(p0 *re_ikettrace.Trace) (uint64, error)
func Float64Payload ¶
func Float64Payload(p0 float64) re_ikettrace.Payload
func FormatPTXMetadataSection ¶
Example ¶
package main
import (
"fmt"
iket "github.com/tmc/lib/nvidia/x/obs/iket"
)
func main() {
section, err := iket.FormatPTXMetadataSection(iket.TraceMarkDomain, map[int]string{
1: "rmsnorm",
2: "qkv_gemm",
})
if err != nil {
panic(err)
}
fmt.Print(section)
fmt.Printf("trace.mark.b32 1, %%r1, %s;\n", iket.PTXMetadataLabel(1))
}
Output: .metadata_section { .metadata_domain 1 .metadata 1 { "rmsnorm", .b32 1, .metadata_label "iket_stage_1" } .metadata 2 { "qkv_gemm", .b32 2, .metadata_label "iket_stage_2" } } trace.mark.b32 1, %r1, iket_stage_1;
func FromSpanTrace ¶
func FromSpanTrace(p0 *re_ikettrace.RingTrace, p1 string, p2, p3 [3]int, p4 map[uint16]string) (*re_ikettrace.Trace, error)
func FromSpanTraceWithInfo ¶
func FromSpanTraceWithInfo(p0 *re_ikettrace.RingTrace, p1 re_ikettrace.LaunchInfo) (*re_ikettrace.Trace, error)
func InsertPTXMetadataSection ¶
Example ¶
package main
import (
"fmt"
iket "github.com/tmc/lib/nvidia/x/obs/iket"
"strings"
)
func main() {
// ptx is nvcc output for a kernel that calls iket_hw_trace_mark_b32.
ptx := `.version 9.5
.target sm_107f
.address_size 64
.visible .entry k()
{
.reg .b32 %r<2>;
trace.mark.b32 1, %r1, iket_stage_1;
ret;
}
`
stages := map[int]string{1: "rmsnorm", 2: "qkv_gemm"}
out, err := iket.InsertPTXMetadataSection([]byte(ptx), stages)
if err != nil {
panic(err)
}
fmt.Print(string(out[:strings.Index(string(out), ".visible")]))
}
Output: .version 9.5 .target sm_107f .address_size 64 .metadata_section { .metadata_domain 1 .metadata 1 { "rmsnorm", .b32 1, .metadata_label "iket_stage_1" } }
func Int64Payload ¶
func Int64Payload(p0 int64) re_ikettrace.Payload
func KVDigest ¶
KVDigest returns the hex SHA-256 of kv, the form of Reproducer.KVHash.
func LookupGlobalTimerResolution ¶
func LookupGlobalTimerResolution(arch string) (re_ikettrace.GlobalTimerResolutionSpec, error)
func MeasureClockCalibration ¶
func MeasureClockCalibration(p0 re_ikettrace.CalibrationConfig, p1 func() (re_ikettrace.ClockSample, error)) (re_ikettrace.ClockCalibration, error)
func MeasureDeviceClock ¶
func MeasureDeviceClock(p0 re_ikettrace.CalibrationConfig, p1 func() (uint64, error)) (re_ikettrace.ClockCalibration, error)
func MeasureIKETInstrumentationOverhead ¶
func MeasureIKETInstrumentationOverhead(p0, p1 []re_ikettrace.ABBASpanBlock) (re_ikettrace.OverheadReport, error)
func MeasureInstrumentationOverhead ¶
func MeasureInstrumentationOverhead(p0, p1 []re_ikettrace.ABBASpanBlock) (re_ikettrace.OverheadReport, error)
func MeasureTraceTimerResolution ¶
func MeasureTraceTimerResolution(p0 *re_ikettrace.Trace) (uint64, int, error)
func MergeMultiRankTraces ¶
func MergeMultiRankTraces(p0 map[int]*re_ikettrace.Trace, p1 map[int]re_ikettrace.ClockCalibration) (*re_ikettrace.Trace, error)
func MonotonicNanos ¶
func MonotonicRawNanos ¶
func NewClockSession ¶
func NewClockSession(p0 re_ikettrace.CalibrationConfig) *re_ikettrace.ClockSession
func NewClockTimeline ¶
func NewClockTimeline(p0 []re_ikettrace.ClockCalibration, p1 re_ikettrace.CalibrationConfig) (*re_ikettrace.ClockTimeline, error)
func NewDAG ¶
func NewDAG(p0 string) (*re_ikettrace.DAG, error)
Example ¶
package main
import (
"fmt"
iket "github.com/tmc/lib/nvidia/x/obs/iket"
)
func main() {
dag, err := iket.NewDAG("warp_specialized_gemm")
if err != nil {
panic(err)
}
if err := dag.AddEdge("dma_load", "mma_compute", "smem_pipe", "mbarrier"); err != nil {
panic(err)
}
fmt.Printf("dag=%s regions=%v edges=%d\n", dag.Name, dag.Regions, len(dag.Edges))
}
Output: dag=warp_specialized_gemm regions=[dma_load mma_compute] edges=1
func NewFlightRing ¶
func NewFlightRing(p0 uint32, p1 re_ikettrace.FlightConfig) (*re_ikettrace.FlightRing, error)
func NewFlightRingHeader ¶
func NewFlightRingHeader(p0 uint32, p1 re_ikettrace.FlightConfig) re_ikettrace.FlightRingHeader
func NewIKETLiveConsumer ¶
func NewIKETLiveConsumer(p0 re_ikettrace.Config, p1 re_ikettrace.LaunchInfo) (*re_ikettrace.LiveConsumer, error)
func NewLiveConsumer ¶
func NewLiveConsumer(p0 re_ikettrace.Config, p1 re_ikettrace.LaunchInfo) (*re_ikettrace.LiveConsumer, error)
func NewLiveStreamConsumer ¶
func NewLiveStreamConsumer(p0 re_ikettrace.RingConfig) (*re_ikettrace.LiveStreamConsumer, error)
func NewRingBuffer ¶
func NewRingBuffer(p0 re_ikettrace.RingConfig) ([]byte, error)
func PTXMetadataLabel ¶
func ParseEnabledCluster ¶
func ParseEnabledClusterConfig ¶
func ParseEnabledClusterConfig(p0 io.Reader) (map[string]re_ikettrace.EnabledClusterRule, error)
func ParseFlightConfig ¶
func ParseFlightConfig(p0 []byte) (re_ikettrace.FlightConfig, error)
func ParsePTXMetadataSection ¶
Example ¶
package main
import (
"fmt"
iket "github.com/tmc/lib/nvidia/x/obs/iket"
)
func main() {
ptx := `.version 9.5
.target sm_107f
.address_size 64
.metadata_section {
.metadata_domain 1
.metadata 1 { "rmsnorm", .b32 1, .metadata_label "iket_stage_1" }
.metadata 2 { "qkv_gemm", .b32 2, .metadata_label "iket_stage_2" }
}
`
stages, err := iket.ParsePTXMetadataSection([]byte(ptx))
if err != nil {
panic(err)
}
fmt.Println(stages[1], stages[2])
}
Output: rmsnorm qkv_gemm
func ParseTrace ¶
func ParseTrace(p0 io.Reader) (*re_ikettrace.Trace, error)
func ParseValidationReport ¶
func ParseValidationReport(p0 io.Reader) (*re_ikettrace.ValidationReport, error)
func PopulateAndValidateKnownDurations ¶
func PopulateAndValidateKnownDurations(p0 []re_ikettrace.KnownDurationControl) error
func Ranges ¶
func Ranges(p0 []byte, p1 re_ikettrace.LaunchInfo, p2 func(r re_ikettrace.Range, name string, loc re_ikettrace.Location) error) error
func ReadHostInstant ¶
func ReadHostInstant() (re_ikettrace.HostInstant, error)
func ReadLoadedCUDALibraries ¶
ReadLoadedCUDALibraries scans /proc/<pid>/maps (under procRoot) and returns the sorted list of distinct loaded CUDA/NVIDIA shared library paths (such as libcublasLt.so.*, libnvrtc.so.*, libcudart.so.*, libcuda.so.*, libcupti.so.*).
func ResolveEnabledCluster ¶
func ResolveEnabledCluster(p0 map[string]re_ikettrace.EnabledClusterRule, p1 *[3]int, p2 string) ([3]int, bool)
func Summarize ¶
func Summarize(p0 string, p1 []uint64, p2 int, p3 []re_ikettrace.Phase, p4 int) (re_ikettrace.Summary, error)
func SummarizeClock ¶
func SummarizeClock(p0 string, p1 []uint64, p2 int, p3 []re_ikettrace.Phase, p4 int, p5 re_ikettrace.PhaseClock) (re_ikettrace.Summary, error)
func SummarizeCrossSMSpread ¶
func SummarizeCrossSMSpread(p0 [][]uint64, p1 []uint32, p2 int, p3 uint64) (re_ikettrace.CrossSMConsistencyReport, error)
func SummarizeDeviceTimerResolution ¶
func SummarizeDeviceTimerResolution(p0, p1, p2, p3 string, p4 []uint64) (re_ikettrace.DeviceTimerResolution, error)
func TraceToOTLPSpans ¶
func TraceToOTLPSpans(traceID, parentKernelSpanID string, tr *Trace, cal *ClockCalibration, opts *OTLPOptions) ([]OTLPSpan, []OTLPStageSummary, error)
TraceToOTLPSpans converts tr into OTLP child spans nested under parentKernelSpanID with span_kind="iket_stage" and per-stage summaries. Any inverted stage range fails closed with ErrInvertedStageSpan.
Example ¶
package main
import (
"fmt"
iket "github.com/tmc/lib/nvidia/x/obs/iket"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
tr := &iket.Trace{
TimerResolutionNs: 32,
StringTable: []string{"decode_attention"},
LocationTable: []iket.Location{{SMID: 3, CTAID: [3]int{0, 0, 0}, WarpID: 0}},
Launches: []iket.Launch{
{
KernelName: "ServeAttention",
GridDimX: 1,
GridDimY: 1,
GridDimZ: 1,
BlockDimX: 128,
BlockDimY: 1,
BlockDimZ: 1,
Ranges: []iket.Range{
{RangeID: 0, RangeNameIdx: 0, StartTs: 1_000, EndTs: 2_600, WarpLocIdxs: []int{0}},
},
},
},
}
cal := &iket.ClockCalibration{
HostBaseNs: 1_700_000_000_000_000,
DeviceBaseNs: 1_000,
Scale: 1.0,
}
traceID := obsotlp.DeterministicTraceID("example-iket-otlp")
parentID := obsotlp.DeterministicSpanID("example-iket-otlp", "kernel")
spans, summaries, err := iket.TraceToOTLPSpans(traceID, parentID, tr, cal, nil)
if err != nil {
panic(err)
}
fmt.Printf("stage=%s dur_ns=%d p50_ns=%d unresolved=%v\n",
spans[0].Name, spans[0].End-spans[0].Start, summaries[0].P50DurNs, spans[0].Attrs["unresolved"])
}
Output: stage=decode_attention dur_ns=1600 p50_ns=1600 unresolved=false
func Uint64Payload ¶
func Uint64Payload(p0 uint64) re_ikettrace.Payload
func ValidateHostClockRateControl ¶
func ValidateHostClockRateControl(p0 re_ikettrace.HostClockRateControl) error
func ValidateKnownDurationControl ¶
func ValidateKnownDurationControl(p0 re_ikettrace.KnownDurationControl) error
func ValidateKnownDurations ¶
func ValidateKnownDurations(p0 []re_ikettrace.KnownDurationControl) error
func ValidateName ¶
func VerifyKnownDurationMutants ¶
func VerifyKnownDurationMutants(p0 []re_ikettrace.KnownDurationControl) (string, string, error)
func VerifyNegativeControlConstantTimestamp ¶
func VerifyNegativeControlConstantTimestamp(p0 []byte, p1 re_ikettrace.LaunchInfo, p2, p3, p4, p5, p6 uint64) (re_ikettrace.NegativeControlResult, error)
func VerifySharedDeviceTimerRateMutant ¶
func VerifySharedDeviceTimerRateMutant(p0 []re_ikettrace.HostClockRateControl) (bool, string, error)
func WriteBundle ¶
WriteBundle writes b to w as a standard TAR archive. The same payload, entry count and name limits as ReadBundle are checked before writing any bytes.
func WritePerfettoFlowJSON ¶
func WritePerfettoFlowJSON(p0 io.Writer, p1 *re_ikettrace.Trace, p2 *re_ikettrace.DAG) error
func WriteSpanTrace ¶
func WriteTrace ¶
func WriteTrace(p0 io.Writer, p1 *re_ikettrace.Trace) error
Types ¶
type ABBASpanBlock ¶
type ABBASpanBlock = re_ikettrace.ABBASpanBlock
type ABBAStep ¶
type ABBAStep = re_ikettrace.ABBAStep
type Budgets ¶
type Budgets struct {
// Measured targets (sampled):
CPUWindow time.Duration `json:"cpu_window"` // Sampling window for host CPU measurement (e.g. 1s)
MaxCPUPercent float64 `json:"max_cpu_percent"` // Target maximum CPU percent (e.g. 10.0%)
MaxRSSBytes uint64 `json:"max_rss_bytes"` // Target maximum host RSS in bytes
// Enforceable hard limits:
MaxRingRecords int `json:"max_ring_records"` // Upper bound on in-memory ring records
MaxRetainedBytes int64 `json:"max_retained_bytes"` // Per-bundle byte limit; not aggregate storage retention
MaxCaptureDuration time.Duration `json:"max_capture_duration"` // Context timeout; providers and writers must honor cancellation
MaxConcurrentCaptures int `json:"max_concurrent_captures"` // Max active captures across all tenants
MaxTenantConcurrency int `json:"max_tenant_concurrency"` // Max active captures for a single tenant
MaxTenantCapturesPerHour int `json:"max_tenant_captures_per_hour"` // Rate limit per tenant per hour
// Temporal limits & hysteresis:
CooldownDuration time.Duration `json:"cooldown_duration"` // Minimum cooldown duration after capture
HysteresisCount int `json:"hysteresis_count"` // Required consecutive trigger events before escalating
HysteresisWindow time.Duration `json:"hysteresis_window"` // Time window for consecutive trigger events
MaxRetainedReceipts int `json:"max_retained_receipts"` // Bounded ring capacity for incident receipts
}
Budgets defines both enforceable hard limits and measured targets for continuous flight recording and incident escalation.
Ring capacity, per-bundle byte count, and capture concurrency are enforced. Capture duration uses context cancellation; providers and writers must cooperate.
Measured targets (such as CPU percent and RSS bytes) are evaluated periodically via sampled checks over an explicit measurement window. They represent measured target bounds rather than instantaneous hard caps.
func DefaultBudgets ¶
func DefaultBudgets() Budgets
DefaultBudgets returns conservative initial limits for snapshot capture.
func QualificationBudgets ¶
func QualificationBudgets() Budgets
QualificationBudgets returns the frozen qualification budgets.
type BufferWriterFactory ¶
type BufferWriterFactory struct {
Buffers map[string]*bytes.Buffer
// contains filtered or unexported fields
}
BufferWriterFactory retains up to 100 incident bundles in memory. Each bundle is independently byte-limited by the coordinator; this factory does not enforce an aggregate byte limit. Access Buffers only after Trigger returns.
func NewBufferWriterFactory ¶
func NewBufferWriterFactory() *BufferWriterFactory
NewBufferWriterFactory creates an in-memory writer factory.
func (*BufferWriterFactory) CreateWriter ¶
func (b *BufferWriterFactory) CreateWriter(incidentID string, tenantID string) (io.Writer, func() error, error)
CreateWriter allocates an in-memory buffer.
type Bundle ¶
type Bundle struct {
Manifest Manifest
SystemInfo *SystemInfo
Files map[string][]byte
}
Bundle represents a multi-modal flight recorder archive containing the diagnostic manifest and raw binary artifacts (such as gpu.pprof, go.trace, kernels.ptx, kernels.sass).
func ReadBundle ¶
ReadBundle reads a diagnostic TAR bundle from r. It accepts at most 1024 regular entries and 256 MiB of payload, matching the default snapshot budget. Duplicate entries, links, and unsafe names are refused; no files are extracted.
func (*Bundle) DecodeFaultEvidence ¶
func (b *Bundle) DecodeFaultEvidence() (FaultInfo, NegativeRewriteConstraint, error)
DecodeFaultEvidence extracts and validates the versioned fault.json and negative_rules.json replay/quarantine artifacts from b, requiring an exact matching module digest, offending kernel and optional exact association. A legacy module-only result remains facts, not an exact search quarantine.
func (*Bundle) ExportGPUVisTimeline ¶
ExportGPUVisTimeline writes the timeline from b to w. If b.Files contains "gpuvis_timeline.json" or "timeline.gpuvis.json", it writes those bytes directly. If it contains "flight_ring.json", it decodes the snapshot and exports the timeline.
func (*Bundle) FlightRingSnapshot ¶
func (b *Bundle) FlightRingSnapshot() (*FlightRingSnapshot, error)
FlightRingSnapshot decodes and returns the FlightRingSnapshot stored in b.Files["flight_ring.json"] or parsed from "flight_ring.bin".
func (*Bundle) GPUVisTimeline ¶
func (b *Bundle) GPUVisTimeline() (*GPUVisTimeline, error)
GPUVisTimeline decodes and returns the GPUVisTimeline from b.
func (*Bundle) Reproducer ¶
func (b *Bundle) Reproducer() (*Reproducer, error)
Reproducer returns the bundle's validated reproducer manifest entry. For KVPages it also checks the named KV entry against the recorded KV hash.
Example ¶
package main
import (
"bytes"
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"log"
"strings"
)
func main() {
kv := []byte("kv pages read by the step")
r := &iket.Reproducer{
Version: iket.ReproducerVersion,
Rows: []iket.ReproducerRow{
{Kind: iket.RowDecode, Seq: 1, Pos: 9, SeqLen: 10, Tokens: []int32{42}},
},
KVSource: iket.KVPages,
KVFile: "reproducer/kv.bin",
KVHash: iket.KVDigest(kv),
GraphKey: 1,
Kernels: []iket.ReproducerKernel{{Name: "serve_decode", ModuleHash: strings.Repeat("ab", 32)}},
WeightsHash: strings.Repeat("cd", 32),
DType: "fp8",
StepTimeNs: 3_000_000,
}
sum, err := r.Digest()
if err != nil {
log.Fatal(err)
}
r.InputHash = sum
b := iket.NewBundle(iket.Manifest{Reason: "tail", Reproducer: r})
b.Files[r.KVFile] = kv
var buf bytes.Buffer
if err := iket.WriteBundle(&buf, b); err != nil {
log.Fatal(err)
}
read, err := iket.ReadBundle(&buf)
if err != nil {
log.Fatal(err)
}
got, err := read.Reproducer()
if err != nil {
log.Fatal(err)
}
fmt.Println(len(got.Rows), "row,", got.StepTimeNs, "ns")
// A replay that rebuilt different KV pages must refuse the step.
err = got.CheckKV([]byte("other pages"))
fmt.Println(errors.Is(err, iket.ErrReproducerMismatch))
}
Output: 1 row, 3000000 ns true
type CUPTIActivityCapture ¶
type CUPTIActivityCapture struct {
// contains filtered or unexported fields
}
CUPTIActivityCapture starts and drains real CUPTI activity acquisition. It preserves cuptiactivity's version/layout admission checks. It collects activity for the current process, including other device ordinals, and does not attach to another process. Application work must already be running. Close does not synchronize that work; incomplete records are reported, never silently repaired. A capture with losses returns an error and retains its partial raw evidence. Do not copy a CUPTIActivityCapture after use.
func NewCUPTIActivityCapture ¶
func NewCUPTIActivityCapture(config CUPTIActivityCaptureConfig) (*CUPTIActivityCapture, error)
NewCUPTIActivityCapture validates the ownership and memory contract. Native capability and record-layout admission happen during Capture before collection.
Example ¶
package main
import (
"fmt"
"time"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
"github.com/tmc/lib/nvidia/x/obs/iket"
)
func main() {
// Set ExclusiveOwnership only when the application controls CUPTI activity
// registration and enable/disable APIs, including other profiling libraries.
provider, err := iket.NewCUPTIActivityCapture(iket.CUPTIActivityCaptureConfig{
Activities: cuptix.ActivityConfig{
Kinds: []cupti.ActivityKind{cupti.ActivityKindConcurrentKernel},
BufferBytes: 64 << 10, MaxBuffers: 4, MaxRecords: 1024,
},
CollectionWindow: 100 * time.Millisecond,
ExclusiveOwnership: true,
})
// Construction validates configuration; Trigger performs native admission.
fmt.Println(provider != nil, err)
}
Output: true <nil>
func (*CUPTIActivityCapture) Capture ¶
func (p *CUPTIActivityCapture) Capture(ctx context.Context, rec *Recorder, req TriggerRequest, releaseLease func()) (report CaptureReport, captureErr error)
Capture starts acquisition, waits a bounded window, drains the owned session, and attaches raw records and loss status as incident-activity.json. Host clock calibration is inherited from Recorder; unknown alignment remains unknown. On cleanup failure, call Close explicitly to retry cleanup and release the retained cooperating device lease. There is no automatic cleanup retry.
func (*CUPTIActivityCapture) Close ¶
func (p *CUPTIActivityCapture) Close() error
Close retries only cleanup retained after a failed Capture. It releases the cooperating device lease when native cleanup succeeds and is otherwise safe to call repeatedly. Callers explicitly decide whether a cleanup retry is safe.
type CUPTIActivityCaptureConfig ¶
type CUPTIActivityCaptureConfig struct {
Activities cuptix.ActivityConfig
CollectionWindow time.Duration
ExclusiveOwnership bool
}
CUPTIActivityCaptureConfig bounds a process-wide activity session. ExclusiveOwnership acknowledges that the application owns activity callback registration and enable/disable APIs, including other profiling libraries. Device leases coordinate cooperating collectors only; they cannot establish this process-wide ownership. CollectionWindow must leave time for draining and snapshot serialization within the coordinator's MaxCaptureDuration.
type CUPTINegotiator ¶
type CUPTINegotiator interface {
CheckCompatibility(ctx context.Context, device uint32) error
AcquireLease(ctx context.Context, device uint32, ownerID string) (release func(), err error)
}
CUPTINegotiator negotiates CUPTI compatibility and device ownership without session theft.
type CalibrationConfig ¶
type CalibrationConfig = re_ikettrace.CalibrationConfig
type CandidateAssociation ¶
type CandidateAssociation struct {
Version int `json:"version"`
Kind string `json:"kind"`
IdentityProvenance string `json:"identity_provenance"`
ExecutableID string `json:"executable_id"`
WorkloadKey string `json:"workload_key"`
InputKey string `json:"input_key"`
Generation int `json:"generation"`
VerificationKey string `json:"verification_key"`
}
CandidateAssociation binds one evaluator-observed comparison failure to an exact search invocation. It is not native fault attribution: executable, workload, input and reference identities are asserted by their callers. Version 1 is the only supported association version. Legacy fault schema 1 records without this additive field remain readable as module facts only. Older strict readers refuse the additive field; no native-fault identity is inferred during migration.
func (CandidateAssociation) Validate ¶
func (a CandidateAssociation) Validate() error
Validate checks the association's version, provenance kind and bounded exact identities. Digests identify caller assertions, not authenticated evidence.
type CaptureReport ¶
type CaptureReport struct {
Provider string `json:"provider"`
Started bool `json:"started"`
Closed bool `json:"closed"`
RetainedOwnership bool `json:"retained_ownership"`
Duration time.Duration `json:"duration"`
Records int `json:"records"`
PendingBuffers int `json:"pending_buffers"`
RefusedBuffers uint64 `json:"refused_buffers"`
IncompleteRecords uint64 `json:"incomplete_records"`
DiscardedRecords uint64 `json:"discarded_records"`
DroppedRecords uint64 `json:"dropped_records"`
CallbackErrors uint64 `json:"callback_errors"`
Error string `json:"error,omitempty"`
}
CaptureReport describes acquisition separately from snapshot serialization. Started means native startup succeeded, not that complete GPU work was seen.
type CaptureWriterFactory ¶
type CaptureWriterFactory interface {
CreateWriter(incidentID string, tenantID string) (io.Writer, func() error, error)
}
CaptureWriterFactory creates an io.Writer for an incident capture bundle.
type CausalStepStitch ¶
type CausalStepStitch = re_ikettrace.CausalStepStitch
type ClockCalibration ¶
type ClockCalibration = re_ikettrace.ClockCalibration
type ClockSample ¶
type ClockSample = re_ikettrace.ClockSample
type ClockSession ¶
type ClockSession = re_ikettrace.ClockSession
type ClockTimeline ¶
type ClockTimeline = re_ikettrace.ClockTimeline
type ClusterCoord ¶
type ClusterCoord = re_ikettrace.ClusterCoord
type Config ¶
type Config = re_ikettrace.Config
type CriticalPathNode ¶
type CriticalPathNode = re_ikettrace.CriticalPathNode
type CriticalPathReport ¶
type CriticalPathReport = re_ikettrace.CriticalPathReport
type CrossSMConsistencyReport ¶
type CrossSMConsistencyReport = re_ikettrace.CrossSMConsistencyReport
type CrossSMSampleEntry ¶
type CrossSMSampleEntry = re_ikettrace.CrossSMSampleEntry
type DAG ¶
type DAG = re_ikettrace.DAG
type DAGCheckOptions ¶
type DAGCheckOptions = re_ikettrace.DAGCheckOptions
type DAGEdge ¶
type DAGEdge = re_ikettrace.DAGEdge
type DAGEdgeSummary ¶
type DAGEdgeSummary = re_ikettrace.DAGEdgeSummary
type DAGScope ¶
type DAGScope = re_ikettrace.DAGScope
type DAGViolation ¶
type DAGViolation = re_ikettrace.DAGViolation
type DAGViolationKind ¶
type DAGViolationKind = re_ikettrace.DAGViolationKind
type DecodedFlightRecord ¶
type DecodedFlightRecord struct {
Seq uint64 `json:"seq"`
Clock uint64 `json:"clock"`
TimestampNs int64 `json:"timestamp_ns"`
KernelID uint32 `json:"kernel_id"`
KernelName string `json:"kernel_name"`
SMID uint32 `json:"smid"`
CTAID uint32 `json:"ctaid"`
Flags uint32 `json:"flags"`
Kind string `json:"kind"`
}
DecodedFlightRecord is a host-decoded ikettrace.FlightRecord with resolved kernel name, nanosecond timestamp, and event kind.
type DecodedFlightSpan ¶
type DecodedFlightSpan struct {
KernelID uint32 `json:"kernel_id"`
KernelName string `json:"kernel_name"`
SMID uint32 `json:"smid"`
CTAID uint32 `json:"ctaid"`
EntryClock uint64 `json:"entry_clock"`
ExitClock uint64 `json:"exit_clock"`
DurationClocks uint64 `json:"duration_clocks"`
EntryNs int64 `json:"entry_ns"`
ExitNs int64 `json:"exit_ns"`
DurationNs uint64 `json:"duration_ns"`
EntrySeq uint64 `json:"entry_seq"`
ExitSeq uint64 `json:"exit_seq"`
}
DecodedFlightSpan pairs matching entry and exit DecodedFlightRecord events for the same (KernelID, SMID, CTAID) tuple.
type DefaultCUPTINegotiator ¶
type DefaultCUPTINegotiator struct{}
DefaultCUPTINegotiator coordinates device ownership via x/internal/cuptiowner.
func (DefaultCUPTINegotiator) AcquireLease ¶
func (DefaultCUPTINegotiator) AcquireLease(ctx context.Context, device uint32, ownerID string) (func(), error)
AcquireLease reserves the device ordinal for the capture duration.
func (DefaultCUPTINegotiator) CheckCompatibility ¶
func (DefaultCUPTINegotiator) CheckCompatibility(ctx context.Context, device uint32) error
CheckCompatibility verifies if device is available without holding the lease.
type Detector ¶
type Detector struct {
// contains filtered or unexported fields
}
Detector is a bounded, concurrency-safe baseline. Its zero value is unusable; use NewDetector. Observations must arrive in timestamp order.
func NewDetector ¶
func NewDetector(c DetectorConfig) (*Detector, error)
NewDetector validates and freezes a detector profile. Rolling state is limited to 4096 observations. Warmup is limited to 4096 in either mode.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"time"
)
func main() {
d, err := iket.NewDetector(iket.DetectorConfig{
Mode: "rolling", Window: 3, Warmup: 3, Delta: 5, MaxGap: time.Second,
})
if err != nil {
fmt.Println(err)
return
}
recorder, err := iket.New(iket.FlightConfig{Capacity: 10})
if err != nil {
fmt.Println(err)
return
}
coordinator, err := iket.NewEscalationCoordinator(recorder, iket.DefaultBudgets())
if err != nil {
fmt.Println(err)
return
}
defer coordinator.Stop()
for i, v := range []float64{10, 10, 10, 30} {
result := d.Observe(iket.DetectorObservation{
Metric: "latency", Unit: "ms", Epoch: "process-1", Clock: "mono-1",
Timestamp: int64(i), Value: v, Available: true,
})
if result.Anomaly {
// The existing coordinator independently decides capture admission.
request := iket.TriggerRequest{Reason: result.Reason,
MetricName: "latency", MetricValue: v, Threshold: result.Threshold}
fmt.Println(request.Reason, request.Threshold)
receipt, _ := coordinator.Trigger(context.Background(), request)
// No capture is admitted by this disarmed coordinator.
fmt.Println(receipt.Outcome, receipt.RefusalReason)
}
}
}
Output: high_anomaly 15 refused disarmed
func (*Detector) Observe ¶
func (d *Detector) Observe(o DetectorObservation) DetectorDecision
Observe evaluates against the preceding baseline, then incorporates the value. Missing, invalid or reset values erase the baseline. Identity/phase changes, clock reversal and expired gaps start a new warmup with the current value. High anomalies are included in future baselines; callers must account for this adaptation when selecting a profile and comparing static thresholds.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"time"
)
func main() {
d, _ := iket.NewDetector(iket.DetectorConfig{
Mode: "ewma", Alpha: .25, Warmup: 3, Delta: 5, MaxGap: time.Second,
})
result := d.Observe(iket.DetectorObservation{Available: false})
fmt.Println(result.Ready, result.Reason)
}
Output: false missing
type DetectorConfig ¶
type DetectorConfig struct {
Mode string
Window int
Alpha float64
Warmup int
Delta float64
MaxGap time.Duration
}
DetectorConfig freezes a high-side anomaly profile. Mode is "rolling" or "ewma". Rolling retains Window observations; EWMA uses Alpha in (0, 1]. Warmup observations precede decisions. Delta is an absolute increase in the observation's unit. MaxGap bounds the interval between observations. Neither mode adjusts for seasonality or establishes a causal diagnosis.
type DetectorDecision ¶
type DetectorDecision struct {
Ready, Anomaly bool
Reason string
Samples int
Baseline, Threshold float64
}
DetectorDecision separates anomaly evidence from capture admission. Baseline and Threshold describe state before this observation. Samples is the rolling population or the EWMA valid observation count, saturated at 4096. Ready only means the detector completed warmup.
type DetectorObservation ¶
type DetectorObservation struct {
Metric, Unit, Epoch, Phase, Clock string
Timestamp int64
Value float64
Available, CounterReset bool
}
DetectorObservation is one comparable gauge/window value. Epoch identifies the process/model/instrument generation; Phase and Clock identify compatible workload and monotonic clock domains. Missing values are not healthy samples. CounterReset invalidates state; cumulative counters must be converted into comparable windows before observation.
type DeviceRing ¶
type DeviceRing struct {
// contains filtered or unexported fields
}
DeviceRing maintains a bounded rolling window of CUPTI activity records, CUPTI PM counter samples, and IKET live-consumer events in memory, and writes a lookback bundle when a step latency trigger fires.
func NewDeviceRing ¶
func NewDeviceRing(rec *Recorder, cfg DeviceRingConfig) (*DeviceRing, error)
NewDeviceRing creates a bounded rolling DeviceRing and attaches it to rec.
func (*DeviceRing) Lookback ¶
func (d *DeviceRing) Lookback(triggerNs int64, reason string) (*DeviceRingLookback, error)
Lookback extracts the current rolling lookback window [triggerNs - Window, triggerNs] after evicting older entries.
func (*DeviceRing) ObserveStep ¶
func (d *DeviceRing) ObserveStep( ctx context.Context, w io.Writer, step int, name string, startNs, endNs int64, ) (*Manifest, *DeviceRingLookback, error)
ObserveStep records the step [startNs, endNs], drains configured device pollers, and when the step duration exceeds StepLatencyThreshold writes a TAR snapshot bundle containing device_ring.json to w. When the step does not exceed the threshold, ObserveStep returns (nil, nil, nil) without writing to w.
func (*DeviceRing) Poll ¶
func (d *DeviceRing) Poll() error
Poll invokes any configured ActivityPoller, PMPoller, and IKETConsumer once, pushing drained observations into the rolling ring.
func (*DeviceRing) PollIKET ¶
func (d *DeviceRing) PollIKET(refTimestampNs int64) (int, error)
PollIKET polls the configured iket.LiveConsumer against IKETBuffer and pushes newly sealed ranges, markers, and warp lifetimes into the rolling ring.
func (*DeviceRing) PushActivity ¶
func (d *DeviceRing) PushActivity(a cuptix.ActivityRecord)
PushActivity appends a CUPTI activity record to the rolling ring and evicts entries outside the configured lookback window or capacity bound.
func (*DeviceRing) PushIKETEvent ¶
func (d *DeviceRing) PushIKETEvent(ev DeviceRingIKETEvent)
PushIKETEvent appends a decoded IKET event to the rolling ring and evicts entries outside the configured lookback window or capacity bound.
func (*DeviceRing) PushPMSample ¶
func (d *DeviceRing) PushPMSample(sample cuptix.PMSample)
PushPMSample appends a CUPTI PM counter sample to the rolling ring and evicts entries outside the configured lookback window or capacity bound.
func (*DeviceRing) RecordStep ¶
func (d *DeviceRing) RecordStep(step int, name string, startNs, endNs int64) bool
RecordStep records one execution step in the rolling ring, evicts records older than endNs - Window, and reports whether the step duration exceeded StepLatencyThreshold.
func (*DeviceRing) Start ¶
func (d *DeviceRing) Start() error
Start begins rolling device-ring collection and starts the optional background poller if PollInterval > 0.
func (*DeviceRing) Stop ¶
func (d *DeviceRing) Stop() error
Stop halts background polling on the device ring.
type DeviceRingConfig ¶
type DeviceRingConfig struct {
// Window is the rolling lookback duration to retain in memory (defaults to Recorder's Window or DefaultWindow).
Window time.Duration
// MaxActivityRecords bounds retained cuptiactivity.Record items (default 65536).
MaxActivityRecords int
// MaxPMSamples bounds retained cuptipmsampling.Sample items (default 16384).
MaxPMSamples int
// MaxIKETEvents bounds retained DeviceRingIKETEvent items (default 65536).
MaxIKETEvents int
// MaxSteps bounds retained DeviceRingStep items (default 16384).
MaxSteps int
// StepLatencyThreshold triggers a lookback snapshot in ObserveStep when a
// step's duration (endNs - startNs) strictly exceeds this threshold.
StepLatencyThreshold time.Duration
// PollInterval, when positive, starts a background goroutine on Start() that
// drains ActivityPoller, PMPoller, and IKETConsumer at this period.
PollInterval time.Duration
// ActivityPoller optionally drains newly completed CUPTI activity records.
ActivityPoller func() ([]cuptix.ActivityRecord, error)
// PMPoller optionally drains newly decoded CUPTI PM counter samples.
PMPoller func() ([]cuptix.PMSample, error)
// IKETConsumer and IKETBuffer optionally supply a live IKET consumer and its
// backing buffer to poll via IKETConsumer.Poll(IKETBuffer).
IKETConsumer *LiveConsumer
IKETBuffer []byte
// ProcRoot overrides "/proc" when scanning loaded CUDA shared libraries.
ProcRoot string
// RequireNonEmpty fails Lookback and ObserveStep with ErrEmptyDeviceRing
// when steps were recorded in the window but all three device streams
// (Activities, PMSamples, IKETEvents) are empty.
RequireNonEmpty bool
}
DeviceRingConfig configures a bounded rolling device ring attached to a Recorder.
type DeviceRingIKETEvent ¶
type DeviceRingIKETEvent struct {
TimestampNs int64 `json:"timestamp_ns"`
StartTs uint64 `json:"start_ts"`
EndTs uint64 `json:"end_ts"`
DurationNs uint64 `json:"duration_ns"`
Name string `json:"name"`
Kind string `json:"kind"`
Range *Range `json:"range,omitempty"`
Marker *Marker `json:"marker,omitempty"`
WarpLifetime *WarpLifetime `json:"warp_lifetime,omitempty"`
}
DeviceRingIKETEvent records one decoded IKET range, marker, or warp lifetime in the rolling ring.
type DeviceRingLookback ¶
type DeviceRingLookback struct {
TriggerReason string `json:"trigger_reason"`
TriggerTimestampNs int64 `json:"trigger_timestamp_ns"`
WindowNs int64 `json:"window_ns"`
CutoffTimestampNs int64 `json:"cutoff_timestamp_ns"`
Steps []DeviceRingStep `json:"steps"`
Activities []cuptix.ActivityRecord `json:"activities"`
PMSamples []cuptix.PMSample `json:"pm_samples"`
IKETEvents []DeviceRingIKETEvent `json:"iket_events"`
LoadedLibraries []string `json:"loaded_libraries,omitempty"`
EvictedSteps uint64 `json:"evicted_steps"`
EvictedActivities uint64 `json:"evicted_activities"`
EvictedPMSamples uint64 `json:"evicted_pm_samples"`
EvictedIKETEvents uint64 `json:"evicted_iket_events"`
PollErrors uint64 `json:"poll_errors,omitempty"`
}
DeviceRingLookback holds the rolling lookback window written to device_ring.json on a snapshot.
func DecodeDeviceRingLookback ¶
func DecodeDeviceRingLookback(b *Bundle) (*DeviceRingLookback, error)
DecodeDeviceRingLookback extracts and validates device_ring.json from b.
func (*DeviceRingLookback) Validate ¶
func (lb *DeviceRingLookback) Validate() error
Validate checks structural and timestamp invariants on a decoded DeviceRingLookback.
type DeviceRingStep ¶
type DeviceRingStep struct {
Step int `json:"step"`
Name string `json:"name,omitempty"`
StartNs int64 `json:"start_ns"`
EndNs int64 `json:"end_ns"`
DurationNs uint64 `json:"duration_ns"`
Triggered bool `json:"triggered,omitempty"`
}
DeviceRingStep records one execution step's timing and trigger status in the rolling ring.
type DeviceTimerResolution ¶
type DeviceTimerResolution = re_ikettrace.DeviceTimerResolution
type DirectoryWriterFactory ¶
type DirectoryWriterFactory struct {
// contains filtered or unexported fields
}
DirectoryWriterFactory writes incident bundles to files in a directory.
func NewDirectoryWriterFactory ¶
func NewDirectoryWriterFactory(dir string) *DirectoryWriterFactory
NewDirectoryWriterFactory creates a factory writing to dir.
func (*DirectoryWriterFactory) CreateWriter ¶
func (d *DirectoryWriterFactory) CreateWriter(incidentID string, tenantID string) (io.Writer, func() error, error)
CreateWriter creates a new tar file in the configured directory. An existing path, including a symlink, is refused without changing the retained bundle.
type DropError ¶
type DropError = re_ikettrace.DropError
type EnabledClusterRule ¶
type EnabledClusterRule = re_ikettrace.EnabledClusterRule
type EscalationCoordinator ¶
type EscalationCoordinator struct {
// contains filtered or unexported fields
}
EscalationCoordinator creates bounded snapshots of an existing Recorder. It does not start native acquisition or change its fidelity. Snapshot storage retention and deletion are the writer factory owner's responsibility.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"log"
"time"
)
func main() {
rec, err := iket.New(iket.FlightConfig{
Window: 5 * time.Second,
Capacity: 100,
})
if err != nil {
log.Fatal(err)
}
if err := rec.Start(); err != nil {
log.Fatal(err)
}
defer rec.Stop()
budgets := iket.QualificationBudgets()
budgets.HysteresisCount = 1
coord, err := iket.NewEscalationCoordinator(rec, budgets, iket.WithResourceSampler(&iket.FakeResourceSampler{}))
if err != nil {
log.Fatal(err)
}
if err := coord.Arm(); err != nil {
log.Fatal(err)
}
defer coord.Stop()
receipt, err := coord.Trigger(context.Background(), iket.TriggerRequest{
TenantID: "prod-tenant",
Reason: "latency_regression",
MetricName: "gpu_latency_ms",
MetricValue: 125.0,
Threshold: 100.0,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Incident outcome: %s (state: %s)\n", receipt.Outcome, receipt.State)
}
Output: Incident outcome: captured (state: cooldown)
func NewEscalationCoordinator ¶
func NewEscalationCoordinator(rec *Recorder, budgets Budgets, opts ...EscalationOption) (*EscalationCoordinator, error)
NewEscalationCoordinator creates a new coordinator wrapping recorder.
func (*EscalationCoordinator) Arm ¶
func (ec *EscalationCoordinator) Arm() error
Arm moves the coordinator into StateArmed. It does not clear a pending cooldown: State reports StateCooldown until that cooldown elapses.
func (*EscalationCoordinator) Close ¶
func (ec *EscalationCoordinator) Close() error
Close implements io.Closer.
func (*EscalationCoordinator) CooldownRemaining ¶
func (ec *EscalationCoordinator) CooldownRemaining() time.Duration
CooldownRemaining returns the remaining incident cooldown, or zero when State is not StateCooldown.
func (*EscalationCoordinator) Disarm ¶
func (ec *EscalationCoordinator) Disarm() error
Disarm transitions the coordinator from StateArmed to StateIdle.
func (*EscalationCoordinator) History ¶
func (ec *EscalationCoordinator) History() []IncidentReceipt
History returns a copy of retained incident receipts.
func (*EscalationCoordinator) State ¶
func (ec *EscalationCoordinator) State() State
State reports the current state machine state as seen by incident triggers: StateCooldown exactly while CooldownRemaining is positive. A healthy baseline capture's cooldown does not appear here.
func (*EscalationCoordinator) Stop ¶
func (ec *EscalationCoordinator) Stop() error
Stop permanently disarms the coordinator, cancels active capture contexts, and closes asynchronous admission. It is idempotent and does not wait for provider cleanup. Wait drains asynchronous completion; retained native cleanup remains the IncidentCapture provider owner's responsibility.
func (*EscalationCoordinator) Trigger ¶
func (ec *EscalationCoordinator) Trigger(ctx context.Context, req TriggerRequest) (*IncidentReceipt, error)
Trigger evaluates an incident escalation request against declared budgets and state. If admitted, it snapshots the recorder, enforces byte and concurrency limits, and records the receipt. It does not start a new acquisition session. If refused, it records the refusal reason and trigger evidence, returning ErrEscalationRefused.
func (*EscalationCoordinator) TriggerAsync ¶
func (ec *EscalationCoordinator) TriggerAsync(ctx context.Context, req TriggerRequest) (<-chan EscalationResult, error)
TriggerAsync submits a trigger without waiting for resource sampling, native acquisition, or snapshot export. At most Recorder.Config.MaxQueuedJobs requests are pending, in addition to one executing request. Queue admission does not imply capture admission: the worker evaluates the normal Trigger budgets. Request details are copied; the caller must not mutate them during submission. Each accepted request receives exactly one buffered result and a closed channel, even when stopped or canceled. The receiver need not consume it for progress. Call Stop and Wait when finished to release the lazily started worker.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
)
func main() {
recorder, err := iket.New(iket.FlightConfig{Capacity: 100, MaxQueuedJobs: 2})
if err != nil {
fmt.Println(err)
return
}
coordinator, err := iket.NewEscalationCoordinator(recorder, iket.QualificationBudgets())
if err != nil {
fmt.Println(err)
return
}
result, err := coordinator.TriggerAsync(context.Background(), iket.TriggerRequest{Reason: "latency"})
if err != nil {
fmt.Println(err)
return
}
// Queue admission succeeds, but this coordinator has not been armed.
completion := <-result
fmt.Println(completion.Receipt.Outcome, completion.Receipt.RefusalReason)
coordinator.Stop()
fmt.Println(coordinator.Wait(context.Background()))
}
Output: refused disarmed <nil>
func (*EscalationCoordinator) Wait ¶
func (ec *EscalationCoordinator) Wait(ctx context.Context) error
Wait waits for all accepted asynchronous jobs to finish after Stop. It does not retry retained native cleanup or wait for separately invoked synchronous Trigger calls. Providers and writers must cooperate with context cancellation. The caller may time out without preventing later worker completion.
type EscalationOption ¶
type EscalationOption func(*EscalationCoordinator)
EscalationOption configures an EscalationCoordinator.
func WithCUPTINegotiator ¶
func WithCUPTINegotiator(n CUPTINegotiator) EscalationOption
WithCUPTINegotiator sets a custom CUPTINegotiator.
func WithCaptureWriterFactory ¶
func WithCaptureWriterFactory(f CaptureWriterFactory) EscalationOption
WithCaptureWriterFactory sets a custom CaptureWriterFactory.
func WithIncidentCapture ¶
func WithIncidentCapture(provider IncidentCapture) EscalationOption
WithIncidentCapture configures additional acquisition. Without this option, Trigger only snapshots observations already in the recorder.
func WithResourceSampler ¶
func WithResourceSampler(s ResourceSampler) EscalationOption
WithResourceSampler sets a custom ResourceSampler.
type EscalationResult ¶
type EscalationResult struct {
Receipt *IncidentReceipt
Err error
}
EscalationResult is the terminal result of one asynchronously submitted trigger. A failed capture may have both a receipt and an error.
type Event ¶
type Event = re_ikettrace.Event
type EventPos ¶
type EventPos = re_ikettrace.EventPos
type FakeCUPTINegotiator ¶
type FakeCUPTINegotiator struct {
// contains filtered or unexported fields
}
FakeCUPTINegotiator allows simulating conflicting owners and compatibility errors.
func (*FakeCUPTINegotiator) AcquireLease ¶
func (f *FakeCUPTINegotiator) AcquireLease(ctx context.Context, device uint32, ownerID string) (func(), error)
AcquireLease acquires a mock lease.
func (*FakeCUPTINegotiator) CheckCompatibility ¶
func (f *FakeCUPTINegotiator) CheckCompatibility(ctx context.Context, device uint32) error
CheckCompatibility checks configured conflict status.
func (*FakeCUPTINegotiator) SetConflict ¶
func (f *FakeCUPTINegotiator) SetConflict(conflict bool, err error)
SetConflict sets whether compatibility check should indicate a conflict.
type FakeClock ¶
type FakeClock struct {
// contains filtered or unexported fields
}
FakeClock is a thread-safe injected clock for testing.
func NewFakeClock ¶
NewFakeClock creates a FakeClock anchored at start.
func (*FakeClock) NowMonotonic ¶
NowMonotonic returns current simulated monotonic nanoseconds.
type FakeResourceSampler ¶
type FakeResourceSampler struct {
CPUPercent float64
RSSBytes uint64
Err error
// contains filtered or unexported fields
}
FakeResourceSampler provides scripted resource measurements for testing.
func (*FakeResourceSampler) SampleUsage ¶
SampleUsage returns the configured values.
type FaultInfo ¶
type FaultInfo struct {
Candidate *CandidateAssociation `json:"candidate_association,omitempty"`
SchemaVersion int `json:"schema_version"`
TimestampNs int64 `json:"timestamp_ns"`
ErrorCode int `json:"error_code"`
ErrorName string `json:"error_name"`
ErrorMessage string `json:"error_message"`
OffendingKernel string `json:"offending_kernel,omitempty"`
CorrelationID uint64 `json:"correlation_id,omitempty"`
ModuleID string `json:"module_id,omitempty"`
ModuleDigest string `json:"module_digest,omitempty"`
ModuleGeneration uint64 `json:"module_generation,omitempty"`
FailedRuleNames []string `json:"failed_rule_names,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
}
FaultInfo describes a GPU fault or abort event for zero-device crash dump generation.
func DecodeFaultInfo ¶
DecodeFaultInfo decodes a versioned FaultInfo JSON payload and validates it for offline replay or hypothesis admission.
func (FaultInfo) MarshalJSON ¶
MarshalJSON encodes f with an explicit schema_version, defaulting zero SchemaVersion values to FaultInfoSchemaVersion and rejecting unknown versions.
func (*FaultInfo) UnmarshalJSON ¶
UnmarshalJSON decodes f and validates its wire schema_version.
type FlightCfg ¶
type FlightCfg = re_ikettrace.FlightConfig
type FlightClock ¶
Clock abstracts time for deterministic simulation in unit and acceptance tests.
type FlightConfig ¶
type FlightConfig struct {
Window time.Duration // Time window to retain in memory (default 10s)
Capacity int // Maximum number of GPU records in ring buffer (default 65536)
ClockUncertaintyNs int64 // Estimated host-to-device clock alignment error (nanoseconds)
GoTraceEnabled bool // Whether to capture Go execution trace in snapshots (go.trace)
GoTraceWindow time.Duration // Time window for Go execution trace (default: matches Window)
GoTraceMaxBytes uint64 // Upper bound on in-memory Go execution trace size in bytes (0 = runtime default)
GoTraceStandard bool // If true, use standard trace.Start/Stop adapter instead of trace.FlightRecorder
GoTracer GoTraceRecorder // Optional custom Go execution trace flight recorder
RecordGPUPprof bool // Whether to capture GPU pprof profile in snapshots (gpu.pprof)
RecordPerfetto bool // Whether to capture Perfetto timeline in snapshots (timeline.pftrace)
MaxProviderOutputBytes int64 // Max bytes allowed per provider output (default: 64 MiB)
MaxSnapshotBytes int64 // Max retained file payload bytes; manifest/TAR framing have a separate global limit (default: 256 MiB)
MaxQueuedJobs int // Max pending async snapshot jobs (default: 16)
SystemInfo *SystemInfo // Optional canonical system/device/library provenance record
}
Config configures in-memory flight recording.
type FlightLayout ¶
type FlightLayout uint8
A FlightLayout names the byte layout of a flight ring buffer. The decoder never infers it: the caller says which writer produced the ring.
const ( // FlightLayoutHost is the layout [ikettrace.FlightRing.Append] and // [ikettrace.FlightRing.Encode] write: a validated header, and records // that carry their own Seq and wrap at Capacity. FlightLayoutHost FlightLayout = iota // FlightLayoutCaveV0 is the layout the sm_121a flight cave writes // (cudasass.AssembleFlightCave). The device reads Capacity, a uint32 at // header offset 16, increments the uint32 at offset 8 (the low half of // WriteIdx) once per event, and writes no other header field. Event idx // goes to the slot at 64 + 32*idx, of which the cave stores only: // // +0 uint32 SR_CLOCKLO // +12 uint32 0 for entry, 1 for exit // +20 uint32 SR_CTAID.X // // Once idx reaches Capacity it stores nothing, so the ring holds the // first Capacity events and never wraps. The records carry no Seq and no // kernel, SM or thread identity: the decoder numbers them by slot, and // pairs no spans. A slot an event has claimed but not yet stored, in a // snapshot taken while the kernel runs, reads as an entry at clock 0. FlightLayoutCaveV0 )
func (FlightLayout) MarshalText ¶
func (l FlightLayout) MarshalText() ([]byte, error)
MarshalText returns the layout's name.
func (FlightLayout) String ¶
func (l FlightLayout) String() string
func (*FlightLayout) UnmarshalText ¶
func (l *FlightLayout) UnmarshalText(text []byte) error
UnmarshalText sets l to the layout named by text.
type FlightRecord ¶
type FlightRecord = re_ikettrace.FlightRecord
type FlightRing ¶
type FlightRing = re_ikettrace.FlightRing
type FlightRingDecodeOptions ¶
type FlightRingDecodeOptions struct {
// Layout is the layout the ring was written in. The zero value is
// [FlightLayoutHost].
Layout FlightLayout
// KernelNames maps numeric KernelID values to symbol names. When a
// KernelID is absent, KernelName defaults to "kernel_<id>". A
// [FlightLayoutCaveV0] ring records no KernelID, so its records take
// the name of KernelID 0.
KernelNames map[uint32]string
// ClockToNs converts a device clock reading into host-calibrated
// nanoseconds. When nil, the raw clock value is cast to int64.
ClockToNs func(clock uint64) int64
}
FlightRingDecodeOptions configures how raw binary ikettrace.FlightRing buffers are decoded into FlightRingSnapshot values.
type FlightRingHeader ¶
type FlightRingHeader = re_ikettrace.FlightRingHeader
type FlightRingSnapshot ¶
type FlightRingSnapshot struct {
Layout FlightLayout `json:"layout,omitempty"`
Header ikettrace.FlightRingHeader `json:"header"`
Config ikettrace.FlightConfig `json:"config"`
Records []DecodedFlightRecord `json:"records"`
Spans []DecodedFlightSpan `json:"spans"`
Overwritten uint64 `json:"overwritten"`
Overflowed uint64 `json:"overflowed,omitempty"`
}
FlightRingSnapshot holds the decoded header, __iket_flight_cfg mirror, ordered slot records, and paired entry/exit spans from a binary flight ring.
Overwritten counts the records a host-layout ring wrapped over. A FlightLayoutCaveV0 ring never wraps; Overflowed counts the events its writer could not store because the ring was full, WriteIdx - Capacity.
func DecodeFlightRing ¶
func DecodeFlightRing(ring *ikettrace.FlightRing, opts FlightRingDecodeOptions) (*FlightRingSnapshot, error)
DecodeFlightRing converts an already-parsed host-layout ikettrace.FlightRing into a FlightRingSnapshot. Other layouts have no parsed form: decode them with DecodeFlightRingSnapshot.
func DecodeFlightRingSnapshot ¶
func DecodeFlightRingSnapshot(data []byte, opts FlightRingDecodeOptions) (*FlightRingSnapshot, error)
DecodeFlightRingSnapshot decodes a binary ikettrace.FlightRing buffer produced by device instrumentation or ikettrace.FlightRing.Encode into a FlightRingSnapshot.
func (*FlightRingSnapshot) ExportGPUVisTimeline ¶
func (s *FlightRingSnapshot) ExportGPUVisTimeline(w io.Writer) error
ExportGPUVisTimeline writes s formatted as a gpuvis timeline JSON document to w.
func (*FlightRingSnapshot) GPUVisTimeline ¶
func (s *FlightRingSnapshot) GPUVisTimeline() (*GPUVisTimeline, error)
GPUVisTimeline builds an in-memory GPUVisTimeline from decoded spans and records in s.
func (*FlightRingSnapshot) RecordsForRecorder ¶
func (s *FlightRingSnapshot) RecordsForRecorder() []Record
RecordsForRecorder converts s into Record entries suitable for pushing into a Recorder: one per paired span, in span order, followed by one zero-duration entry for each record no span consumes, in Seq order. Those are the entries of kernels that never exited, which a hung or crashed kernel leaves, exits whose entry was overwritten, and markers.
func (*FlightRingSnapshot) Truncation ¶
func (s *FlightRingSnapshot) Truncation() string
Truncation describes the events s does not hold, or returns "" if it holds them all.
type GPUVisEvent ¶
type GPUVisEvent struct {
Name string `json:"name"`
Cat string `json:"cat,omitempty"`
Ph string `json:"ph"` // "X" (complete span), "i" (instant marker), "M" (metadata)
Ts float64 `json:"ts"` // microsecond timestamp
Dur float64 `json:"dur,omitempty"`
Pid int `json:"pid"`
Tid int `json:"tid"`
Args map[string]any `json:"args,omitempty"`
Cname string `json:"cname,omitempty"`
}
GPUVisEvent models one span, instant marker, or metadata event in a gpuvis timeline JSON document.
type GPUVisTimeline ¶
type GPUVisTimeline struct {
Format string `json:"format"`
DisplayTimeUnit string `json:"displayTimeUnit"`
TraceEvents []GPUVisEvent `json:"traceEvents"`
OtherData map[string]string `json:"otherData,omitempty"`
}
GPUVisTimeline models the top-level gpuvis timeline JSON export document.
func DecodeGPUVisTimeline ¶
func DecodeGPUVisTimeline(r io.Reader) (*GPUVisTimeline, error)
DecodeGPUVisTimeline decodes and validates a GPUVisTimeline JSON stream from r.
type GlobalTimerResolutionSpec ¶
type GlobalTimerResolutionSpec = re_ikettrace.GlobalTimerResolutionSpec
type GoTraceRecorder ¶
type GoTraceRecorder interface {
// Start begins recording Go runtime execution events.
Start() error
// Stop halts recording Go runtime execution events. It halts recording
// even when it returns an error, such as a failure to retain the final
// window.
Stop() error
// Snapshot returns a copy of the recorded Go execution trace.
Snapshot(ctx context.Context) ([]byte, error)
}
GoTraceRecorder captures Go execution traces into an in-memory buffer.
func NewAdaptiveTraceRecorder ¶
func NewAdaptiveTraceRecorder(window time.Duration, maxBytes uint64) GoTraceRecorder
NewAdaptiveTraceRecorder creates a GoTraceRecorder that prefers runtime/trace.FlightRecorder and falls back to standard trace.Start/Stop.
func NewFlightRecorder ¶
func NewFlightRecorder(window time.Duration, maxBytes uint64) GoTraceRecorder
NewFlightRecorder returns a GoTraceRecorder backed by runtime/trace.FlightRecorder. The window parameter specifies the minimum event age to retain in the circular buffer. The maxBytes parameter specifies the maximum buffer size in bytes (0 for runtime default).
func NewStandardTraceAdapter ¶
func NewStandardTraceAdapter(maxBytes uint64) GoTraceRecorder
NewStandardTraceAdapter returns a GoTraceRecorder that uses trace.Start and trace.Stop. It serves as a clean fallback or adapter for tests and environments without FlightRecorder. If the byte cap discards data, Snapshot returns the retained bytes with an error reporting the loss. Stop and subsequent snapshots retain that error.
type GoTraceValidation ¶
type GoTraceValidation struct {
Outcome string // "decoded", "rejected", or "unavailable"
Status string // Outcome, a colon and the detail
Authority string // always GoTraceValidatorAuthority
Decoder string // validator's description, verbatim; empty unless decoded
InputSHA256 string // sha256 of the validated bytes; empty if none were read
InputBytes int64
}
GoTraceValidation reports one explicit validation of a bundle's go.trace.
func ValidateGoTrace ¶
func ValidateGoTrace(ctx context.Context, b *Bundle, v GoTraceValidator) (*GoTraceValidation, error)
ValidateGoTrace validates b.Files["go.trace"] with v. It never modifies b. The caller must not modify b during the call. Snapshot, FaultSnapshot, Handler and escalation never call it, and it changes no Manifest field.
The recorder's own placeholder and magic checks run first and report "rejected" without calling v. The error is nil only for the "decoded" outcome; a cancelled ctx yields "unavailable" even if v returned.
"decoded" means only that v accepted the bytes. It establishes neither completeness nor absence of loss: a decoder may accept a trace cut short, so the decoded Status always ends "completeness unknown".
Example ¶
b := NewBundle(Manifest{Reason: "example"})
b.Files["go.trace"] = []byte("go 1.26 trace\x00\x00\x00")
v := func(ctx context.Context, data []byte) (string, error) {
return "example decoder", nil
}
r, err := ValidateGoTrace(context.Background(), b, v)
fmt.Println(r.Outcome, err)
fmt.Println(r.Authority)
Output: decoded <nil> caller-selected validator assertion; not independent decoder authority; timing and population unvalidated
type GoTraceValidator ¶
A GoTraceValidator decodes a Go execution trace with a decoder chosen by the caller and returns a short description of that decoder. Its result is the caller's assertion, not independent decoder authority. To report malformed input it returns an error wrapping ErrArtifactInvalid; any other error means the outcome is unknown.
The validator receives a private copy of the trace bytes and must not modify it.
type HostClockRateControl ¶
type HostClockRateControl = re_ikettrace.HostClockRateControl
type HostDeviceGap ¶
type HostDeviceGap = re_ikettrace.HostDeviceGap
type HostInstant ¶
type HostInstant = re_ikettrace.HostInstant
type HostRateABBABlock ¶
type HostRateABBABlock = re_ikettrace.HostRateABBABlock
type HostResourceSampler ¶
HostResourceSampler measures process CPU and resident memory over Window. A zero Window selects one second. CPU is expressed as percent of one CPU.
func (HostResourceSampler) SampleUsage ¶
SampleUsage measures usage over a cancellable window. Unsupported platforms return an error rather than reporting invented zero-valued measurements.
type IKETIncident ¶
type IKETIncident struct {
Triggered bool
Reason string
Regions []RegionSummary
Edges []DAGEdgeSummary
Violations []DAGViolation
}
IKETIncident reports the sub-kernel region summaries, DAG edge checks, and escalation trigger status of an evaluated iket.Trace.
func EvaluateIKETIncident ¶
func EvaluateIKETIncident(trace *Trace, policy IKETTriggerPolicy) (*IKETIncident, error)
EvaluateIKETIncident summarizes the sub-kernel regions of trace and checks them against policy's optional compile-time iket.DAG and per-region P99 latency ceilings.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"log"
)
func main() {
tr := &iket.RingTrace{
Config: iket.RingConfig{Rings: 1, Capacity: 4},
Events: []iket.Event{
{Start: 1000, End: 1400, Block: 0, Warp: 0, ID: 1},
{Start: 1500, End: 2100, Block: 0, Warp: 0, ID: 2},
},
}
it, err := iket.FromSpanTrace(tr, "megakernel_iket", [3]int{1, 1, 1}, [3]int{64, 1, 1}, map[uint16]string{
1: "train_Forward",
2: "serve_DecodeAttention",
})
if err != nil {
log.Fatal(err)
}
dag, err := iket.NewDAG("megakernel_pipe")
if err != nil {
log.Fatal(err)
}
if err := dag.AddEdge("train_Forward", "serve_DecodeAttention", "w_bf16", "ld_volatile_bf16"); err != nil {
log.Fatal(err)
}
inc, err := iket.EvaluateIKETIncident(it, iket.IKETTriggerPolicy{
DAG: dag,
MaxRegionP99Ns: map[string]uint64{"serve_DecodeAttention": 500},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("triggered=%t reason=%s violations=%d\n", inc.Triggered, inc.Reason, len(inc.Violations))
}
Output: triggered=true reason=iket_p99_exceeded:serve_DecodeAttention violations=0
type IKETLiveConsumer ¶
type IKETLiveConsumer = re_ikettrace.IKETLiveConsumer
type IKETOverheadReport ¶
type IKETOverheadReport = re_ikettrace.IKETOverheadReport
type IKETOverheadSummary ¶
type IKETOverheadSummary = re_ikettrace.IKETOverheadSummary
type IKETTriggerPolicy ¶
IKETTriggerPolicy defines sub-kernel phase latency ceilings and optional compile-time iket.DAG ordering checks for flight-recorder escalation.
type IncidentCapture ¶
type IncidentCapture interface {
Capture(ctx context.Context, recorder *Recorder, request TriggerRequest, releaseLease func()) (CaptureReport, error)
}
IncidentCapture starts additional acquisition for an admitted incident. The coordinator has reserved its cooperating device lease before calling Capture. A provider retaining native cleanup ownership must retain releaseLease and report RetainedOwnership; it must release the lease only after cleanup succeeds. A provider must not synchronize or otherwise alter application GPU work.
type IncidentReceipt ¶
type IncidentReceipt struct {
IncidentID string `json:"incident_id"`
Timestamp time.Time `json:"timestamp"`
TenantID string `json:"tenant_id"`
State State `json:"state"`
Outcome string `json:"outcome"` // "captured", "refused", "failed"
RefusalReason string `json:"refusal_reason,omitempty"`
Trigger TriggerEvidence `json:"trigger"`
Budgets Budgets `json:"budgets"`
Perturbation PerturbationReport `json:"perturbation"`
Capture CaptureReport `json:"capture"`
Error string `json:"error,omitempty"`
}
IncidentReceipt is the comprehensive audit and diagnostic receipt of an incident escalation.
type InternalEvent ¶
type InternalEvent = re_ikettrace.InternalEvent
type KnownDurationControl ¶
type KnownDurationControl = re_ikettrace.KnownDurationControl
type KnownDurationTrial ¶
type KnownDurationTrial = re_ikettrace.KnownDurationTrial
type Launch ¶
type Launch = re_ikettrace.Launch
type LaunchInfo ¶
type LaunchInfo = re_ikettrace.LaunchInfo
type LibExt ¶
type LibExt = re_ikettrace.LibExt
type LiveConsumer ¶
type LiveConsumer = re_ikettrace.LiveConsumer
type LiveStreamConsumer ¶
type LiveStreamConsumer = re_ikettrace.LiveStreamConsumer
type LoadedModule ¶
type LoadedModule struct {
Handle ModuleHandle
InputSHA256 [32]byte
KernelNames []string
CfgAddr uint64
CfgSize uint64
Config cudasass.PatchConfig
}
LoadedModule describes a CUDA module loaded and tracked by a ModuleHook.
type Location ¶
type Location = re_ikettrace.Location
type Manifest ¶
type Manifest struct {
Timestamp time.Time `json:"timestamp"`
Reason string `json:"reason"`
WindowRequestedNs int64 `json:"window_requested_ns"`
GoSpanNs int64 `json:"go_span_ns"`
GPUSpanNs int64 `json:"gpu_span_ns"`
OverlapSpanNs int64 `json:"overlap_span_ns"`
GPURecords int `json:"gpu_records"`
GPUDropped int64 `json:"gpu_dropped"`
// GPUOutsideWindow counts retained records excluded by the snapshot cutoff.
GPUOutsideWindow int `json:"gpu_outside_window"`
GoTraceBytes int64 `json:"go_trace_bytes"`
// ClockUncertaintyNs is the alignment uncertainty in nanoseconds; -1 means unavailable.
ClockUncertaintyNs int64 `json:"clock_uncertainty_ns"`
// ClockUncertaintySource says where ClockUncertaintyNs came from.
// "estimated" follows a successful Recorder.CalibrateClock: half the
// host-clock bracket measured around a CUPTI clock read, plus drift
// since the read at an assumed 11 ppm. It is not a qualified bound on
// the physical alignment error; the true drift is not measured.
// "configured" is Config.ClockUncertaintyNs. "unavailable" means neither,
// and "host_only" marks a fault snapshot; both report -1.
ClockUncertaintySource string `json:"clock_uncertainty_source"`
OverlapReliable bool `json:"overlap_reliable"`
ProviderStatus map[string]string `json:"provider_status,omitempty"`
LossReasons []string `json:"loss_reasons,omitempty"`
SystemInfo *SystemInfo `json:"system_info,omitempty"`
// Reproducer, if set, lets the kept step run again standalone.
// Read it with Bundle.Reproducer, which validates it.
Reproducer *Reproducer `json:"reproducer,omitempty"`
}
Manifest records metadata and time-window spans for a flight recorder snapshot.
func (*Manifest) OverlapSpan ¶
OverlapSpan reports the overlapping time duration where both Go and GPU records are present.
func (*Manifest) WindowRequested ¶
WindowRequested reports the requested recording duration as time.Duration.
type Marker ¶
type Marker = re_ikettrace.Marker
type Meta ¶
type Meta = re_ikettrace.Meta
type ModeOverheadComparison ¶
type ModeOverheadComparison = re_ikettrace.ModeOverheadComparison
type ModuleDriver ¶
type ModuleDriver interface {
LoadModuleData(image []byte) (ModuleHandle, error)
GetGlobal(mod ModuleHandle, name string) (addr uint64, size uint64, err error)
MemcpyHtoD(dst uint64, src []byte) error
}
ModuleDriver abstracts the CUDA driver operations required by ModuleHook to load patched cubin images, resolve __iket_flight_cfg, and update device memory without reloading the module.
type ModuleHandle ¶
type ModuleHandle uintptr
ModuleHandle is an opaque handle to a loaded CUDA module.
type ModuleHook ¶
type ModuleHook struct {
// contains filtered or unexported fields
}
ModuleHook intercepts CUDA module loads, patches cubins with entry/exit flight-recorder trampolines (cached by SHA-256), resolves __iket_flight_cfg, and flips FlightMode in device memory without reloading the module.
func NewModuleHook ¶
func NewModuleHook(driver ModuleDriver, cfg ModuleHookConfig) (*ModuleHook, error)
NewModuleHook creates a ModuleHook backed by driver.
func (*ModuleHook) LoadModule ¶
func (h *ModuleHook) LoadModule(image []byte, kernelName string) (*LoadedModule, error)
LoadModule intercepts raw module bytes for an explicit kernelName, patches the cubin with SHA-256 caching, loads it via the driver, and resolves __iket_flight_cfg in device memory.
func (*ModuleHook) LoadModuleData ¶
func (h *ModuleHook) LoadModuleData(image []byte) (*LoadedModule, error)
LoadModuleData intercepts raw module bytes, patches the cubin (reusing any SHA-256 cached patched image), loads it via the driver, and resolves __iket_flight_cfg in device memory.
func (*ModuleHook) Module ¶
func (h *ModuleHook) Module(mod ModuleHandle) (LoadedModule, bool)
Module returns a snapshot of the tracked LoadedModule for mod.
func (*ModuleHook) SetConfig ¶
func (h *ModuleHook) SetConfig(mod ModuleHandle, cfg cudasass.PatchConfig) error
SetConfig writes a full 16-byte cudasass.PatchConfig to __iket_flight_cfg in device memory for mod without reloading the module.
func (*ModuleHook) SetMode ¶
func (h *ModuleHook) SetMode(mod ModuleHandle, mode uint32) error
SetMode updates FlightMode in device memory for mod without reloading it.
func (*ModuleHook) SetModeAll ¶
func (h *ModuleHook) SetModeAll(mode uint32) error
SetModeAll updates FlightMode in device memory across all currently loaded modules without reloading them.
func (*ModuleHook) Stats ¶
func (h *ModuleHook) Stats() ModuleHookStats
Stats returns a snapshot of cache and mode-flip counters.
func (*ModuleHook) UnloadModule ¶
func (h *ModuleHook) UnloadModule(mod ModuleHandle) error
UnloadModule removes mod from the hook's tracked modules and calls the driver's UnloadModule method if implemented.
type ModuleHookConfig ¶
type ModuleHookConfig struct {
// InitialConfig is the initial __iket_flight_cfg embedded into patched cubins.
InitialConfig cudasass.PatchConfig
// KernelName optionally restricts LoadModuleData to patching a single kernel.
// When empty, LoadModuleData discovers and patches all kernels in the cubin.
KernelName string
// Patcher optionally overrides the cubin patcher.
// Defaults to [cudasass.PatchCubinEntryExitWithConfig].
Patcher PatchFunc
}
ModuleHookConfig configures a ModuleHook.
type ModuleHookStats ¶
type ModuleHookStats struct {
CacheHits uint64
CacheMisses uint64
ModulesLoaded uint64
ModeFlips uint64
}
ModuleHookStats reports cache and mode-flip counters for a ModuleHook.
type Names ¶
type Names = re_ikettrace.Names
type NegativeControlResult ¶
type NegativeControlResult = re_ikettrace.NegativeControlResult
type NegativeRewriteConstraint ¶
type NegativeRewriteConstraint struct {
Candidate *CandidateAssociation `json:"candidate_association,omitempty"`
SchemaVersion int `json:"schema_version"`
CandidateDigest string `json:"candidate_digest"`
OffendingKernel string `json:"offending_kernel"`
QuarantinedRules []string `json:"quarantined_rules"`
Reason string `json:"reason"`
PruneSubtree bool `json:"prune_subtree"`
Timestamp time.Time `json:"timestamp"`
}
NegativeRewriteConstraint preserves candidate-only failure facts. The legacy CandidateDigest is a module digest. Only Candidate supplies the exact search invocation association; module digests must not be matched to executable IDs.
func DecodeNegativeRewriteConstraint ¶
func DecodeNegativeRewriteConstraint(data []byte) (NegativeRewriteConstraint, error)
DecodeNegativeRewriteConstraint decodes a versioned NegativeRewriteConstraint JSON payload and validates it for exact-candidate quarantine admission.
func (NegativeRewriteConstraint) MarshalJSON ¶
func (c NegativeRewriteConstraint) MarshalJSON() ([]byte, error)
MarshalJSON encodes c with an explicit schema_version, defaulting zero SchemaVersion values to NegativeRewriteConstraintSchemaVersion and rejecting unknown schema versions or invalid candidate digests.
func (*NegativeRewriteConstraint) UnmarshalJSON ¶
func (c *NegativeRewriteConstraint) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes c and validates its wire schema_version and candidate digest format. Withheld constraints (empty CandidateDigest with no broad rule or subtree ban) remain inspectable after unmarshaling; DecodeNegativeRewriteConstraint and Validate enforce exact-candidate quarantine admission.
func (*NegativeRewriteConstraint) Validate ¶
func (c *NegativeRewriteConstraint) Validate() error
Validate checks that c is an admitted versioned exact-candidate quarantine constraint: it must carry NegativeRewriteConstraintSchemaVersion, a valid exact association or legacy 64-character hexadecimal module CandidateDigest, a non-empty Reason, and no unreproduced broad rule bans or subtree pruning.
type OTLPEdge ¶
type OTLPEdge = re_ikettrace.OTLPEdge
type OTLPOptions ¶
type OTLPOptions = obsotlp.IKETOptions
OTLPOptions configures OTLP child span synthesis for an IKET trace.
type OTLPStageSummary ¶
type OTLPStageSummary = obsotlp.StageSummary
OTLPStageSummary aggregates per-stage latency percentiles, warp skew, and critical-path share across an IKET trace.
func SummarizeOTLPStages ¶
func SummarizeOTLPStages(tr *Trace, opts *OTLPOptions) ([]OTLPStageSummary, error)
SummarizeOTLPStages computes per-stage latency percentiles (p50, p99), warp skew, critical-path share, and the <4x tick resolution unresolved flag for tr.
type OverheadReport ¶
type OverheadReport = re_ikettrace.OverheadReport
type OverheadSummary ¶
type OverheadSummary = re_ikettrace.OverheadSummary
type PatchFunc ¶
PatchFunc patches a cubin for a single kernel with an initial cudasass.PatchConfig.
type Payload ¶
type Payload = re_ikettrace.Payload
type PayloadType ¶
type PayloadType = re_ikettrace.PayloadType
type PerturbationReport ¶
type PerturbationReport struct {
CaptureDuration time.Duration `json:"capture_duration"`
BundleBytes int64 `json:"bundle_bytes"`
RecordsCaptured int `json:"records_captured"`
CPUPercentActual float64 `json:"cpu_percent_actual"`
RSSBytesActual uint64 `json:"rss_bytes_actual"`
}
PerturbationReport captures measured overhead induced by high-fidelity incident capture.
type Phase ¶
type Phase = re_ikettrace.Phase
type PhaseClock ¶
type PhaseClock = re_ikettrace.PhaseClock
type PhaseStat ¶
type PhaseStat = re_ikettrace.PhaseStat
type PreTriggerReport ¶
type PreTriggerReport struct {
Available bool `json:"available"`
WindowDuration time.Duration `json:"window_duration"`
RecordCount int `json:"record_count"`
Truncated bool `json:"truncated"`
EarliestTimestampNs int64 `json:"earliest_timestamp_ns,omitempty"`
LatestTimestampNs int64 `json:"latest_timestamp_ns,omitempty"`
MissingPreTriggerFamilies []string `json:"missing_pre_trigger_families,omitempty"`
}
PreTriggerReport documents the availability and fidelity of pre-incident observations retained in memory before the trigger was fired.
type Range ¶
type Range = re_ikettrace.Range
type RangeScope ¶
type RangeScope = re_ikettrace.RangeScope
type RangeType ¶
type RangeType = re_ikettrace.RangeType
type RealClock ¶
type RealClock struct{}
RealClock implements Clock using the operating system clock.
func (RealClock) NowMonotonic ¶
type Record ¶
type Record struct {
TimestampNs int64 // Host or calibrated nanosecond timestamp
KernelName string // Executed kernel symbol name
CorrelationID uint64 // CUPTI correlation ID
DurationNs uint64 // Device execution duration in nanoseconds
Labels map[string]string // Contextual attributes (e.g. layer, expert, op)
}
Record represents a single timestamped GPU execution observation in the ring buffer.
type Recorder ¶
type Recorder struct {
// contains filtered or unexported fields
}
Recorder retains recent GPU observations in a host-memory ring buffer and combines them with configured artifact providers when taking a snapshot.
func New ¶
func New(cfg FlightConfig) (*Recorder, error)
New creates a new flight recorder with the supplied configuration.
func (*Recorder) AttachFile ¶
AttachFile attaches a named static artifact (such as kernels.ptx or kernels.sass) to snapshots.
func (*Recorder) CalibrateClock ¶
CalibrateClock measures the correspondence between the host clock and the CUPTI device timestamp clock. After it succeeds, PushActivityRecord maps device timestamps onto the host clock, and snapshots report clock uncertainty source "estimated": half the host-clock bracket measured around the device clock read, plus an allowance for drift since the read at an assumed 11 ppm. Only the bracket is measured. The estimate is not a qualified bound on the physical alignment error: the true drift rate of the clocks is not measured.
CalibrateClock is vendor library access: it loads libcupti if it is not already loaded and calls cuptiGetTimestamp. It does not enable activity collection.
CalibrateClock returns an error and changes nothing if the recorder is not running, if the clock read fails, or if the recorder is stopped before the read completes. A later successful call replaces an earlier calibration. Concurrent calls are serialized.
Example ¶
ExampleRecorder_CalibrateClock shows CalibrateClock refusing a recorder that is not running. A refused call reads no clock and changes nothing, so snapshots still report the clock uncertainty as unavailable.
On a running recorder CalibrateClock loads libcupti and reads the CUPTI device clock, so this example does not make that call. A program that wants calibrated activity timestamps calls it after Start:
if err := rec.CalibrateClock(); err != nil {
log.Printf("activity timestamps stay uncalibrated: %v", err)
}
rec, err := New(FlightConfig{})
if err != nil {
log.Fatal(err)
}
fmt.Println(rec.CalibrateClock())
if err := rec.Start(); err != nil {
log.Fatal(err)
}
rec.Stop()
fmt.Println(rec.CalibrateClock())
m, err := rec.Snapshot(context.Background(), io.Discard, "refused")
if err != nil {
log.Fatal(err)
}
fmt.Println(m.ClockUncertaintyNs, m.ClockUncertaintySource)
Output: cudaflightrecorder: recorder not running cudaflightrecorder: recorder is closed -1 unavailable
func (*Recorder) CleanupErr ¶
CleanupErr returns any error encountered during collector shutdown or resource cleanup.
func (*Recorder) Close ¶
Close halts flight recording and returns any cleanup or collector shutdown errors.
func (*Recorder) DetachFile ¶
DetachFile removes an attached static artifact by name.
func (*Recorder) FaultSnapshot ¶
func (r *Recorder) FaultSnapshot(ctx context.Context, w io.Writer, fault FaultInfo) (*Manifest, error)
FaultSnapshot writes a zero-device crash dump TAR archive to w using exclusively host DRAM circular buffer records and host-side telemetry, without contacting the GPU or driver. It preserves fault facts and candidate identity without admitting broad rewrite bans from an unreproduced fault.
func (*Recorder) Handler ¶
Handler returns an HTTP handler that triggers a snapshot and streams the resulting TAR bundle to the client upon GET/POST request.
func (*Recorder) PreTriggerDiagnostics ¶
func (r *Recorder) PreTriggerDiagnostics(triggerNs int64, window time.Duration) PreTriggerReport
PreTriggerDiagnostics returns diagnostic details about the currently retained records in the ring buffer relative to a trigger timestamp.
func (*Recorder) Push ¶
Push adds an observation to the in-memory circular buffer. It is non-blocking and safe for concurrent execution.
func (*Recorder) PushActivityRecord ¶
func (r *Recorder) PushActivityRecord(activity cuptix.ActivityRecord)
PushActivityRecord records a CUPTI activity using the host clock as its timestamp. Device timestamps are not comparable with the host timestamps used by Go traces, so the activity start is mapped through the calibration made by CalibrateClock. Without one, the record has timestamp 0 and the activity.uncalibrated label.
func (*Recorder) PushPMSample ¶
PushPMSample records a hardware Performance Monitor counter observation into the flight recorder.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
"github.com/tmc/lib/nvidia/x/obs/iket"
"log"
"time"
)
func main() {
rec, err := iket.New(iket.FlightConfig{
Window: 5 * time.Second,
Capacity: 100,
})
if err != nil {
log.Fatal(err)
}
if err := rec.Start(); err != nil {
log.Fatal(err)
}
defer rec.Stop()
sample := cuptix.PMSample{
Index: 0,
StartTimestamp: 1000,
EndTimestamp: 2000,
DurationNs: 1000,
Values: map[string]float64{"sm_busy": 95.0},
}
rec.PushPMSample(sample)
fmt.Printf("Pushed PM sample: duration=%dns\n", sample.DurationNs)
}
Output: Pushed PM sample: duration=1000ns
func (*Recorder) PushPolicyRecord ¶
PushPolicyRecord records a driver policy observation. It has the shape of a policy record sink, so a policy package can use it without this package importing that one. Call it after draining policy events, never from a driver fault handler.
timestampNs is a host timestamp in Unix nanoseconds. Zero uses collector receipt time, marked in the record labels. The record has no kernel name or device duration; duration_status marks the zero DurationNs as unavailable. The recorder must be started. Capacity and drop accounting are those of Push. The caller may reuse labels after this method returns.
Example ¶
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"github.com/tmc/lib/nvidia/x/obs/internal/obsbpfpolicy"
)
func main() {
r, err := iket.New(iket.FlightConfig{Capacity: 8})
if err != nil {
fmt.Println(err)
return
}
if err := r.Start(); err != nil {
fmt.Println(err)
return
}
defer r.Stop()
observer := obsbpfpolicy.SinkObserver{Sink: r}
observer.Observe(obsbpfpolicy.Outcome{Hook: "on_bind", Fallback: true, Reason: "hook unavailable"})
var out bytes.Buffer
if _, err := r.Snapshot(context.Background(), &out, "policy"); err != nil {
fmt.Println(err)
return
}
bundle, err := iket.ReadBundle(&out)
if err != nil {
fmt.Println(err)
return
}
var records []iket.Record
if err := json.Unmarshal(bundle.Files["gpu_records.json"], &records); err != nil {
fmt.Println(err)
return
}
fmt.Println(records[0].Labels["hook"], records[0].Labels["reason"])
}
Output: on_bind hook unavailable
func (*Recorder) PushSASSMetric ¶
func (r *Recorder) PushSASSMetric(timestampNs int64, correlationID uint64, sm cuptix.SASSMetric)
PushSASSMetric records an instruction-level SASS metric into the flight recorder ring buffer.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
"github.com/tmc/lib/nvidia/x/obs/iket"
"log"
"time"
)
func main() {
rec, err := iket.New(iket.FlightConfig{
Window: 5 * time.Second,
Capacity: 100,
})
if err != nil {
log.Fatal(err)
}
if err := rec.Start(); err != nil {
log.Fatal(err)
}
defer rec.Stop()
sm := cuptix.SASSMetric{
PC: 0x100,
KernelName: "gemm_wmma",
TotalSamples: 200,
Selected: 40,
Dominant: &cuptix.PipelineStall{
Name: "long_scoreboard",
Percent: 80.0,
},
}
rec.PushSASSMetric(time.Now().UnixNano(), 10, sm)
fmt.Println("Pushed SASS metric for:", sm.KernelName)
}
Output: Pushed SASS metric for: gemm_wmma
func (*Recorder) Register ¶
Register registers the flight recorder HTTP handler at DefaultEndpoint ("/debug/flightrecorder") on mux. If mux is nil, it registers on http.DefaultServeMux.
func (*Recorder) SetCleanupErr ¶
SetCleanupErr records a collector or cleanup error explicitly.
func (*Recorder) SetGPUPprofProvider ¶
SetGPUPprofProvider configures a provider that yields raw gpu.pprof bytes.
func (*Recorder) SetGoTraceProvider ¶
SetGoTraceProvider configures a provider that yields raw go.trace bytes.
func (*Recorder) SetPerfettoProvider ¶
SetPerfettoProvider configures a provider that yields raw timeline.pftrace bytes.
func (*Recorder) SetSystemInfo ¶
func (r *Recorder) SetSystemInfo(info *SystemInfo)
SetSystemInfo attaches a canonical SystemInfo record to snapshots produced by r.
func (*Recorder) Snapshot ¶
Snapshot writes a tar bundle to w containing recent flight records, a manifest, and artifacts supplied by configured providers. The reason labels the snapshot for later analysis. Record extraction reads host memory. Snapshot also calls configured providers and writes to w; their behavior determines whether those operations block or access GPU hardware.
Example (WithGoTrace) ¶
package main
import (
"bytes"
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"log"
"time"
)
func main() {
rec, err := iket.New(iket.FlightConfig{
Window: 5 * time.Second,
Capacity: 1024,
GoTraceEnabled: true,
})
if err != nil {
log.Fatal(err)
}
if err := rec.Start(); err != nil {
log.Fatal(err)
}
defer rec.Stop()
rec.SetGoTraceProvider(func(ctx context.Context) ([]byte, error) {
return []byte("go 1.22 trace payload"), nil
})
// Record a GPU execution observation
now := time.Now()
rec.Push(iket.Record{
TimestampNs: now.UnixNano(),
KernelName: "flash_attention_fwd",
CorrelationID: 101,
DurationNs: 15000,
})
time.Sleep(time.Millisecond)
// Take a multi-modal snapshot containing both Go trace and GPU records
var buf bytes.Buffer
manifest, err := rec.Snapshot(context.Background(), &buf, "latency_spike")
if err != nil {
log.Fatal(err)
}
bundle, err := iket.ReadBundle(&buf)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Snapshot reason: %s\n", bundle.Manifest.Reason)
fmt.Printf("GPU records: %d\n", bundle.Manifest.GPURecords)
fmt.Printf("Has go.trace: %t\n", len(bundle.Files["go.trace"]) > 0)
// manifest.OverlapReliable reports whether the Go and GPU spans were
// aligned with a clock uncertainty small enough to trust the overlap, and a
// caller gates its own conclusions on it:
//
// if manifest.OverlapReliable {
// // compare the Go and GPU spans
// }
//
// The example neither prints nor checks its value. Start never
// calibrates the clock and this recorder neither configures
// ClockUncertaintyNs nor calls CalibrateClock, so the uncertainty is
// unavailable and the value here is always false; printing it would show
// only that one case. The rules behind it are tested directly, by
// TestAlignSpansUncertaintyInputs and TestClockUncertaintyPrecedence.
//
// What does hold on every host is that the manifest Snapshot returns and
// the one inside the bundle are the same manifest, so that is what the
// example reports. It is printed rather than checked with log.Fatal:
// os.Exit from an example aborts the test binary and takes every other
// result in the package with it.
fmt.Printf("Bundle manifest agrees: %t\n",
bundle.Manifest.OverlapReliable == manifest.OverlapReliable &&
bundle.Manifest.ClockUncertaintyNs == manifest.ClockUncertaintyNs &&
bundle.Manifest.ClockUncertaintySource == manifest.ClockUncertaintySource)
}
Output: Snapshot reason: latency_spike GPU records: 1 Has go.trace: true Bundle manifest agrees: true
func (*Recorder) SnapshotOnIKETIncident ¶
func (r *Recorder) SnapshotOnIKETIncident( ctx context.Context, w io.Writer, trace *Trace, policy IKETTriggerPolicy, ) (*Manifest, *IKETIncident, error)
SnapshotOnIKETIncident evaluates trace against policy and, when an incident is triggered, captures a flight-recorder snapshot bundle to w labeled with the incident's reason. When no incident is triggered, it returns a nil Manifest and the evaluated IKETIncident without taking a snapshot.
func (*Recorder) Start ¶
Start begins continuous in-memory flight recording.
Start does not load or call CUPTI. Until CalibrateClock succeeds, activity records pushed with PushActivityRecord carry timestamp 0 and the activity.uncalibrated label, and snapshots report the configured clock uncertainty, or -1 when none is configured.
type RegionDiff ¶
type RegionDiff = re_ikettrace.RegionDiff
type RegionSummary ¶
type RegionSummary = re_ikettrace.RegionSummary
type Reproducer ¶
type Reproducer struct {
Version int `json:"version"`
StepID uint64 `json:"step_id"`
// Rows is the step's batch in execution order.
Rows []ReproducerRow `json:"rows"`
// KVSource is KVPages or KVPrefill.
KVSource string `json:"kv_source"`
// KVFile names the bundle entry holding the KV pages when KVSource
// is KVPages, and is empty otherwise.
KVFile string `json:"kv_file,omitempty"`
// KVHash is the hex SHA-256 of the KV pages the rows read, as
// returned by KVDigest.
KVHash string `json:"kv_hash"`
// GraphKey identifies the captured CUDA graph the step replayed.
// It is zero when Eager is set.
GraphKey uint64 `json:"graph_key"`
Eager bool `json:"eager"`
// Kernels lists the step's kernels in launch order.
Kernels []ReproducerKernel `json:"kernels"`
WeightsHash string `json:"weights_hash"`
DType string `json:"dtype"`
// Settings is the settings snapshot in effect for the step. Only its
// compacted form is hashed, so reformatting it does not change InputHash.
Settings json.RawMessage `json:"settings,omitempty"`
// StepTimeNs is the captured device step time.
StepTimeNs int64 `json:"step_time_ns"`
// Cause is the tail cause label attached to the step, if any.
Cause string `json:"cause,omitempty"`
// Tracing reports whether tracing was on when the step was captured.
Tracing bool `json:"tracing"`
// InputHash is the hex SHA-256 returned by Digest.
InputHash string `json:"input_hash"`
}
A Reproducer is the manifest entry that lets a kept serving step run again standalone. It records the step's inputs (the batch, the KV state the rows read, the graph or eager path and its kernels, the weights and the settings), what was observed when it ran (device step time, cause label, tracing), and InputHash, a digest of the inputs alone.
A replay recomputes InputHash from what it loaded and checks the KV state it restored with Reproducer.CheckKV; on a mismatch it must refuse the step rather than time it.
func DecodeReproducer ¶
func DecodeReproducer(data []byte) (*Reproducer, error)
DecodeReproducer decodes a JSON reproducer, refusing unknown fields and trailing data, and validates it.
func (*Reproducer) CheckKV ¶
func (r *Reproducer) CheckKV(kv []byte) error
CheckKV reports whether kv, the KV pages a replay loaded or rebuilt, hash to r.KVHash. A mismatch is reported as ErrReproducerMismatch.
func (*Reproducer) Digest ¶
func (r *Reproducer) Digest() (string, error)
Digest returns the hex SHA-256 of r's inputs: version, batch, KV hash, graph key and eager flag, kernels and their module hashes, weights hash, dtype and compacted settings. StepID, the observations and InputHash itself are not hashed. Digest reports an error if r's inputs are invalid.
func (*Reproducer) Validate ¶
func (r *Reproducer) Validate() error
Validate checks r's version, structure and bounds, and that InputHash equals Digest. A wrong InputHash is reported as ErrReproducerMismatch.
type ReproducerKernel ¶
type ReproducerKernel struct {
Name string `json:"name"`
// ModuleHash is the hex SHA-256 of the loaded module image.
ModuleHash string `json:"module_hash"`
}
A ReproducerKernel names one kernel of a step and the module it came from.
type ReproducerRow ¶
type ReproducerRow struct {
// Kind is RowDecode or RowPrompt.
Kind string `json:"kind"`
Seq uint32 `json:"seq"`
// Pos is the position of Tokens[0] in its sequence.
Pos int32 `json:"pos"`
// SeqLen is the number of KV entries the row reads,
// at least Pos+len(Tokens).
SeqLen int32 `json:"seq_len"`
// Tokens are the row's input tokens: one for a decode row,
// one or more for a prompt row.
Tokens []int32 `json:"tokens"`
// Prefix holds the Pos tokens before Tokens when the reproducer's
// KVSource is KVPrefill, and is empty otherwise.
Prefix []int32 `json:"prefix,omitempty"`
// Output reports whether the row's last token produces a next token.
Output bool `json:"output"`
}
A ReproducerRow is one row of a reproducer's batch.
type ResourceSampler ¶
type ResourceSampler interface {
SampleUsage(ctx context.Context) (cpuPercent float64, rssBytes uint64, err error)
}
ResourceSampler samples host process CPU and memory (RSS) metrics.
type RingConfig ¶
type RingConfig = re_ikettrace.RingConfig
type RingTrace ¶
type RingTrace = re_ikettrace.RingTrace
type SleepBracketResult ¶
type SleepBracketResult = re_ikettrace.SleepBracketResult
type SnapshotDiskManager ¶
type SnapshotDiskManager struct {
// contains filtered or unexported fields
}
SnapshotDiskManager manages regular files in one snapshot directory. Use a single manager and no external writer for that directory. It may prune only snapshots created by this instance; existing and replaced files remain unowned but count toward the byte budget. Ownership does not survive restart. Subdirectories are outside the budget and are never removed.
func NewSnapshotDiskManager ¶
func NewSnapshotDiskManager(dir string, maxBytes int64) (*SnapshotDiskManager, error)
NewSnapshotDiskManager creates a new disk retention manager for the specified directory.
func (*SnapshotDiskManager) RetainedBytes ¶
func (m *SnapshotDiskManager) RetainedBytes() int64
RetainedBytes computes the current total disk usage for snapshots in the managed directory.
func (*SnapshotDiskManager) SaveSnapshot ¶
func (m *SnapshotDiskManager) SaveSnapshot(filename string, data []byte) (string, error)
SaveSnapshot writes a snapshot archive to disk while enforcing the retention budget. If the snapshot exceeds maxBytes by itself, or if existing files cannot be pruned to accommodate it, ErrDiskBudgetExceeded is returned.
type StageSpan ¶
StageSpan is a single calibrated IKET stage interval on a (SM, CTA/block, warp).
func StageSpans ¶
func StageSpans(tr *Trace, cal *ClockCalibration, tickResolutionNs uint64) ([]StageSpan, error)
StageSpans extracts all stage ranges from tr, applies cal when non-nil, and returns the resulting StageSpan slice.
type State ¶
type State string
State represents the lifecycle state of the escalation state machine.
const ( // StateIdle indicates the coordinator is passive; continuous observation may run, // but escalation triggers are ignored or refused. StateIdle State = "idle" // StateArmed indicates the coordinator is actively evaluating triggers. StateArmed State = "armed" // StateCapturing indicates an incident escalation capture is in progress. StateCapturing State = "capturing" // StateCooldown indicates capture has completed and the system is cooling down // to prevent trigger storms and thrashing. StateCooldown State = "cooldown" // StateRefused indicates a trigger was evaluated and rejected due to a budget or conflict. StateRefused State = "refused" // StateStopped indicates permanent terminal shutdown. StateStopped State = "stopped" )
type StitchedKernel ¶
type StitchedKernel = re_ikettrace.StitchedKernel
type StuckRingError ¶
type StuckRingError = re_ikettrace.StuckRingError
type StuckSegmentError ¶
type StuckSegmentError = re_ikettrace.StuckSegmentError
type Summary ¶
type Summary = re_ikettrace.Summary
type SystemInfo ¶
type SystemInfo = systeminfo.SystemInfo
SystemInfo is the canonical system, device, driver, loaded-library, clock, power, throttle, and host-CPU contention record embedded in flight recorder bundles.
type TailConfig ¶
type TailConfig struct {
// EncodeSnapshot optionally writes an offline spans JSONL artifact on selection.
// It must honor ctx; output and total preparation+capture time are bounded by
// the coordinator's byte and duration budgets. It runs only on selected captures.
EncodeSnapshot func(context.Context, io.Writer, TailDecision) error
MaxSteps, MaxBytes, Predecessors, SnapshotsPerMinute int
StepThreshold, TTFTTarget, ITLTarget time.Duration
SampleEvery uint64
TenantID string
}
type TailDecision ¶
type TailDecision struct {
RequestID string `json:"request_id,omitempty"`
Keep bool `json:"keep"`
SampleRate uint64 `json:"sample_rate"`
Reason string `json:"reason"`
Incomplete bool `json:"incomplete"`
Steps []TailStep `json:"steps,omitempty"`
Incident *IncidentReceipt `json:"incident,omitempty"`
}
TailDecision separates selection from capture admission. SampleRate applies to every exported span of the selected request. Incomplete exposes evicted steps.
type TailRecorder ¶
type TailRecorder struct {
// contains filtered or unexported fields
}
TailRecorder retains completed steps in host memory. Device allocation and asynchronous drain ownership belong to the caller. Its zero value is unusable. Capture calls are serialized without blocking retention. Use one instance per Recorder; the caller arms the supplied EscalationCoordinator.
func NewTailRecorder ¶
func NewTailRecorder(rec *Recorder, coordinator *EscalationCoordinator, cfg TailConfig) (*TailRecorder, error)
NewTailRecorder creates a bounded host recorder backed by rec's coordinator.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
)
func main() {
rec, _ := iket.New(iket.FlightConfig{Capacity: 8})
defer rec.Stop()
coord, _ := iket.NewEscalationCoordinator(rec, iket.DefaultBudgets())
defer coord.Stop()
tail, err := iket.NewTailRecorder(rec, coord, iket.TailConfig{MaxSteps: 4, MaxBytes: 4096, Predecessors: 1, SnapshotsPerMinute: 1, SampleEvery: 100, TenantID: "example"})
fmt.Println(tail != nil, err)
}
Output: true <nil>
func (*TailRecorder) Complete ¶
func (t *TailRecorder) Complete(ctx context.Context, id string, ids []uint64, ttft, maxITL time.Duration, failed bool) (TailDecision, error)
Complete selects a request at completion. ids names every participating step; missing or mismatched batch links are reported through Incomplete. Error and tail requests always have SampleRate=1; healthy requests use a stable ID hash.
func (*TailRecorder) Record ¶
func (t *TailRecorder) Record(step TailStep) (bool, error)
Record copies a completed step and reports whether its latency threshold fired. Oversized steps evict history and report loss, never substituting old history.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"time"
)
func main() {
// Drain completion must precede Record; no GPU operation occurs in this example.
rec, _ := iket.New(iket.FlightConfig{Capacity: 8})
defer rec.Stop()
coord, _ := iket.NewEscalationCoordinator(rec, iket.DefaultBudgets())
defer coord.Stop()
tail, _ := iket.NewTailRecorder(rec, coord, iket.TailConfig{MaxSteps: 4, MaxBytes: 4096, Predecessors: 1, SnapshotsPerMinute: 1, SampleEvery: 100, TenantID: "example", StepThreshold: time.Millisecond})
fired, err := tail.Record(iket.TailStep{ID: 1, StartNs: 1, EndNs: 2})
fmt.Println(fired, err, tail.Stats().RetainedSteps)
}
Output: false <nil> 1
func (*TailRecorder) Stats ¶
func (t *TailRecorder) Stats() TailStats
Stats returns payload retention and cumulative loss counts. MaxBytes covers encoded step payloads, excluding Go bookkeeping and transient capture copies.
func (*TailRecorder) Trigger ¶
func (t *TailRecorder) Trigger(ctx context.Context, reason string, ids []uint64) (TailDecision, error)
Trigger captures explicit steps for a "step_latency" or "manual" trigger. Both paths enforce coordinator admission, cooldown, duration and byte budgets.
type TailStats ¶
type TailStats struct {
RetainedBytes, RetainedSteps int
Evicted, Oversized, Suppressed, Failed uint64
}
TailStats counts payload retention and all capture refusals and failures.
type TailStep ¶
type TailStep struct {
// RequestLinks contains only known, frozen request span contexts and their
// proven row bindings. Absent request context stays absent, never synthesized.
RequestLinks []obsotlp.SpanLink `json:"request_links,omitempty"`
// TestDelayTicks is a measured globaltimer bracket from an explicit spin-kernel control.
TestDelayTicks [2]uint64 `json:"test_delay_ticks,omitempty"`
ID uint64 `json:"id"`
StartNs int64 `json:"start_ns"`
EndNs int64 `json:"end_ns"`
RequestIDs []string `json:"request_ids"`
IKET []byte `json:"iket"`
Calibration json.RawMessage `json:"calibration"`
}
TailStep is a completed asynchronously drained device buffer with batch links. IDs are positive, monotonically increasing serving step numbers; gaps record lost steps. Times use one host clock. Calibration contains the measured lane48 calibration.
type Trace ¶
type Trace = re_ikettrace.Trace
type TriggerEvidence ¶
type TriggerEvidence struct {
TimestampMono int64 `json:"timestamp_mono"`
TimestampUnix int64 `json:"timestamp_unix"`
TenantID string `json:"tenant_id"`
Reason string `json:"reason"`
MetricName string `json:"metric_name"`
MetricValue float64 `json:"metric_value"`
Threshold float64 `json:"threshold"`
PreTrigger PreTriggerReport `json:"pre_trigger"`
Details map[string]string `json:"details,omitempty"`
}
TriggerEvidence captures the factual trigger context, metric values, and pre-trigger availability.
type TriggerRequest ¶
type TriggerRequest struct {
TenantID string `json:"tenant_id"`
Reason string `json:"reason"`
MetricName string `json:"metric_name"`
MetricValue float64 `json:"metric_value"`
Threshold float64 `json:"threshold"`
DeviceOrdinal uint32 `json:"device_ordinal"`
Details map[string]string `json:"details,omitempty"`
}
TriggerRequest defines an incoming escalation request.
type ValidationReport ¶
type ValidationReport = re_ikettrace.ValidationReport
type WarpLifetime ¶
type WarpLifetime = re_ikettrace.WarpLifetime
type WorkloadTrigger ¶
type WorkloadTrigger struct {
// contains filtered or unexported fields
}
WorkloadTrigger owns one series' Detector history and uses an existing coordinator for capture admission. Its zero value is unusable. Do not copy it. Observe is synchronous and serialized; the coordinator's existing capture budgets and cooperative provider/writer cancellation remain authoritative. Use separate instances for concurrent series. Invalid observations reset only this instance; run/phase/epoch/bucket changes restart its warmup.
func NewWorkloadTrigger ¶
func NewWorkloadTrigger(c WorkloadTriggerConfig, coordinator *EscalationCoordinator) (*WorkloadTrigger, error)
NewWorkloadTrigger freezes a series profile and creates its existing Detector. Provider/version admission remains with the serving reader during Observe.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
"time"
)
// This example provider performs no native acquisition or trace production.
type exampleWorkloadCapture struct{}
func (exampleWorkloadCapture) Capture(context.Context, *iket.Recorder, iket.TriggerRequest, func()) (iket.CaptureReport, error) {
return iket.CaptureReport{Provider: "host_fake", Closed: true}, nil
}
func newWorkloadExample() (*iket.WorkloadTrigger, func(), error) {
recorder, err := iket.New(iket.FlightConfig{Capacity: 8})
if err != nil {
return nil, nil, err
}
if err := recorder.Start(); err != nil {
return nil, nil, err
}
budgets := iket.DefaultBudgets()
budgets.HysteresisCount = 1
coordinator, err := iket.NewEscalationCoordinator(recorder, budgets,
iket.WithClock(iket.NewFakeClock(time.Unix(1, 0))),
iket.WithResourceSampler(&iket.FakeResourceSampler{}),
iket.WithCUPTINegotiator(&iket.FakeCUPTINegotiator{}),
iket.WithIncidentCapture(exampleWorkloadCapture{}))
if err != nil {
recorder.Stop()
return nil, nil, err
}
cleanup := func() { coordinator.Stop(); recorder.Stop() }
if err := coordinator.Arm(); err != nil {
cleanup()
return nil, nil, err
}
bridge, err := iket.NewWorkloadTrigger(iket.WorkloadTriggerConfig{
Provider: "triton", Version: "25.06", Metric: "nv_inference_queue_duration_us", Unit: "us",
Mode: "counter_delta", TimeSource: "collector_observation",
Labels: map[string]string{"model": "example", "version": "1"}, TenantID: "host-example",
WindowDuration: time.Second, StaticThreshold: 20,
Detector: iket.DetectorConfig{Mode: "rolling", Window: 2, Warmup: 1, Delta: 5, MaxGap: time.Second},
}, coordinator)
if err != nil {
cleanup()
return nil, nil, err
}
return bridge, cleanup, nil
}
func observeWorkloadExample(bridge *iket.WorkloadTrigger, index int64, before, after string) (iket.WorkloadTriggerResult, error) {
ctx := context.Background()
source := telemetry.WorkloadSource{Provider: "triton", Version: "25.06", RunID: "constructed-example", Phase: "steady", ClockDomain: "example-clock", ClockEpochID: "example-epoch"}
read := func(value string, when int64) (telemetry.WorkloadExport, error) {
raw := "# TYPE nv_inference_queue_duration_us counter\nnv_inference_queue_duration_us{model=\"example\",version=\"1\"} " + value + "\n"
e, err := telemetry.ReadServingExposition(ctx, strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
return e, err
}
return telemetry.StampWorkloadSnapshot(e, when, source.ClockDomain, source.ClockEpochID)
}
window := iket.WorkloadTriggerWindow{StartNanos: index * int64(time.Second), EndNanos: (index + 1) * int64(time.Second), ClockDomain: source.ClockDomain, ClockEpochID: source.ClockEpochID}
a, err := read(before, window.StartNanos)
if err != nil {
return iket.WorkloadTriggerResult{}, err
}
b, err := read(after, window.EndNanos)
if err != nil {
return iket.WorkloadTriggerResult{}, err
}
return bridge.Observe(ctx, a, b, window)
}
func main() {
bridge, cleanup, err := newWorkloadExample()
if err != nil {
fmt.Println(err)
return
}
defer cleanup()
result, err := observeWorkloadExample(bridge, 0, "0", "10")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(result.Decision.Reason, result.Incident == nil)
}
Output: warmup true
func (*WorkloadTrigger) Observe ¶
func (t *WorkloadTrigger) Observe(ctx context.Context, before, after telemetry.WorkloadExport, window WorkloadTriggerWindow) (result WorkloadTriggerResult, err error)
Observe authenticates parsed exports against their bounded serving-reader raw bytes, validates a counter/histogram window, and feeds its value to Detector. Collector timestamps are reproduced only through StampWorkloadSnapshot; native timestamps are never overwritten. Missing/reset/invalid data clears warmup without adding a healthy zero. All returned raw bytes are owned by the result. The raw SHA references are also retained in incident trigger details. The full exact rational is returned in ExactValue; incident details retain its SHA-256 so high precision cannot exceed the coordinator's detail-string limit.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
"time"
)
// This example provider performs no native acquisition or trace production.
type exampleWorkloadCapture struct{}
func (exampleWorkloadCapture) Capture(context.Context, *iket.Recorder, iket.TriggerRequest, func()) (iket.CaptureReport, error) {
return iket.CaptureReport{Provider: "host_fake", Closed: true}, nil
}
func newWorkloadExample() (*iket.WorkloadTrigger, func(), error) {
recorder, err := iket.New(iket.FlightConfig{Capacity: 8})
if err != nil {
return nil, nil, err
}
if err := recorder.Start(); err != nil {
return nil, nil, err
}
budgets := iket.DefaultBudgets()
budgets.HysteresisCount = 1
coordinator, err := iket.NewEscalationCoordinator(recorder, budgets,
iket.WithClock(iket.NewFakeClock(time.Unix(1, 0))),
iket.WithResourceSampler(&iket.FakeResourceSampler{}),
iket.WithCUPTINegotiator(&iket.FakeCUPTINegotiator{}),
iket.WithIncidentCapture(exampleWorkloadCapture{}))
if err != nil {
recorder.Stop()
return nil, nil, err
}
cleanup := func() { coordinator.Stop(); recorder.Stop() }
if err := coordinator.Arm(); err != nil {
cleanup()
return nil, nil, err
}
bridge, err := iket.NewWorkloadTrigger(iket.WorkloadTriggerConfig{
Provider: "triton", Version: "25.06", Metric: "nv_inference_queue_duration_us", Unit: "us",
Mode: "counter_delta", TimeSource: "collector_observation",
Labels: map[string]string{"model": "example", "version": "1"}, TenantID: "host-example",
WindowDuration: time.Second, StaticThreshold: 20,
Detector: iket.DetectorConfig{Mode: "rolling", Window: 2, Warmup: 1, Delta: 5, MaxGap: time.Second},
}, coordinator)
if err != nil {
cleanup()
return nil, nil, err
}
return bridge, cleanup, nil
}
func observeWorkloadExample(bridge *iket.WorkloadTrigger, index int64, before, after string) (iket.WorkloadTriggerResult, error) {
ctx := context.Background()
source := telemetry.WorkloadSource{Provider: "triton", Version: "25.06", RunID: "constructed-example", Phase: "steady", ClockDomain: "example-clock", ClockEpochID: "example-epoch"}
read := func(value string, when int64) (telemetry.WorkloadExport, error) {
raw := "# TYPE nv_inference_queue_duration_us counter\nnv_inference_queue_duration_us{model=\"example\",version=\"1\"} " + value + "\n"
e, err := telemetry.ReadServingExposition(ctx, strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
return e, err
}
return telemetry.StampWorkloadSnapshot(e, when, source.ClockDomain, source.ClockEpochID)
}
window := iket.WorkloadTriggerWindow{StartNanos: index * int64(time.Second), EndNanos: (index + 1) * int64(time.Second), ClockDomain: source.ClockDomain, ClockEpochID: source.ClockEpochID}
a, err := read(before, window.StartNanos)
if err != nil {
return iket.WorkloadTriggerResult{}, err
}
b, err := read(after, window.EndNanos)
if err != nil {
return iket.WorkloadTriggerResult{}, err
}
return bridge.Observe(ctx, a, b, window)
}
func main() {
bridge, cleanup, err := newWorkloadExample()
if err != nil {
fmt.Println(err)
return
}
defer cleanup()
if _, err := observeWorkloadExample(bridge, 0, "0", "10"); err != nil {
fmt.Println(err)
return
}
result, err := observeWorkloadExample(bridge, 1, "10", "40")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(result.Decision.Reason, result.ExactValue, result.StaticExceeded)
fmt.Println(result.Incident.Capture.Provider, "native startup:", result.Incident.Capture.Started)
}
Output: high_anomaly 30 true host_fake native startup: false
type WorkloadTriggerConfig ¶
type WorkloadTriggerConfig struct {
Provider, Version, Metric, Unit string
Mode, TimeSource string
Labels map[string]string
WindowDuration time.Duration
MinPopulation uint64
StaticThreshold float64
Detector DetectorConfig
Limits telemetry.WorkloadLimits
TenantID string
DeviceOrdinal uint32
}
WorkloadTriggerConfig freezes one serving series' observation profile. Mode is "counter_delta" or "histogram_mean"; Metric is the counter name or histogram base name. Labels selects exactly one series, excluding histogram le labels. Unit is the counter or histogram sum unit. WindowDuration and TimeSource ("producer" or "collector_observation") must remain fixed. MinPopulation must be positive for a histogram mean. StaticThreshold is a separate high-side comparison in Unit, not an SLO or capture admission policy.
Provider/Version must be supported by nvtelemetry.ReadServingExposition: Triton 25.06, vLLM 0.8.5, Ray 2.44.0, SGLang 0.5.21 or Dynamo 1.5.1. Training exports and arbitrary WorkloadExport producers are not supported.
type WorkloadTriggerResult ¶
type WorkloadTriggerResult struct {
Config WorkloadTriggerConfig
Window WorkloadTriggerWindow
Before, After telemetry.WorkloadExport
Series []telemetry.WorkloadDelta
ExactValue string
Population string
Rounded bool
StaticExceeded bool
Observation DetectorObservation
Decision DetectorDecision
Incident *IncidentReceipt
Error string
}
WorkloadTriggerResult retains raw/normalized reader evidence, exact window values and the Detector's float64 representation separately. Rounded reports conversion rounding. Population is empty for counters. StaticExceeded is not an individual-request SLO result. Decision never implies capture admission; Incident is present only when an anomaly was sent to the existing coordinator. Error describes validation failure or capture refusal/failure.
type WorkloadTriggerWindow ¶
WorkloadTriggerWindow names the exact aggregate observation interval and clock. Collector observation times are caller assertions, never sensor or request event times. Phase, run and rank remain in the supplied exports.
Source Files
¶
- doc.go
- flight_async_escalation.go
- flight_bundle.go
- flight_detector.go
- flight_device_ring.go
- flight_escalation.go
- flight_gotrace.go
- flight_gotrace_validate.go
- flight_iket_trigger.go
- flight_incident_capture.go
- flight_policy.go
- flight_recorder.go
- flight_reproducer.go
- flight_resources_linux.go
- flight_ring_decode.go
- flight_tail.go
- flight_workload_trigger.go
- gpuvis_timeline.go
- hook.go
- otlp.go
- reexport.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package obsiket implements the core in-kernel event trace and phase analysis layer.
|
Package obsiket implements the core in-kernel event trace and phase analysis layer. |
|
Package ring decodes device-side in-kernel %globaltimer event ring buffers.
|
Package ring decodes device-side in-kernel %globaltimer event ring buffers. |