Documentation
¶
Overview ¶
Package telemetry provides GPU fleet telemetry, NVML/DCGM/nvidia-smi readers, XID error catalogs and log parsers, and Nsight Compute/Systems importers.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Code generated from pinned official schema SQL by generate_schema.py; DO NOT EDIT.
Example (Bridge) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
s := telemetry.Snapshot{
Owner: [16]byte{1}, Generation: 1, PublishedUnix: 1,
EpochID: "example-epoch", ClockDomain: "synthetic_fixture", SchemaVersion: 2,
Devices: []telemetry.DeviceMetadata{{UUID: "GPU-example"}},
}
data, err := telemetry.Encode(s)
if err != nil {
panic(err)
}
decoded, err := telemetry.DecodeBridge(data)
if err != nil {
panic(err)
}
fmt.Println(decoded.Generation, decoded.Devices[0].UUID, len(data))
}
Output: 1 GPU-example 35024
Example (Ncu) ¶
package main
import (
"crypto/sha256"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
// exampleEnvelope is a synthetic exporter control, not a vendor report.
func exampleEnvelope() telemetry.Envelope {
csv := "ID,Process ID,Process Name,Host Name,Kernel Name,Context,Stream,Block Size,Grid Size,Device,CC,Section Name,Metric Name,Metric Unit,Metric Value,Rule Name,Rule Type,Rule Description,Estimated Speedup Type,Estimated Speedup\n" +
"0,1,example,host,kernel,1,1,\"(1, 1, 1)\",\"(1, 1, 1)\",0,9.0,Timing,gpu__time_duration.sum,ns,42,\n"
return telemetry.Envelope{SchemaVersion: 1, ToolVersion: telemetry.ToolVersion, Format: telemetry.NCUFormat, SourcePath: "synthetic example", ReportDigest: fmt.Sprintf("%x", sha256.Sum256([]byte("synthetic example"))), CSVDigest: fmt.Sprintf("%x", sha256.Sum256([]byte(csv))), CSV: csv}
}
func main() {
r, err := telemetry.ImportNCU(exampleEnvelope(), nil)
fmt.Println(err, len(r.Rows), r.Rows[0].JoinReason)
}
Output: <nil> 1 external launch identity unavailable
Example (Nsys) ¶
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
// metadataFixture is a synthetic read-only database boundary. A real adapter
// belongs outside this package and must verify its stable database identity,
// bind process/cancellation/output limits, and project exact SQLite columns.
type metadataFixture struct{}
func (metadataFixture) ReadTable(ctx context.Context, name string, limit int) (telemetry.Table, error) {
if name != "META_DATA_EXPORT" {
return telemetry.Table{}, telemetry.ErrUnavailable
}
return telemetry.Table{DatabaseSHA256: strings.Repeat("b", 64), Columns: []telemetry.Column{{Name: "name", Type: "TEXT"}, {Name: "value", Type: "TEXT", Nullable: true}}, Rows: []json.RawMessage{json.RawMessage(`{"name":"EXPORT_SCHEMA_VERSION","value":"3.11.0"}`)}}, nil
}
func main() {
source := telemetry.NSysSource{ToolVersion: "2024.2", ToolBuild: "2024.2-fixture", ReportPath: "synthetic.nsys-rep", ReportSHA256: strings.Repeat("a", 64), DatabaseSHA256: strings.Repeat("b", 64), Clock: "unestablished"}
r, err := telemetry.ImportNSys(context.Background(), metadataFixture{}, source, telemetry.NSysLimits{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(r.SchemaVersion, r.Basis, len(r.Events))
}
Output: 3.11.0 external:nsys 0
Example (Nvidiasmi) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"log"
"strings"
)
const report = `<?xml version="1.0" ?>
<!DOCTYPE nvidia_smi_log SYSTEM "nvsmi_device_v12.dtd">
<nvidia_smi_log>
<driver_version>570.148.08</driver_version>
<attached_gpus>1</attached_gpus>
<gpu id="00000000:01:00.0">
<product_name>NVIDIA L4</product_name>
<fb_memory_usage><total>23034 MiB</total><used>0 MiB</used></fb_memory_usage>
<temperature><gpu_temp>45 C</gpu_temp><memory_temp>N/A</memory_temp></temperature>
<gpu_power_readings>
<average_power_draw>16.20 W</average_power_draw>
<current_power_limit>72.00 W</current_power_limit>
</gpu_power_readings>
</gpu>
</nvidia_smi_log>`
func main() {
r, err := telemetry.Parse(strings.NewReader(report))
if err != nil {
log.Fatal(err)
}
fmt.Println(r.DTDVersion, r.DriverVersion)
for _, g := range r.GPUs {
w, _ := g.Power.Draw().Float()
mem, _ := g.FBMemory.Total.Bytes()
fmt.Println(g.ID, g.ProductName, w, g.Power.Limit, mem>>30, "GiB")
}
}
Output: 12 570.148.08 00000000:01:00.0 NVIDIA L4 16.2 72.00 W 22 GiB
Example (Xidlog) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func inputs() telemetry.XIDLogOptions {
return telemetry.XIDLogOptions{Source: telemetry.XIDLogSource{BootID: "supplied-boot", InputID: "constructed example"}, Product: "L4", Driver: "580"}
}
func main() {
r, _ := telemetry.NewReader(strings.NewReader("NVRM: Xid (PCI:0000:65:00): 31, constructed\n"), telemetry.Text, inputs())
v, _ := r.Next()
fmt.Println(v.Kind, v.PCI, v.Code, v.Applicability == telemetry.UncoveredProduct)
}
Output: xid 0000:65:00 31 true
Index ¶
- Constants
- Variables
- func APILaunches(api []Span, names ...string) (calls int, totalNS int64)
- func AggregateWindow(windowName string, startMono, endMono int64, samples []Sample, ...) ([]WindowSummary, []EnergySummary)
- func AggregateWindowStrict(windowName string, startMono, endMono int64, samples []Sample, ...) ([]WindowSummary, []EnergySummary, error)
- func ClassifyNVMLError(err error) string
- func ClocksEventReasonNames(mask uint64) []string
- func DispatchDCGMFieldPolicyV3Callback(violation *dcgm.FieldPolicyViolation, token uint64) int32
- func DockerArgs(g HealthGPU) ([]string, error)
- func Encode(s Snapshot) ([]byte, error)
- func EvaluateSample(sample Sample, policies []TriggerPolicy) (Reading, TriggerPolicy, bool)
- func ExactWorkloadJoin(WorkloadExport) error
- func FormatDDMappingMarkdown(w io.Writer) error
- func FormatOracleComparisonTable(hostLabel string, comps []OracleFieldComparison) string
- func LookupMetricKind(name string) (kind string, found bool)
- func LookupMetricUnit(name string) (unit string, found bool)
- func LookupProduct(id uint64, product Architecture) (Entry, Applicability)
- func MarshalOTLPLogsProto(readings []Reading, o ExportOptions, attribution ...map[string]K8sAttribution) ([]byte, error)
- func MarshalOTLPMetricsProto(readings []Reading, o ExportOptions, attribution ...map[string]K8sAttribution) ([]byte, error)
- func OracleMetricOrder() []string
- func OwnedBy(fsys fs.FS, roots ...int) func(pid uint32) bool
- func ParseKubernetesCgroup(lines []string) (uid, container string)
- func ParseNvidiaSMIQText(text string, dst *OracleSample)
- func ProcessEpochID() string
- func QueryCSV(ctx context.Context, args []string, opts ...SMIOption) ([][]string, error)
- func ReadMovementContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, MovementContext, error)
- func ReadOperatorCPUContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, OperatorCPUContext, error)
- func ReadOperatorContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, OperatorContext, error)
- func ReadPyTorchAnnotations(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, []WorkloadAnnotation, error)
- func ReadServingContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, ServingContext, error)
- func ReadServingContextV2(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, ServingContextV2, error)
- func ReadStream(r io.Reader, maxBytes int64) (*Manifest, []PhaseMarker, []Sample, error)
- func ReadStreamStrict(r io.Reader, maxBytes int64) (*Manifest, []PhaseMarker, []Sample, error)
- func ReadTrainingCheckpointContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, TrainingCheckpointContext, error)
- func ReadTrainingContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, TrainingContext, error)
- func ReadTrainingPhaseContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, TrainingPhaseContext, error)
- func RecoverDurableDelivery(path, owner string) error
- func RecoverRetention(path, owner string) error
- func Reset(ctx context.Context, ids ...string) error
- func RunSMI(ctx context.Context, args []string, opts ...SMIOption) ([]byte, error)
- func RuntimeLoadFromExposition(ctx context.Context, r io.Reader, limits WorkloadLimits) (load float64, ok bool, err error)
- func SafeCaptureLabels(input map[string]string, allowed []string) (map[string]string, error)
- func ShortKernels(step []Span, maxNS int64) (n int, totalNS int64)
- func SplitSteps(kernels []Span, end string) [][]Span
- func Stable(windows []SpanWindow, tolerance float64) error
- func StepGaps(steps [][]Span) []int64
- func TransitionEntityAssignment(previous, next EntityAssignment, at int64) (EntityAssignment, EntityAssignment, error)
- func ValidateDurableDeliveryRecoveryManifest(m DurableDeliveryRecoveryManifest) error
- func ValidateMetricAveraging(name string) error
- func ValidateReadingSource(s *ReadingSource) error
- func ValidateRetentionRecoveryManifest(m RetentionRecoveryManifest) error
- func WriteAccounting(w io.Writer, in AccountingInput) error
- func WriteAccountingReport(w io.Writer, report AccountingReport) error
- func WriteDCGMFieldPolicyV3Event(w io.Writer, e DCGMFieldPolicyV3Event) error
- func WriteDCGMPolicyEvent(w io.Writer, e DCGMPolicyEvent) error
- func WriteDurableDeliveryRecoveryManifest(w io.Writer, m DurableDeliveryRecoveryManifest) error
- func WriteEntityExport(w io.Writer, e EntityExport) error
- func WriteExposition(w io.Writer, readings []Reading, o ExportOptions) error
- func WriteHealthSnapshot(w io.Writer, s HealthSnapshot, limits HealthLimits) error
- func WriteMovementContext(w io.Writer, c MovementContext, l WorkloadLimits) error
- func WriteOTLPLogs(w io.Writer, readings []Reading, o ExportOptions) error
- func WriteOTLPMetrics(w io.Writer, readings []Reading, o ExportOptions) error
- func WriteOperatorCPUContext(w io.Writer, c OperatorCPUContext, l WorkloadLimits) error
- func WriteOperatorContext(w io.Writer, c OperatorContext, l WorkloadLimits) error
- func WriteRetentionRecoveryManifest(w io.Writer, m RetentionRecoveryManifest) error
- func WriteServingContext(w io.Writer, c ServingContext, l WorkloadLimits) error
- func WriteServingContextV2(w io.Writer, c ServingContextV2, l WorkloadLimits) error
- func WriteTrainingCheckpointContext(w io.Writer, c TrainingCheckpointContext, l WorkloadLimits) error
- func WriteTrainingContext(w io.Writer, c TrainingContext, l WorkloadLimits) error
- func WriteTrainingPhaseContext(w io.Writer, c TrainingPhaseContext, l WorkloadLimits) error
- func WriteTrainingWorkloadOTLP(w io.Writer, e WorkloadExport, o TrainingWorkloadOTLPOptions) error
- func WriteWorkloadOTLP(w io.Writer, before, after WorkloadExport, o WorkloadOTLPOptions) error
- type AccountingAllocation
- type AccountingClock
- type AccountingEnergy
- type AccountingIdle
- type AccountingInput
- type AccountingNode
- type AccountingNodeTotal
- type AccountingRate
- type AccountingReport
- type AccountingShare
- type AccountingWork
- type Applicability
- type Architecture
- type ArmCheck
- type ArmObserver
- func NewArmObserver(dev ArmObserverDevice, uuid string, cfg MonitorConfig, ...) *ArmObserver
- func OpenArmObserver(index uint32, cfg MonitorConfig, owned func(pid uint32) bool) (*ArmObserver, error)
- func OpenArmObserverPCI(busID string, cfg MonitorConfig, owned func(pid uint32) bool) (*ArmObserver, error)
- type ArmObserverDevice
- type AttributionRead
- type AttributionRefresher
- func (a *AttributionRefresher) Close() error
- func (a *AttributionRefresher) Ready() bool
- func (a *AttributionRefresher) Resolve(proc EntityProcess, deviceUUID string, at int64) JobAttributionResult
- func (a *AttributionRefresher) Run(ctx context.Context) error
- func (a *AttributionRefresher) Status() RefreshStatus
- func (a *AttributionRefresher) Step(ctx context.Context) error
- type BenchmarkCorrelation
- type BenchmarkOptions
- type BenchmarkRecord
- type Binding
- type Bridge
- type BridgeOptions
- type CalibratedClock
- type Candidate
- type CapabilitySet
- type CapturePolicy
- type CaptureRegistry
- type CaptureStatus
- type Category
- type Clock
- type ClockDriftError
- type ClockEventReasons
- type ClockMetadata
- type Clocks
- type CollectedXID
- type Collector
- func (c *Collector) InitStream() error
- func (c *Collector) Manifest() *Manifest
- func (c *Collector) Run(ctx context.Context) (*Manifest, error)
- func (c *Collector) Samples() []Sample
- func (c *Collector) SetPhase(name string) error
- func (c *Collector) SetSampleHook(hook func(Sample))
- func (c *Collector) Step(ctx context.Context) error
- func (c *Collector) Stop() (*Manifest, error)
- type CollectorConfig
- type CollectorDaemon
- type CollectorIntervals
- type Column
- type ContendedError
- type DCGMClient
- type DCGMConfig
- type DCGMDevice
- type DCGMField
- type DCGMFieldPolicyV3Binder
- type DCGMFieldPolicyV3Config
- type DCGMFieldPolicyV3Event
- type DCGMFieldPolicyV3Notifications
- func NewDCGMFieldPolicyV3Notifications(handle dcgm.Handle, fieldID uint16, policyID uint64, capacity int) (*DCGMFieldPolicyV3Notifications, error)
- func NewDCGMFieldPolicyV3NotificationsWithBinder(handle dcgm.Handle, fieldID uint16, policyID uint64, capacity int, ...) (*DCGMFieldPolicyV3Notifications, error)
- type DCGMFieldPolicyV3Reader
- type DCGMFieldPolicyV3Source
- type DCGMLimits
- type DCGMNotificationReader
- type DCGMPolicyConfig
- type DCGMPolicyEvent
- type DCGMPolicySource
- type DCGMReadingSource
- type DCGMReport
- type DCGMSampler
- type DDMetricMapping
- type DecodeMatch
- type DecodeOutcome
- type DecodeResult
- type DecodeRule
- type DecodeVariant
- type Delivery
- type DeliveryConfig
- type DeliveryStats
- type DeviceMetadata
- type DeviceProcess
- type DeviceSample
- type DurableDelivery
- func (d *DurableDelivery) Close(ctx context.Context) error
- func (d *DurableDelivery) Done() <-chan struct{}
- func (d *DurableDelivery) Enqueue(ctx context.Context, payload []byte) error
- func (d *DurableDelivery) Recover(ctx context.Context) error
- func (d *DurableDelivery) Stats() DurableDeliveryStats
- type DurableDeliveryConfig
- type DurableDeliveryRecoveryManifest
- type DurableDeliveryStats
- type ECCCounts
- type ECCErrors
- type ECCLocations
- type Element
- type EnergySummary
- type Entity
- type EntityAssignment
- type EntityCache
- func (c *EntityCache) Clear()
- func (c *EntityCache) CompleteJob(owner EntityOwner) error
- func (c *EntityCache) Get(query EntityAssignment, now int64) []EntityAssignment
- func (c *EntityCache) LoadFile(path string, scope EntityCacheScope, now int64) (discarded bool, err error)
- func (c *EntityCache) Put(assignments []EntityAssignment, now int64) error
- func (c *EntityCache) SaveFile(path string) (err error)
- type EntityCacheScope
- type EntityEvaluation
- type EntityExport
- type EntityOwner
- type EntityProcess
- type EntityProvenance
- type EntityResolution
- type EntitySnapshot
- type Entry
- type Envelope
- type Environment
- type EnvironmentReason
- type Error
- type Event
- type ExportOptions
- type ExpositionOptions
- type ExpositionSample
- type Fabric
- type FakeClock
- func (f *FakeClock) Advance(d time.Duration)
- func (f *FakeClock) MonotonicDomain() string
- func (f *FakeClock) MonotonicEpochID() string
- func (f *FakeClock) NowMonotonic() int64
- func (f *FakeClock) NowUnix() int64
- func (f *FakeClock) Provenance() string
- func (f *FakeClock) SetEpochID(id string)
- func (f *FakeClock) StepWall(d time.Duration)
- func (f *FakeClock) WallDomain() string
- type FakeSampler
- type Field
- type FieldSummary
- type Fitness
- type FitnessWant
- type GPUCollection
- type GPUProcess
- type GovernedSampler
- func (s *GovernedSampler) Close(ctx context.Context) error
- func (s *GovernedSampler) Devices() []DeviceMetadata
- func (s *GovernedSampler) Ready(nowNanos, maxAgeNanos int64) error
- func (s *GovernedSampler) Sample(ctx context.Context) (readings []Reading, err error)
- func (s *GovernedSampler) Status() CaptureStatus
- type HealthGPU
- type HealthLimits
- type HealthObservation
- type HealthOptions
- type HealthReport
- type HealthSnapshot
- func JoinNVLinkHealth(s HealthSnapshot, report NVLinkSnapshot, l HealthLimits) (*HealthSnapshot, error)
- func JoinNodeHealth(s HealthSnapshot, n hostmetrics.Snapshot, uuid string, l HealthLimits) (*HealthSnapshot, error)
- func JoinRedfishHealth(s HealthSnapshot, sensor hostmetrics.RedfishSensor, uuid string, ...) (*HealthSnapshot, error)
- func ReadHealthSnapshot(r io.Reader, limits HealthLimits) (*HealthSnapshot, error)
- type HealthSource
- type Histogram
- type HistogramBinding
- type HistogramWindowCoverageStatus
- type HistogramWindowFieldStatus
- type HistogramWindowOptions
- type HistogramWindowPolicy
- type HistogramWindowReason
- type HistogramWindowSource
- type HistogramWindowStatus
- type HistogramWindowSummary
- type IBPortSampler
- type IBSamplerOption
- type Info
- type InfoROM
- type JobAttributionResult
- type JobAttributionSnapshot
- type JobAttributionTable
- func (t *JobAttributionTable) Clear()
- func (t *JobAttributionTable) Refresh(snap JobAttributionSnapshot, now int64) ([]JobAttributionResult, error)
- func (t *JobAttributionTable) Resolve(proc EntityProcess, deviceUUID string, at int64) JobAttributionResult
- func (t *JobAttributionTable) Stats() (entries int, lastRefresh int64, refreshFailures int)
- type Join
- type K8sAttribution
- type K8sAttributionResolver
- type KernelGaps
- type Kind
- type Kmsg
- type KubernetesPods
- type LaunchGaps
- type LaunchKey
- type Link
- type Log
- type MIGDevice
- type ManagedField
- type ManagedImport
- type Manifest
- type Memory
- type MetadataFailure
- type Metric
- type MetricKind
- type MetricsHandler
- type Monitor
- type MonitorConfig
- type MonitorDevice
- type MonitorStats
- type MovementContext
- type MovementEndpoint
- type MovementPath
- type MovementTransfer
- type NCUReport
- type NIXLAgent
- type NIXLAgentInventory
- type NIXLAgentObservation
- type NIXLInventory
- type NIXLInventoryOptions
- type NSysLimits
- type NSysReader
- type NSysReport
- type NSysSource
- type NVLinkConfig
- type NVLinkCounterConfig
- type NVLinkCounterObservation
- type NVLinkCounterReader
- type NVLinkCounterSnapshot
- type NVLinkDevice
- type NVLinkErrorCounterDevice
- type NVLinkObservation
- type NVLinkPeer
- type NVLinkQuery
- type NVLinkReader
- type NVLinkSnapshot
- type NVMLFabricReader
- type NVMLHealthReader
- type NVMLProcessDevice
- type NVMLProcessFact
- type NVMLProcessQuery
- type NVMLProcessSelection
- type NVMLSampler
- type NVMLXIDReader
- type Node
- type Number
- type OTLPClockMetadata
- type OTLPFormat
- type OTLPHistogramReadResult
- type OTLPReadOptions
- type OTLPSourceTime
- type Observation
- type Observer
- type OperatorBinding
- type OperatorCPUContext
- type OperatorContext
- type OperatorGroup
- type OperatorInventory
- type OperatorMember
- type OperatorReference
- type OracleFieldComparison
- type OracleFieldValue
- type OracleSample
- type PCI
- type PhaseMarker
- type Platform
- type PluginDeviceBinding
- type PodEntityMetadata
- type PodResourceAllocation
- type Power
- type ProcEntityFacts
- type ProcEnvironFacts
- type ProcEnvironState
- type Process
- type Provider
- type RawLaunch
- type RawTable
- type Reading
- type ReadingSource
- type RealClock
- type Record
- type RecoveryText
- type RecoveryToken
- type RecoveryTransition
- type RefreshConfig
- type RefreshStatus
- type RemappedRows
- type Result
- type Retention
- type RetentionConfig
- type RetentionRecoveryManifest
- type RetentionStatus
- type RetiredPages
- type Row
- type SMIGPU
- type SMIOption
- type SMIResult
- type Sample
- type SamplePoint
- type Sampler
- type SamplingCoverage
- type ServingAttempt
- type ServingAttemptRef
- type ServingBatch
- type ServingCache
- type ServingCacheUse
- type ServingContext
- type ServingContextSummary
- type ServingContextV2
- type ServingRoute
- type ServingTransferRef
- type SlurmAllocation
- type SlurmAttributionSource
- type SlurmCgroupIdentity
- type SlurmGPUMapping
- type SlurmGRESAllocation
- type Snapshot
- type SourceCell
- type Span
- type SpanWindow
- type StepGroups
- type Store
- type StreamRecord
- type Table
- type Temperature
- type Test
- type Topology
- type TopologyDevice
- type TopologyEdge
- type TrainingCheckpoint
- type TrainingCheckpointContext
- type TrainingContext
- type TrainingContextSummary
- type TrainingOperatorReference
- type TrainingPhase
- type TrainingPhaseContext
- type TrainingQualityPolicy
- type TrainingRecovery
- type TrainingRecoverySummary
- type TrainingStepReport
- type TrainingUpdate
- type TrainingWorkloadOTLPOptions
- type TriggerPolicy
- type UnixTimeMapping
- type Unjoined
- type UnsupportedError
- type Utilization
- type Value
- type Warning
- type WindowOptions
- type WindowSummary
- type WorkloadAnnotation
- type WorkloadDelta
- type WorkloadExport
- func ReadClearMLScalars(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, error)
- func ReadMLflowHistory(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, error)
- func ReadServingExposition(ctx context.Context, r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, error)
- func ReadWandBHistory(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, error)
- func StampWorkloadSnapshot(e WorkloadExport, nanos int64, domain, epoch string) (WorkloadExport, error)
- type WorkloadHTTPResult
- func FetchClearMLScalarPages(ctx context.Context, client *http.Client, request *http.Request, ...) ([]WorkloadHTTPResult, error)
- func FetchMLflowHistoryPages(ctx context.Context, client *http.Client, request *http.Request, ...) ([]WorkloadHTTPResult, error)
- func FetchWorkload(ctx context.Context, client *http.Client, request *http.Request, ...) (WorkloadHTTPResult, error)
- type WorkloadLimits
- type WorkloadMetric
- type WorkloadOTLPOptions
- type WorkloadRefresher
- func (w *WorkloadRefresher) Close() error
- func (w *WorkloadRefresher) Latest(now int64) (WorkloadHTTPResult, bool)
- func (w *WorkloadRefresher) Ready() bool
- func (w *WorkloadRefresher) Run(ctx context.Context) error
- func (w *WorkloadRefresher) Status() RefreshStatus
- func (w *WorkloadRefresher) Step(ctx context.Context) error
- type WorkloadSource
- type Writer
- func (w *Writer) BytesWritten() int
- func (w *Writer) FamilyLoss() map[string]tracecontract.Loss
- func (w *Writer) LostRecords() uint64
- func (w *Writer) RecordDrop() error
- func (w *Writer) WriteManifest(m *Manifest) error
- func (w *Writer) WritePhase(p *PhaseMarker) error
- func (w *Writer) WriteSample(s *Sample) (err error)
- type XIDLogFormat
- type XIDLogOptions
- type XIDLogReader
- type XIDLogSource
- type XIDNotification
- type XIDNotifications
- type XIDSource
Examples ¶
- Package (Bridge)
- Package (Ncu)
- Package (Nsys)
- Package (Nvidiasmi)
- Package (Xidlog)
- AccountEnergy
- AccountEnergy (CostOnly)
- AccountTelemetry
- AccountingIdle
- AccountingNode
- AdaptNVMLProcesses
- AggregateHistogramWindow (CumulativeDifference)
- AggregateHistogramWindow (Delta)
- AggregateHistogramWindow (Unsupported)
- AggregateWindowStrict (Units)
- AnalyzeLaunchGaps
- Applicability
- AttributionRefresher
- CapturePolicy.Validate
- CaptureRegistry.NewSampler
- CheckFitness
- Column
- ComposeEntityAssignment
- CounterWorkloadWindow
- DCGMExporterFields
- DCGMIMEXFields
- DCGMPolicySource.Close
- DCGMSampler.Close
- DecodeMatch
- DecodeOutcome
- DecodeResult
- DecodeRule
- DecodeRules
- DecodeSources
- DecodeVariant
- DecodeXID
- Delivery.Done
- EntityCache.CompleteJob
- EntityCache.LoadFile
- EntityCache.SaveFile
- EntityCacheScope
- EvaluateEntityResolutions
- Event
- ExactWorkloadJoin
- FakeSampler
- FetchClearMLScalarPages
- FetchMLflowHistoryPages
- FetchManaged
- FetchWorkload
- FormatDDMappingMarkdown
- GovernedSampler
- GovernedSampler.Close
- GovernedSampler.Devices
- GovernedSampler.Ready
- GovernedSampler.Sample
- GovernedSampler.Status
- HealthSnapshot.Validate
- HealthSource.QueryStale
- Histogram
- HistogramWorkloadWindow
- IBPortSampler
- ImportNCU
- ImportNSys
- InspectTrainingSteps
- IntegratePowerToEnergy (TimeOrder)
- JobAttributionTable
- Join
- JoinNVLinkHealth
- JoinNodeHealth
- JoinRedfishHealth
- JudgeArms
- K8sAttributionResolver.LookupGPU
- Kind.String
- Kmsg
- Lookup
- LookupMetricUnit
- LookupProduct
- LookupRaw
- MetricsHandler
- MetricsHandler.Invalidate
- MetricsHandler.Ready
- MetricsHandler.ServeHTTP
- MetricsHandler.Update
- Monitor.Window
- NSysLimits
- NSysReader
- NSysReport
- NSysSource
- NVLinkCounterReader.Read
- NVLinkCounterReadings
- NVLinkCounterSnapshot.Validate
- NVLinkReader.Read
- NVLinkSnapshot.Validate
- NVMLFabricReader.Read
- NVMLHealthReader.Read
- NVMLXIDReader.Close
- NVMLXIDReader.Poll
- NewDCGMFieldPolicyV3Source
- NewDCGMPolicySource
- NewDCGMSampler
- NewDelivery
- NewDurableDelivery
- NewEntityCache
- NewLogsDelivery
- NewLogsDurableDelivery
- NewMetricsHandler
- NewNVLinkCounterReader
- NewNVLinkReader
- NewNVMLFabricReader
- NewNVMLHealthReader
- NewNVMLXIDReader
- NewReader
- Number
- Observation
- Observer
- OpenDCGMClient
- OpenRetention
- OperatorCPUContext
- ParseKmsg
- ParseRecoveryTransition
- ParseSMIXML
- ParseSlurmCgroupPath
- ParseText
- ParseTopology
- Provider
- QueryCSV
- QueryNVMLProcesses
- ReadAccounting
- ReadCapturePolicy
- ReadClearMLScalars
- ReadDCGMJSON
- ReadEntityExport
- ReadExposition
- ReadHealthSnapshot
- ReadKubernetesPodsJSON
- ReadMLflowHistory
- ReadManaged
- ReadManaged (FloatingSentinel)
- ReadMovementContext
- ReadNCU
- ReadNVLinkCounterSnapshot
- ReadNVLinkSnapshot
- ReadOTLPHistogramMetrics
- ReadOperatorCPUContext
- ReadOperatorContext
- ReadPodResourcesJSON
- ReadProcEntity
- ReadProcEntity (NonLive)
- ReadProcEnviron
- ReadPyTorchAnnotations
- ReadPyTorchAnnotations (Cpu210)
- ReadRaw
- ReadServingContext
- ReadServingContextV2
- ReadServingExposition
- ReadServingExposition (RayMemoryUnits)
- ReadServingExposition (VllmV1)
- ReadSlurmAttributionSnapshot
- ReadTrainingCheckpointContext
- ReadTrainingContext
- ReadTrainingPhaseContext
- ReadWandBHistory
- ReadXIDNotifications
- RecognizeRecoveryText
- Record
- RecoverRetention
- RecoveryText
- RecoveryToken
- RecoveryTransition
- Reset
- ResolvePodResourceAssignments
- ResolveSlurmAssignments
- Retention.Close
- Retention.Status
- Retention.Store
- RunSMI
- RuntimeLoadFromExposition
- SafeCaptureLabels
- SamplingCoverage
- ServingContextV2.V1
- SourceCell
- Stable
- StampWorkloadSnapshot
- StepGroups
- SummarizeNIXLInventory
- SummarizeServingContext
- SummarizeTrainingContext
- SummarizeTrainingRecovery
- Table
- TrainingCheckpoint
- TrainingCheckpointContext
- TrainingRecovery
- TrainingRecoverySummary
- TrainingWorkloadOTLPOptions
- TransitionEntityAssignment
- TriggerPolicy.Matches
- Unjoined
- ValidateReadingSource
- Value.Float
- Value.IntList
- WorkloadRefresher
- WriteAccounting
- WriteAccountingReport
- WriteDCGMFieldPolicyV3Event
- WriteDCGMPolicyEvent
- WriteExposition
- WriteHealthSnapshot
- WriteMovementContext
- WriteOTLPLogs
- WriteOTLPLogs (SuppliedEvent)
- WriteOTLPMetrics
- WriteOperatorCPUContext
- WriteOperatorContext
- WriteServingContext
- WriteTrainingCheckpointContext
- WriteTrainingContext
- WriteTrainingPhaseContext
- WriteTrainingWorkloadOTLP
- WriteTrainingWorkloadOTLP (Mlflow)
- WriteWorkloadOTLP
- Writer.FamilyLoss
- XIDLogFormat
- XIDLogOptions
- XIDLogReader.Next
- XIDLogSource
Constants ¶
const ( EnvironmentClear = "clear" EnvironmentVoid = "void" EnvironmentUnchecked = "unchecked" )
Environment states.
const ( EnvForeignProcess = "foreign_process" // a process the caller does not own held a context EnvClockReason = "clock_reason" // the driver reported a clock-reducing event EnvClockSpread = "clock_spread" // SM clocks differed between arms by more than the tolerance EnvUnread = "unread" // evidence is missing or too thin to judge )
Kinds of EnvironmentReason. The first three void a comparison; EnvUnread leaves it unchecked.
const ( Version = 1 KeySize = 4 MaxDevices = 8 MaxReadings = 128 HeaderSize = 208 DeviceSize = 256 ReadingSize = 256 ValueSize = HeaderSize + MaxDevices*DeviceSize + MaxReadings*ReadingSize )
Layout defines a single-key, non-per-CPU BPF_MAP_TYPE_HASH snapshot.
const ( MetricNVLinkDLReplayErrors = "nvlink_dl_replay_errors" MetricNVLinkDLRecoveryErrors = "nvlink_dl_recovery_errors" MetricNVLinkDLCRCFlitErrors = "nvlink_dl_crc_flit_errors" MetricNVLinkDLCRCDataErrors = "nvlink_dl_crc_data_errors" MetricNVLinkDLECCDataErrors = "nvlink_dl_ecc_data_errors" NVLinkErrorCounterAPI = "nvmlDeviceGetNvLinkErrorCounter" )
Raw cumulative NVLink error-count metrics. These are not byte traffic, throughput or congestion measurements. Reset coverage remains unknown.
const ( PrometheusText004 = "prometheus-0.0.4" OpenMetrics100 = "openmetrics-1.0.0" )
const ( DefaultMonitorPeriod = 20 * time.Millisecond MinMonitorPeriod = 5 * time.Millisecond )
Monitor periods.
const ( ReasonNoSamples = "no_samples" ReasonInvalidWindow = "invalid_window" )
Window unavailable reasons.
const ( NCUSchemaVersion = 1 ToolVersion = "2026.3.0.0" // Format selects the release-pinned NVIDIA details CSV header profile. NCUFormat = "ncu-details-csv-2026.3.0" // MaxBytes bounds encoded envelopes and total candidate image bytes. MaxNCUBytes = 32 << 20 // MaxRows bounds CSV records and explicit launch bindings. MaxRows = 65536 )
const ( SchemaVersionLegacy = 1 SchemaVersionV2 = 2 SchemaVersionV3 = 3 SchemaVersionV4 = 4 SchemaVersionV5 = 5 TelemetrySchemaVersion = SchemaVersionV2 CollectorVersion = "nvtelemetry-2.0.0" )
const ( MetricGPUUtilization = "gpu_utilization_pct" MetricMemoryUtilization = "memory_utilization_pct" MetricMemoryUsedBytes = "memory_used_bytes" MetricMemoryTotalBytes = "memory_total_bytes" MetricPowerUsageMW = "power_milliwatts" MetricTotalEnergyMJ = "total_energy_millijoules" MetricTemperatureC = "temperature_celsius" MetricSMClockMHz = "sm_clock_mhz" MetricMemoryClockMHz = "memory_clock_mhz" MetricClocksEventReasons = "clocks_event_reasons" MetricSMActivity = "sm_activity_pct" MetricTensorActivity = "tensor_activity_pct" MetricDRAMActivity = "dram_activity_pct" MetricPCIeRxBytesPerSec = "pcie_rx_bytes_per_sec" MetricPCIeTxBytesPerSec = "pcie_tx_bytes_per_sec" MetricNVLinkRxBytesPerSec = "nvlink_rx_bytes_per_sec" MetricNVLinkTxBytesPerSec = "nvlink_tx_bytes_per_sec" MetricThrottleReasons = "throttle_reasons" MetricPCIERxBytes = "pcie_rx_bytes" MetricPCIETxBytes = "pcie_tx_bytes" MetricXIDEvent = "xid_event" )
Metric names.
const ( UnitPercent = "percent" UnitBytes = "bytes" UnitBytesPerSec = "bytes_per_sec" UnitMilliwatts = "milliwatts" UnitMillijoules = "millijoules" UnitCelsius = "celsius" UnitMHz = "mhz" UnitBitmask = "bitmask" UnitJoules = "joules" UnitSeconds = "seconds" )
Canonical units.
const ( EvidenceMeasured = "measured" EvidenceDerived = "derived" )
Evidence classes.
const ( ReasonUnsupported = "unsupported" ReasonPermissionDenied = "permission_denied" ReasonGPULost = "gpu_lost" ReasonBlank = "blank" ReasonStale = "stale" ReasonQueryFailure = "query_failure" ReasonGapExceeded = "gap_exceeded" ReasonCounterReset = "counter_reset" ReasonZeroTokens = "zero_tokens" ReasonMisalignedClock = "misaligned_clock" ReasonIntegerPrecision = "integer_not_exactly_representable_as_float64" // ReasonMissingCounterMetadata marks a V3 counter reading whose // observation is absent or has no kind, so it cannot be read as a counter. ReasonMissingCounterMetadata = "missing_counter_metadata" )
Unavailable reasons.
const ( MIGScopeDisabled = "disabled" MIGScopePhysicalParent = "physical_parent" MIGScopeMIGInstance = "mig_instance" MIGScopeUnsupported = "unsupported" MIGScopePermissionDenied = "permission_denied" MIGScopeUnknown = "unknown" )
MIG scope constants.
const ( DeviceStatusOk = "ok" DeviceStatusUnidentifiable = "unidentifiable" )
Device status constants.
const ( CapabilityQueryable = "queryable" CapabilityUnsupported = "unsupported" CapabilityPermissionDenied = "permission_denied" CapabilityUnknown = "unknown" )
Field capability constants.
const ( PhaseWarmup = "warmup" PhaseMeasurement = "measurement" PhaseCooldown = "cooldown" )
Standard phase names.
const ( BudgetPolicyFail = "fail" BudgetPolicyDrop = "drop" BudgetExceededFail = BudgetPolicyFail BudgetExceededDrop = BudgetPolicyDrop )
Budget policy options.
const ( MaxRecordBytes = 64 << 10 MaxXIDLogBytes = 16 << 20 MaxRecords = 4096 )
const AggregationDelta = "delta"
AggregationDelta is the WindowSummary aggregation of a cumulative counter.
const DCGMFieldPolicyV3Schema = "nvtelemetry.dcgm-field-policy.v3"
DCGMFieldPolicyV3Schema identifies the separately versioned DCGM 4.7+ field-policy v3 diagnostic event record.
const DefaultClockTolerance = 0.02
DefaultClockTolerance is the relative SM clock spread Stable allows by default.
const DefaultGroupPeriods = 5
DefaultGroupPeriods is the shortest window, in sampling periods, a StepGroups with no minimum of its own closes.
const DefaultMetricRegistryVersion = "2026.10-v4"
DefaultMetricRegistryVersion is the current version of the metric definitions dictionary.
const DefaultMonitorCapacity = 4096
DefaultMonitorCapacity is the number of samples a Monitor retains by default: about 82 seconds at DefaultMonitorPeriod.
const DurableDeliveryRecoverySchemaVersion = 1
DurableDeliveryRecoverySchemaVersion identifies the recovery manifest schema for DurableDelivery.
const MaxRecoveryMessageBytes = 4096
MaxRecoveryMessageBytes bounds a single XID154 message, including its prefix.
const NIXLTelemetryBuild = "7077d029467a02d6f5b23e7eb2de244dec8a0b6a"
NIXLTelemetryBuild is the source profile used for the staging-drop counter and buffer-full behavior below. Other builds retain unknown semantics.
const RetentionRecoverySchemaVersion = 1
RetentionRecoverySchemaVersion identifies the recovery manifest schema for Retention.
const Retrieved = "2026-10-06"
Retrieved records when the workbook was retrieved.
const SourceSHA256 = "7f70ce9684be0c9d98a367770341ccc1d8bca4465cebe42dab7e23d57df5d5a5"
SourceSHA256 is the version identity of the imported workbook.
const SourceURL = "https://docs.nvidia.com/deploy/xid-errors/_downloads/4586dadb59119a55d1e93a181caa4272/Xid-Catalog.xlsx"
SourceURL identifies the imported workbook.
WindowSampleValuesUnavailable marks withheld integer extrema and endpoints.
Variables ¶
var ( ErrLayout = errors.New("incompatible telemetry map layout") ErrSnapshot = errors.New("invalid telemetry map snapshot") ErrStale = errors.New("stale telemetry map snapshot") ErrClosed = errors.New("telemetry bridge closed") )
var ( ErrInvalidArgument = errors.New("nvidia-smi: invalid argument or flag") // 2 ErrNotSupported = errors.New("nvidia-smi: operation not available on device") // 3 ErrNotFound = errors.New("nvidia-smi: object not found") // 6 ErrDriverNotLoaded = errors.New("nvidia-smi: NVIDIA driver is not loaded") // 9 ErrGPULost = errors.New("nvidia-smi: GPU has fallen off the bus") // 15 ErrUnknown = errors.New("nvidia-smi: other error or internal driver error") // 255 )
Errors matched by Error through errors.Is, one per exit status documented in the RETURN VALUE section of nvidia-smi(1) (https://docs.nvidia.com/deploy/nvidia-smi/index.html). An Error with exit status 4 also matches fs.ErrPermission.
var ( ErrBudgetExceeded = errors.New("telemetry budget exceeded") ErrUnsupportedSchema = errors.New("unsupported schema version") ErrTruncatedRecord = errors.New("truncated telemetry record") ErrMalformedStream = errors.New("malformed telemetry stream") ErrIdentityMismatch = errors.New("device identity mismatch in stream") ErrUnidentifiableDevice = errors.New("unidentifiable device: missing or unassigned device UUID") ErrBitmaskAveragingRefused = errors.New("refusing to average bitmask or event metric") )
Stream errors.
var ControlNodes = []string{"/dev/nvidiactl", "/dev/nvidia-uvm", "/dev/nvidia-uvm-tools"}
ControlNodes are the nodes every CUDA process needs besides its GPU's own.
var DDMetricMappings = []DDMetricMapping{
{"gpu.sm_utilization", "hw.gpu.utilization", "1", "gauge", "percent × 0.01"},
{"gpu.sm_active", "hw.gpu.sm.active", "1", "gauge", "percent × 0.01"},
{"gpu.sm_occupancy", "hw.gpu.sm.occupancy", "1", "gauge", "percent × 0.01"},
{"gpu.tensor_active", "hw.gpu.pipe.utilization", "1", "gauge", "percent × 0.01, pipe=tensor"},
{"gpu.dram_active", "hw.gpu.memory.bandwidth.utilization", "1", "gauge", "percent × 0.01"},
{"gpu.clock.speed.sm", "hw.gpu.clock.frequency", "MHz", "gauge", ""},
{"gpu.clock.speed.sm.max", "hw.gpu.clock.frequency.max", "MHz", "gauge", ""},
{"gpu.clock.throttled_while_active", "hw.gpu.clock.throttle", "1", "gauge", ""},
{"gpu.clock.throttle_reasons.*", "hw.gpu.clock.throttle.bitmask", "1", "gauge", "combine reason series using their NVML bit positions"},
{"gpu.power.usage", "hw.power", "W", "gauge", "mW × 0.001"},
{"gpu.power.management_limit", "hw.power.limit", "W", "gauge", "mW × 0.001"},
{"gpu.total_energy_consumption", "hw.energy", "J", "sum", "mJ × 0.001"},
{"gpu.temperature", "hw.temperature", "Cel", "gauge", ""},
{"gpu.memory.free", "hw.gpu.memory.usage", "By", "updownsum", "memory.limit minus memory.free"},
{"gpu.memory.limit", "hw.gpu.memory.limit", "By", "updownsum", ""},
{"gpu.memory.bar1.used", "hw.gpu.memory.bar1.usage", "By", "gauge", ""},
{"gpu.memory.bar1.total", "hw.gpu.memory.bar1.limit", "By", "gauge", ""},
{"gpu.errors.xid.total", "hw.gpu.xid.errors", "{error}", "sum", "Agent observation epoch"},
{"gpu.errors.ecc.uncorrected.total", "hw.errors", "{error}", "sum", ""},
{"gpu.remapped_rows.correctable", "hw.gpu.memory.remapped_rows", "1", "gauge", ""},
{"gpu.remapped_rows.failed", "hw.gpu.memory.remapped_rows.status", "1", "gauge", ""},
{"gpu.ecc.repair_pending.channel", "hw.gpu.memory.repair.pending", "1", "gauge", ""},
{"gpu.nvlink.throughput.raw.rx.total", "hw.gpu.nvlink.io", "By/s", "gauge", "receive rate, kBy/s × 1000"},
{"gpu.nvlink.throughput.raw.tx.total", "hw.gpu.nvlink.io", "By/s", "gauge", "transmit rate, kBy/s × 1000"},
{"gpu.nvlink.count.active", "hw.gpu.nvlink.links", "1", "gauge", ""},
{"gpu.nvlink.errors.replay", "hw.gpu.nvlink.errors", "{error}", "sum", ""},
{"gpu.nvlink.errors.symbol", "hw.gpu.nvlink.signal_errors", "{error}", "sum", ""},
{"gpu.pci.throughput.rx", "hw.gpu.io", "By", "sum", "requires integration over measured intervals, receive"},
{"gpu.pci.throughput.tx", "hw.gpu.io", "By", "sum", "requires integration over measured intervals, transmit"},
{"gpu.pci.replay_counter", "hw.gpu.pcie.replays", "1", "sum", ""},
{"gpu.pci.link.speed.current", "hw.gpu.pcie.link.generation", "1", "gauge", "requires link width and known speed-to-generation table"},
{"gpu.pci.link.width.current", "hw.gpu.pcie.link.width", "1", "gauge", ""},
{"gpu.pci.link.speed.degraded", "hw.gpu.pcie.link.degraded", "1", "gauge", ""},
{"gpu.c2c.errors.interrupt", "hw.gpu.c2c.errors", "{error}", "sum", "error class=interrupt"},
{"gpu.c2c.errors.replay", "hw.gpu.c2c.errors", "{error}", "sum", "error class=replay"},
{"gpu.c2c.errors.replay.b2b", "hw.gpu.c2c.errors", "{error}", "sum", "error class=back-to-back replay"},
{"gpu.process.sm_active", "hw.gpu.process.utilization", "1", "gauge", "percent × 0.01"},
{"gpu.process.memory.usage", "hw.gpu.process.memory.usage", "By", "gauge", ""},
}
DDMetricMappings lists projections from the Datadog Agent GPU metric spec. A trailing .* selects a family of input series for a derived metric.
var ErrDCGMFieldPolicyV3SourceClosed = errors.New("dcgm field policy v3 source: closed or uninitialized")
ErrDCGMFieldPolicyV3SourceClosed reports a closed or uninitialized v3 field-policy source.
var ErrDCGMPolicySourceClosed = errors.New("dcgm policy source: closed or uninitialized")
ErrDCGMPolicySourceClosed reports an uninitialized source.
var ErrDeliveryClosed = errors.New("telemetry delivery closed")
ErrDeliveryClosed means shutdown has begun and new batches are refused.
var ErrDeliveryFull = errors.New("telemetry delivery queue full")
ErrDeliveryFull means the outstanding batch or byte budget is exhausted.
var ErrDeliveryIncomplete = errors.New("telemetry delivery incomplete")
ErrDeliveryIncomplete means at least one admitted batch was not fully accepted.
var ErrIncompleteStream = errors.New("incomplete telemetry stream: missing final completeness manifest")
ErrIncompleteStream indicates a stream terminated without its final completeness record.
var ErrOracleDivergence = errors.New("nvtelemetry: oracle field divergence")
ErrOracleDivergence is returned when an nvtelemetry GPU field reading diverges from the nvidia-smi or dcgmi dmon oracle beyond polling tolerance or has a unit-conversion mismatch (such as W vs mW).
var ErrProcEntityNotLive = errors.New("proc entity: process is not live")
ErrUnavailable is returned by Reader for a table absent from the export.
Functions ¶
func APILaunches ¶
APILaunches counts the host calls in api whose names contain one of names, and their total duration.
func AggregateWindow ¶
func AggregateWindow(windowName string, startMono, endMono int64, samples []Sample, opts WindowOptions) ([]WindowSummary, []EnergySummary)
AggregateWindow computes time-weighted summaries for all device metrics within the window [startMono, endMono]. It omits a device/metric group whose units disagree or do not match the registered canonical unit. Unregistered metrics retain their caller-supplied unit, including an empty unit, but every point in a group must use the same unit. No unit conversion is performed. Other groups remain available. AggregateWindowStrict reports unit errors instead.
func AggregateWindowStrict ¶
func AggregateWindowStrict(windowName string, startMono, endMono int64, samples []Sample, opts WindowOptions) ([]WindowSummary, []EnergySummary, error)
AggregateWindowStrict aggregates metrics within the window, returning ErrBitmaskAveragingRefused if any metric has bitmask or event kind. It returns an error for inconsistent units or a registered metric's noncanonical unit. Unregistered metrics must use one consistent caller-supplied unit per group.
Example (Units) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
samples := []telemetry.Sample{{Readings: []telemetry.Reading{{
Name: telemetry.MetricPowerUsageMW, Unit: "W", DeviceUUID: "GPU-example",
Value: 1, Evidence: telemetry.EvidenceMeasured,
}}}}
_, _, err := telemetry.AggregateWindowStrict("measurement", 0, 1, samples, telemetry.WindowOptions{})
fmt.Println(err != nil)
}
Output: true
func ClassifyNVMLError ¶
ClassifyNVMLError translates NVML errors into canonical unavailable reasons.
func ClocksEventReasonNames ¶
ClocksEventReasonNames returns the names of the clocks event reason bits set in mask, in bit order, using nvidia-smi's spellings. A bit with no name is spelled in hexadecimal.
func DispatchDCGMFieldPolicyV3Callback ¶
func DispatchDCGMFieldPolicyV3Callback(violation *dcgm.FieldPolicyViolation, token uint64) int32
DispatchDCGMFieldPolicyV3Callback routes a native or fixture v3 violation callback by its numeric registration token, copying the value before enqueueing.
func DockerArgs ¶
DockerArgs returns docker run arguments that map exactly g's device node and the control nodes read-write and make g the only CUDA device. It sets NVIDIA_VISIBLE_DEVICES=none so the NVIDIA runtime injects driver libraries but no devices of its own.
func Encode ¶
Encode returns the fixed little-endian layout. Unused slots and reserved bytes are zero. IDs, metric names, units and domains are NUL-terminated UTF-8.
func EvaluateSample ¶
func EvaluateSample(sample Sample, policies []TriggerPolicy) (Reading, TriggerPolicy, bool)
EvaluateSample returns the first Reading in sample matching any policy in policies.
func ExactWorkloadJoin ¶
func ExactWorkloadJoin(WorkloadExport) error
ExactWorkloadJoin refuses to turn aggregated exports into individual request or kernel records. Explicit benchmark records use CorrelateBenchmark instead.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
fmt.Println(telemetry.ExactWorkloadJoin(telemetry.WorkloadExport{}))
}
Output: aggregate workload exports cannot establish exact request or kernel joins
func FormatDDMappingMarkdown ¶
FormatDDMappingMarkdown writes the mapping table as Markdown.
Example ¶
var b strings.Builder
if err := FormatDDMappingMarkdown(&b); err != nil {
panic(err)
}
header, _, _ := strings.Cut(b.String(), "\n")
fmt.Println(header)
Output: | Datadog | OTLP | Unit | Type | Conversion |
func FormatOracleComparisonTable ¶
func FormatOracleComparisonTable(hostLabel string, comps []OracleFieldComparison) string
FormatOracleComparisonTable formats the oracle comparison results as a Markdown table.
func LookupMetricKind ¶
LookupMetricKind returns the kind classification for a metric name, and whether it was found.
func LookupMetricUnit ¶
LookupMetricUnit returns the canonical wire unit for name, when specified. An unknown result must not be interpreted as permission to change units.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
unit, ok := telemetry.LookupMetricUnit(telemetry.MetricPowerUsageMW)
fmt.Println(unit, ok)
}
Output: milliwatts true
func LookupProduct ¶
func LookupProduct(id uint64, product Architecture) (Entry, Applicability)
LookupProduct returns the row and its documented product applicability. L4, GB10 and other products without a catalog column are UncoveredProduct; applicability is never inferred from an architecture family.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
entry, coverage := telemetry.LookupProduct(154, "L4")
fmt.Println(entry.Code, coverage == telemetry.UncoveredProduct)
}
Output: 154 true
func MarshalOTLPLogsProto ¶
func MarshalOTLPLogsProto(readings []Reading, o ExportOptions, attribution ...map[string]K8sAttribution) ([]byte, error)
MarshalOTLPLogsProto encodes OTLP diagnostic logs, including XID events. Optional GPU metadata is keyed by device UUID.
func MarshalOTLPMetricsProto ¶
func MarshalOTLPMetricsProto(readings []Reading, o ExportOptions, attribution ...map[string]K8sAttribution) ([]byte, error)
MarshalOTLPMetricsProto encodes OTLP gauges and cumulative monotonic sums. Optional GPU metadata is keyed by device UUID.
func OracleMetricOrder ¶
func OracleMetricOrder() []string
OracleMetricOrder returns the deterministic order of all 12 GPU telemetry fields verified by TestNativeTelemetryDCGMOracle.
func OwnedBy ¶
OwnedBy returns a predicate that claims roots and their descendants, following parent links in the /proc-format file system fsys. A process whose stat file cannot be read is not claimed.
func ParseKubernetesCgroup ¶
ParseKubernetesCgroup extracts an unambiguous Kubernetes pod and runtime ID.
func ParseNvidiaSMIQText ¶
func ParseNvidiaSMIQText(text string, dst *OracleSample)
ParseNvidiaSMIQText extracts PCIe Tx/Rx Throughput (in KB/s -> bytes_per_sec) and Total Energy Consumption (in J or mJ -> millijoules) from `nvidia-smi -q`.
func ProcessEpochID ¶
func ProcessEpochID() string
ProcessEpochID returns the unique process-local monotonic epoch ID.
func QueryCSV ¶
QueryCSV runs nvidia-smi with args (appending "--format=csv,noheader,nounits" when no "--format=" flag is present) and returns trimmed CSV rows. Empty output returns nil, nil. If nvidia-smi exits with a nonzero status, the error is an *Error.
Example ¶
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"runtime"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
if runtime.GOOS == "windows" {
fmt.Println("GPU-0001 NVIDIA GB10")
return
}
dir, err := os.MkdirTemp("", "smi-example-*")
if err != nil {
return
}
defer os.RemoveAll(dir)
fake := filepath.Join(dir, "nvidia-smi")
_ = os.WriteFile(fake, []byte("#!/bin/sh\necho 'GPU-0001, NVIDIA GB10'\n"), 0o755)
rows, err := telemetry.QueryCSV(
context.Background(),
[]string{"--query-gpu=uuid,name"},
telemetry.WithSMIBinary(fake),
telemetry.WithSMIMaxBytes(1<<20),
)
if err == nil && len(rows) > 0 {
fmt.Println(rows[0][0], rows[0][1])
}
}
Output: GPU-0001 NVIDIA GB10
func ReadMovementContext ¶
func ReadMovementContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, MovementContext, error)
ReadMovementContext reads a bounded version 1 movement context with its original bytes and digest. Source must identify application movement-context-v1. Duplicate keys, unknown fields, unsupported versions and enumerations, non-byte units, duplicate transfer IDs, contradictory completion state and unordered times are refused. Supplied identities are retained as supplied; the reader verifies no path, topology or join.
Example ¶
var b bytes.Buffer
if err := telemetry.WriteMovementContext(&b, movementFixture(), telemetry.WorkloadLimits{}); err != nil {
fmt.Println(err)
return
}
_, c, err := telemetry.ReadMovementContext(&b, movementSource(), telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
t := c.Transfers[0]
fmt.Println(t.ID, t.Direction, *t.Bytes, t.Unit, t.State, t.Path.Mechanism)
Output: t1 peer_to_peer 9007199254740993 bytes completed nvlink
func ReadOperatorCPUContext ¶
func ReadOperatorCPUContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, OperatorCPUContext, error)
ReadOperatorCPUContext reads application operator-cpu-context-v1 metadata. It checks bounded strict JSON and the closed raw-hash map, without opening reference locators or parsing another producer's trace. TraceSource must name PyTorch 2.10.0 in the same run; ReadPyTorchAnnotations owns trace validation.
Example ¶
c, source := cpuContextFixture()
var out bytes.Buffer
_ = telemetry.WriteOperatorCPUContext(&out, c, telemetry.WorkloadLimits{})
_, got, err := telemetry.ReadOperatorCPUContext(&out, source, telemetry.WorkloadLimits{})
fmt.Println(got.RunID, got.TraceSource.Version, err)
Output: run 2.10.0 <nil>
func ReadOperatorContext ¶
func ReadOperatorContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, OperatorContext, error)
ReadOperatorContext reads bounded application operator-context-v1 metadata. It preserves original bytes/hash, rejects duplicate/unknown fields and checks raw artifact hashes. Missing or unsupported inventory remains explicitly unknown. It does not authenticate supplied compiler or framework metadata.
Example ¶
var raw bytes.Buffer
if err := telemetry.WriteOperatorContext(&raw, operatorContextFixture(), telemetry.WorkloadLimits{}); err != nil {
panic(err)
}
export, context, err := telemetry.ReadOperatorContext(&raw, operatorSource(), telemetry.WorkloadLimits{})
fmt.Println(err, context.SourceClass, len(context.Groups), len(export.RawSHA256))
Output: <nil> synthetic 0 64
func ReadPyTorchAnnotations ¶
func ReadPyTorchAnnotations(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, []WorkloadAnnotation, error)
ReadPyTorchAnnotations reads complete CPU user_annotation events from PyTorch 2.7.0 and a fixed CPU-only subset of 2.10.0 Chrome exports. The 2.10.0 profile requires schemaVersion 1, present empty deviceProperties, and only user_annotation, cpu_op, Trace, CPU forward/backward flows or uncategorized records. Forward/backward flows remain uninterpreted in Export.Raw. The version is a caller declaration checked for consistency, not producer authentication. Operator records remain in Export.Raw; this does not establish native GPU correlation or compiled member identity. The 2.7.0 raw GPU/flow behavior is unchanged. A bounded profile is not a continuous training or node-health stream.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
source := telemetry.WorkloadSource{Provider: "pytorch", Version: "2.7.0", RunID: "train1"}
raw := `{"traceEvents":[{"name":"train/step","cat":"user_annotation","ph":"X","ts":10,"dur":2,"pid":1,"tid":1}]}`
_, annotations, err := telemetry.ReadPyTorchAnnotations(strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(annotations[0].Name, annotations[0].DurationNanos)
}
Output: train/step 2000
Example (Cpu210) ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
)
func main() {
raw, err := os.ReadFile("testdata/pytorch-2.10.0-cpu-eager.chrome.json")
if err != nil {
fmt.Println(err)
return
}
source := telemetry.WorkloadSource{Provider: "pytorch", Version: "2.10.0", RunID: "retained-cpu-run"}
export, annotations, err := telemetry.ReadPyTorchAnnotations(bytes.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
// These are CPU annotation records, not exact CUDA operation identities.
fmt.Println(len(annotations), len(export.Raw))
fmt.Println(export.RawSHA256 == "fb6a60fc83316a3055d13f46c4f49c962e4e4b11222b52d675eaa0b898cbb2cf")
}
Output: 2 680634 true
func ReadServingContext ¶
func ReadServingContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, ServingContext, error)
ReadServingContext reads version 1 caller-supplied outcomes with bounded original bytes and digest. Supplied identity is not a verified kernel join.
Example ¶
raw := `{"version":1,"run_id":"r","attempts":[]}`
_, c, err := ReadServingContext(strings.NewReader(raw), WorkloadSource{Provider: "application", Version: "1", RunID: "r"}, WorkloadLimits{})
fmt.Println(c.RunID, err)
Output: r <nil>
func ReadServingContextV2 ¶
func ReadServingContextV2(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, ServingContextV2, error)
ReadServingContextV2 reads a bounded version 2 application interchange with its original bytes and digest. Attempts are validated as in version 1. Duplicate keys, unknown fields, other versions, unsupported enumerations, duplicate batch, cache or edge records and unsupported bases are refused. Route records are identified by attempt and frontend, cache uses as ServingCacheUse describes, and transfer references by attempt and transfer ID; basis and evidence are not part of a record's identity. Edge references are retained as supplied, including missing identities.
Example ¶
var b bytes.Buffer
if err := telemetry.WriteServingContextV2(&b, servingContextV2Fixture(), telemetry.WorkloadLimits{}); err != nil {
fmt.Println(err)
return
}
raw := b.Bytes()
_, c, err := telemetry.ReadServingContextV2(bytes.NewReader(raw), servingSource(), telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(c.Attempts), c.Batches[0].ID, len(c.Batches[0].Members), c.Transfers[0].TransferID)
_, _, err = telemetry.ReadServingContext(bytes.NewReader(raw), servingSource(), telemetry.WorkloadLimits{})
fmt.Println(err)
Output: 2 b1 2 t2 decode serving context: json: unknown field "routes"
func ReadStream ¶
ReadStream reads a full JSONL telemetry stream, returning manifest, phases, and samples. It strictly validates schema version, device identities, canonical units, monotonic ordering, and detects truncated records.
func ReadStreamStrict ¶
ReadStreamStrict reads a stream and returns ErrIncompleteStream if the final completeness record is missing.
func ReadTrainingCheckpointContext ¶
func ReadTrainingCheckpointContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, TrainingCheckpointContext, error)
ReadTrainingCheckpointContext reads bounded version 1 supplied observations. It rejects duplicate/unknown fields, missing integer presence, contradictory checkpoint identities, and duplicate rank/state/recovery identities. A partial publication or restore is retained, but cannot qualify a global recovery point.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
raw := `{"version":1,"run_id":"synthetic","checkpoints":[]}`
e, c, err := telemetry.ReadTrainingCheckpointContext(strings.NewReader(raw), telemetry.WorkloadSource{Provider: "application", Version: "synthetic-v1", RunID: "synthetic"}, telemetry.WorkloadLimits{})
fmt.Println(c.RunID, len(e.RawSHA256), err)
}
Output: synthetic 64 <nil>
func ReadTrainingContext ¶
func ReadTrainingContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, TrainingContext, error)
ReadTrainingContext reads version 1 application-supplied optimizer outcomes. It returns original bytes and their digest in the existing workload export. Duplicate JSON keys, unknown fields, repeated rank/step/attempt identities, inconsistent world sizes, and unsupported statuses are refused.
Example ¶
raw := `{"version":1,"run_id":"run","updates":[{"attempt":"first","step":0,"rank":0,"world_size":1,"outcome":"updated","quality":"unknown","evidence":"application-log"}]}`
_, c, err := ReadTrainingContext(strings.NewReader(raw), WorkloadSource{Provider: "application", Version: "1", RunID: "run"}, WorkloadLimits{})
if err != nil {
panic(err)
}
out, _ := SummarizeTrainingContext(c, WorkloadLimits{})
fmt.Println(out.Accepted, out.Unknown)
Output: 0 1
func ReadTrainingPhaseContext ¶
func ReadTrainingPhaseContext(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, TrainingPhaseContext, error)
ReadTrainingPhaseContext reads application training-context-v2 bytes, retaining their original digest. Duplicate/unknown fields, future versions, missing/null integers and noncanonical integer spellings are refused.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
raw := `{"version":2,"run_id":"run","policies":[],"phases":[]}`
_, c, err := telemetry.ReadTrainingPhaseContext(bytes.NewBufferString(raw), telemetry.WorkloadSource{Provider: "application", Version: "training-context-v2", RunID: "run"}, telemetry.WorkloadLimits{})
fmt.Println(c.Version, len(c.Phases), err)
}
Output: 2 0 <nil>
func RecoverDurableDelivery ¶
RecoverDurableDelivery cleans stale writer leases and temporary files after an ungraceful process termination. It validates the private spool directory and owner identity before taking action, and refuses recovery if the lease is actively held by a live writer.
func RecoverRetention ¶
RecoverRetention releases a stale lease only while holding the owner marker's exclusive file lock. Live writers and other recoverers refuse without changing files. Streams and unpublished pending files are preserved. A pending file must be explicitly archived or removed by its owner before reopening. Version 1 or corrupt state refuses unchanged; no process-death inference or migration occurs.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "retention-example-")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
stream, err := os.ReadFile("testdata/canonical_v2.jsonl")
if err != nil {
fmt.Println(err)
return
}
cfg := telemetry.RetentionConfig{Owner: "example", MaxFiles: 1, MaxBytes: int64(len(stream)), MaxStreamBytes: int64(len(stream))}
path := filepath.Join(dir, "owned")
writer, err := telemetry.OpenRetention(path, cfg)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("live recovery refused:", telemetry.RecoverRetention(path, cfg.Owner) != nil)
if err := writer.Close(); err != nil {
fmt.Println(err)
return
}
// Model one unpublished artifact left by an interrupted writer. The writer
// above has actually stopped; recovery never infers death from a PID.
pending := filepath.Join(path, "pending.jsonl")
if err := os.WriteFile(pending, []byte("interrupted bytes"), 0600); err != nil {
fmt.Println(err)
return
}
if err := telemetry.RecoverRetention(path, cfg.Owner); err != nil {
fmt.Println(err)
return
}
_, err = telemetry.OpenRetention(path, cfg)
fmt.Println("pending blocks reopen:", err != nil)
// Preserve this single artifact outside the managed directory. The caller
// owns the archive budget; retention does not create an accumulating archive.
if err := os.Rename(pending, filepath.Join(dir, "preserved.jsonl")); err != nil {
fmt.Println(err)
return
}
writer, err = telemetry.OpenRetention(path, cfg)
if err != nil {
fmt.Println(err)
return
}
if err := writer.Store(1, bytes.NewReader(stream)); err != nil {
writer.Close()
fmt.Println(err)
return
}
fmt.Println("stored:", writer.Status().Files)
fmt.Println("closed:", writer.Close() == nil)
}
Output: live recovery refused: true pending blocks reopen: true stored: 1 closed: true
func Reset ¶
Reset resets the hardware and software state of the GPUs named by ids, by running nvidia-smi --gpu-reset -i with ids joined by commas. It is meant to clear a GPU that would otherwise need a reboot, such as after a double-bit ECC error.
Each id must be a GPU's index ("0"; at most three digits), UUID ("GPU-" and 32 hexadecimal digits with dashes, as in [GPU.UUID]), or PCI bus ID (domain:bus:device.function in hexadecimal, as in [GPU.ID]). Reset returns an error without running nvidia-smi if ids is empty or any id has another form: nvidia-smi resets every GPU when given no -i, and also accepts board serial numbers, which several GPUs on one board can share. Indexes follow the driver's enumeration, which can change across reboots; prefer UUIDs or PCI bus IDs.
nvidia-smi(1) documents these preconditions (https://docs.nvidia.com/deploy/nvidia-smi/index.html):
- It requires root (administrator privileges on Windows).
- No application may be using the GPUs, including CUDA programs, X servers, and monitoring tools such as another nvidia-smi. If the GPUs cannot be reset individually, no compute application may be running on any GPU in the system.
- On pre-Ampere GPUs, and on Ampere NVSwitch systems without a running Fabric Manager, every GPU connected to a reset GPU by NVLink must be reset in the same call; nvidia-smi reports an error naming the missing GPUs otherwise.
- Reset is not supported on MIG-enabled vGPU guests. On Windows it restarts the driver of the named GPUs.
NVIDIA also documents that a reset is not guaranteed to work, is not recommended for production environments, and that each reset GPU's health should be checked before further use, power cycling the node if it is unhealthy. Reset issues nvidia-smi's default function-level reset.
If nvidia-smi exits with a nonzero status, the error is an *Error holding its exit status and output. A GPU in use has no documented exit status of its own; nvidia-smi names the reason in its output. Canceling ctx kills nvidia-smi, which can leave a reset incomplete.
Example ¶
package main
import (
"context"
"errors"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"log"
)
func main() {
// Reset the GPU with this UUID. This needs root and an idle GPU.
err := telemetry.Reset(context.Background(), "GPU-25e04bdf-6a27-0a2d-f989-a9228a03f373")
var e *telemetry.Error
switch {
case errors.As(err, &e):
log.Fatalf("nvidia-smi exited %d: %s%s", e.Code, e.Stdout, e.Stderr)
case err != nil:
log.Fatal(err)
}
}
Output:
func RunSMI ¶
RunSMI runs nvidia-smi with args and returns its standard output. A nonzero exit status is returned as an *Error.
Example ¶
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"runtime"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
if runtime.GOOS == "windows" {
fmt.Println("580.95.05")
return
}
dir, err := os.MkdirTemp("", "smi-run-*")
if err != nil {
return
}
defer os.RemoveAll(dir)
fake := filepath.Join(dir, "nvidia-smi")
_ = os.WriteFile(fake, []byte("#!/bin/sh\nprintf '580.95.05\\n'\n"), 0o755)
out, err := telemetry.RunSMI(
context.Background(),
[]string{"--query-gpu=driver_version", "--format=csv,noheader"},
telemetry.WithSMIBinary(fake),
)
if err == nil {
fmt.Print(string(out))
}
}
Output: 580.95.05
func RuntimeLoadFromExposition ¶
func RuntimeLoadFromExposition(ctx context.Context, r io.Reader, limits WorkloadLimits) (load float64, ok bool, err error)
RuntimeLoadFromExposition parses a Prometheus text 0.0.4 snapshot via ReadExposition and returns the maximum ratio gauge value clamped to [0, 1] for the highest-priority serving load metric present:
- vllm:kv_cache_usage_perc
- vllm:gpu_cache_usage_perc
- sglang:token_usage
- sglang:cache_usage
- dynamo_component_gpu_cache_usage_percent
Returns (0, false, nil) when none of the known gauges are present so callers never confuse an absent reading with a measured 0.0 idle worker.
Example ¶
package main
import (
"context"
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
body := "# TYPE vllm:kv_cache_usage_perc gauge\nvllm:kv_cache_usage_perc{engine=\"0\"} 0.42\n"
load, ok, err := telemetry.RuntimeLoadFromExposition(context.Background(), strings.NewReader(body), telemetry.WorkloadLimits{})
if err != nil {
panic(err)
}
fmt.Printf("ok=%v load=%.2f\n", ok, load)
}
Output: ok=true load=0.42
func SafeCaptureLabels ¶
SafeCaptureLabels selects explicit non-sensitive identity labels before storage/export. It accepts only job_id, namespace, executable and stack_symbol values with a conservative character set. Arbitrary command/environment and diagnostic text are unsupported; this is not general secret detection.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
labels, err := telemetry.SafeCaptureLabels(map[string]string{"job_id": "123", "api_key": "do-not-store"}, []string{"job_id"})
fmt.Println(labels["job_id"], len(labels), err)
}
Output: 123 1 <nil>
func ShortKernels ¶
ShortKernels returns the number and total duration of the kernels in step shorter than maxNS. Such kernels are bound by launch and drain latency, not bandwidth, and keep their duration on a faster device.
func SplitSteps ¶
SplitSteps splits kernels, in start order, into steps that each end with a kernel whose name contains end. Kernels after the last such kernel are dropped: they belong to an unfinished step.
func Stable ¶
func Stable(windows []SpanWindow, tolerance float64) error
Stable reports whether observed SM clock extrema agree within tolerance, a fraction of the lowest reading. Zero tolerance means DefaultClockTolerance. Each window needs at least five samples and five finite positive SM readings, at least 80% effective coverage (window Coverage times the fraction of samples holding SM readings), and available clock event reasons with no active bits. All nonzero masks, including idle, application-clock settings and unknown bits, are conservatively refused. Missing, sparse, idle or throttled evidence does not establish a clock-qualified A/B comparison. A failure is a *ClockDriftError.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
arm := func(sm uint32) telemetry.SpanWindow {
// These summaries stand for measured arm windows with five readings.
return telemetry.SpanWindow{Samples: 5, Coverage: 1, SMClockMHz: telemetry.FieldSummary{Samples: 5, Min: uint64(sm), Max: uint64(sm), Mean: float64(sm)}}
}
// ABBA: arm B ran 3% slower clocks than arm A.
a, b := arm(2040), arm(1980)
fmt.Println(telemetry.Stable([]telemetry.SpanWindow{a, b, b, a}, 0))
fmt.Println(telemetry.Stable([]telemetry.SpanWindow{a, b, b, a}, 0.05))
}
Output: sm clock spread 3.03% exceeds 2.00%: window 1 at 1980 MHz, window 0 at 2040 MHz <nil>
func StepGaps ¶
StepGaps returns the idle time between consecutive steps: from the end of each step's last kernel to the start of the next step's first. It is the host's turnaround between steps (synchronization, copies, parameter updates and the next launch), which no kernel overlaps.
func TransitionEntityAssignment ¶
func TransitionEntityAssignment(previous, next EntityAssignment, at int64) (EntityAssignment, EntityAssignment, error)
TransitionEntityAssignment splits a relationship at an explicitly observed reassignment, process restart/exec or sharing-configuration change. The caller supplies the observation; a new owner or PID alone does not invent its time. The device and clock must be unchanged. Observations at the prior start cannot produce a nonempty historical interval and are refused.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
previous := telemetry.EntityAssignment{Device: telemetry.DeviceMetadata{UUID: "GPU-a"}, Owner: telemetry.EntityOwner{PodUID: "uid-a"}, Source: "allocation_export", SourceRevision: "fixture-v1", Authoritative: true, State: "assigned", ClockDomain: "monotonic", ClockEpoch: "boot-a", EndNanos: 100, Sharing: "unknown"}
next := previous
next.Owner.PodUID = "uid-b"
next.EndNanos = 200
old, current, err := telemetry.TransitionEntityAssignment(previous, next, 50)
if err != nil {
panic(err)
}
fmt.Println(old.EndNanos, current.StartNanos, current.Owner.PodUID)
}
Output: 50 50 uid-b
func ValidateDurableDeliveryRecoveryManifest ¶
func ValidateDurableDeliveryRecoveryManifest(m DurableDeliveryRecoveryManifest) error
ValidateDurableDeliveryRecoveryManifest checks schema version, marker version, owner identity, and bounds.
func ValidateMetricAveraging ¶
ValidateMetricAveraging verifies whether a metric may be summarized using numeric averaging. Bitmask and event metrics are rejected because numeric averages across discrete bit patterns or error event codes are mathematically invalid.
func ValidateReadingSource ¶
func ValidateReadingSource(s *ReadingSource) error
ValidateReadingSource checks the bounded additive source contract.
Example ¶
fmt.Println(ValidateReadingSource(nil))
Output: <nil>
func ValidateRetentionRecoveryManifest ¶
func ValidateRetentionRecoveryManifest(m RetentionRecoveryManifest) error
ValidateRetentionRecoveryManifest checks schema version, marker version, owner identity, and bounds.
func WriteAccounting ¶
func WriteAccounting(w io.Writer, in AccountingInput) error
WriteAccounting validates and writes a versioned input suitable for ReadAccounting. It does not persist data, bill a customer, or change rates.
Example ¶
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
)
func main() {
raw, err := os.ReadFile("testdata/accounting_v1.json")
if err != nil {
panic(err)
}
var input telemetry.AccountingInput
json.Unmarshal(raw, &input)
var wire bytes.Buffer
err = telemetry.WriteAccounting(&wire, input)
report, readErr := telemetry.ReadAccounting(&wire, 1<<20)
fmt.Println(report.Shares[0].RoundedMinor, err, readErr)
}
Output: 150 <nil> <nil>
func WriteAccountingReport ¶
func WriteAccountingReport(w io.Writer, report AccountingReport) error
WriteAccountingReport writes a model-only result, including its input provenance. CostMajor is exact; RoundedMinor uses half-even currency rounding.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"io"
"os"
)
func main() {
raw, err := os.ReadFile("testdata/accounting_v1.json")
if err != nil {
panic(err)
}
report, err := telemetry.ReadAccounting(bytes.NewReader(raw), 1<<20)
fmt.Println(err, telemetry.WriteAccountingReport(io.Discard, report))
}
Output: <nil> <nil>
func WriteDCGMFieldPolicyV3Event ¶
func WriteDCGMFieldPolicyV3Event(w io.Writer, e DCGMFieldPolicyV3Event) error
WriteDCGMFieldPolicyV3Event validates and writes one JSON diagnostic line. Lines exceeding 16384 encoded bytes are refused before writing.
Example ¶
err := WriteDCGMFieldPolicyV3Event(io.Discard, DCGMFieldPolicyV3Event{})
fmt.Println(err != nil)
Output: true
func WriteDCGMPolicyEvent ¶
func WriteDCGMPolicyEvent(w io.Writer, e DCGMPolicyEvent) error
WriteDCGMPolicyEvent writes one bounded diagnostic JSON line. It does not translate opaque union payloads into normalized health, logs or metrics.
Example ¶
err := WriteDCGMPolicyEvent(io.Discard, DCGMPolicyEvent{})
fmt.Println(err != nil)
Output: true
func WriteDurableDeliveryRecoveryManifest ¶
func WriteDurableDeliveryRecoveryManifest(w io.Writer, m DurableDeliveryRecoveryManifest) error
WriteDurableDeliveryRecoveryManifest validates and writes one JSON recovery manifest line.
func WriteEntityExport ¶
func WriteEntityExport(w io.Writer, e EntityExport) error
WriteEntityExport validates and writes a bounded version 1 document.
func WriteExposition ¶
func WriteExposition(w io.Writer, readings []Reading, o ExportOptions) error
WriteExposition emits canonical-unit private metrics and explicit availability gauges. Evidence and reported producer/backend metadata use at most 16 fixed labels; raw source IDs and labels are omitted. Clock presence flags distinguish known zero from unknown; numeric clock bounds remain in diagnostic JSON or OTLP. Reported native origin does not establish independent acquisition. The fixed exposition profile has device scope; entity-assigned readings require OTLP.
Example ¶
var b bytes.Buffer
e := WriteExposition(&b, []Reading{{Name: "power_milliwatts", Unit: "milliwatts", DeviceUUID: "GPU-a", Evidence: EvidenceMeasured, IsInt: true, IntValue: 12500}}, ExportOptions{})
fmt.Print(b.String())
fmt.Println(e)
Output: # TYPE nvtelemetry_power_milliwatts gauge # TYPE nvtelemetry_power_milliwatts_available gauge nvtelemetry_power_milliwatts{device_uuid="GPU-a",evidence="measured",export_schema="metrics.v1",backend_status="unknown",source_status="unknown",native_origin_status="unknown",clock_domain_known="false",sensor_timestamp_known="false",wall_uncertainty_known="false",calibration_known="false"} 12500 nvtelemetry_power_milliwatts_available{device_uuid="GPU-a",evidence="measured",export_schema="metrics.v1",backend_status="unknown",source_status="unknown",native_origin_status="unknown",clock_domain_known="false",sensor_timestamp_known="false",wall_uncertainty_known="false",calibration_known="false"} 1 <nil>
func WriteHealthSnapshot ¶
func WriteHealthSnapshot(w io.Writer, s HealthSnapshot, limits HealthLimits) error
WriteHealthSnapshot validates and writes one bounded bundle. It rejects short writes; callers own the writer and its retention policy.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func exampleHealth() (telemetry.HealthSnapshot, telemetry.HealthLimits) {
limits := telemetry.HealthLimits{MaxBytes: 4096, MaxDevices: 1, MaxSources: 1, MaxObservations: 4, MaxEdges: 1}
s := telemetry.HealthSnapshot{
Version: 1, NodeID: "node-0", TopologyEpoch: "topology-1", ClockDomain: "synthetic", ClockEpoch: "fixture-1", AtNanos: 10,
DeviceStates: map[string]string{"GPU-0": "present"},
Sources: []telemetry.HealthSource{{ID: "nvml", Kind: "nvml", Version: "fixture-v1", State: "available", HasLastSuccess: true, LastSuccessNanos: 10}},
Observations: []telemetry.HealthObservation{{SourceID: "nvml", Class: "raw", Reading: telemetry.Reading{
Name: telemetry.MetricTemperatureC, Unit: telemetry.UnitCelsius, Backend: "nvml", DeviceUUID: "GPU-0", Evidence: telemetry.EvidenceMeasured, Value: 31, TimestampMonotonic: 10,
}}},
Complete: true,
}
return s, limits
}
func main() {
s, limits := exampleHealth()
var b bytes.Buffer
err := telemetry.WriteHealthSnapshot(&b, s, limits)
fmt.Println(err, b.Len() > 0)
}
Output: <nil> true
func WriteMovementContext ¶
func WriteMovementContext(w io.Writer, c MovementContext, l WorkloadLimits) error
WriteMovementContext validates and writes the interchange, checking the encoded byte budget one transfer at a time. It generates no identities.
Example ¶
c := movementFixture()
c.Transfers[0].Unit = "KiB"
fmt.Println(telemetry.WriteMovementContext(&bytes.Buffer{}, c, telemetry.WorkloadLimits{}))
Output: movement transfer "t1": bytes require exact unit bytes
func WriteOTLPLogs ¶
func WriteOTLPLogs(w io.Writer, readings []Reading, o ExportOptions) error
WriteOTLPLogs writes bounded diagnostic readings as an OTLP/HTTP JSON ExportLogsServiceRequest. The private nvtelemetry.logs.v1 body preserves events, bitmasks, unavailable status, and exact unsigned values as decimal strings. No severity or sensor time is inferred. An unknown collector wall timestamp omits timeUnixNano. Unavailable reasons retain fixed canonical status classes; unrecognized reasons become "unknown". Raw labels, source IDs, and native error text are omitted. Resource identity follows WriteOTLPMetrics. Canonical signed diagnostic values use value_int64; uint64 values never pass through floats.
Example ¶
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var b bytes.Buffer
err := telemetry.WriteOTLPLogs(&b, []telemetry.Reading{{Name: telemetry.MetricXIDEvent, Unit: "code", DeviceUUID: "GPU-a", Evidence: telemetry.EvidenceMeasured, IsInt: true, IntValue: 79}}, telemetry.ExportOptions{})
fmt.Println(json.Valid(b.Bytes()), err)
}
Output: true <nil>
Example (SuppliedEvent) ¶
one := uint64(1)
r := Reading{Name: "ecc_error_event", Unit: "code", DeviceUUID: "GPU-example", Evidence: EvidenceMeasured, Number: &Number{Uint: &one}, Observation: &Observation{Kind: "event", SourceClass: "synthetic"}}
var b bytes.Buffer
err := WriteOTLPLogs(&b, []Reading{r}, ExportOptions{})
fmt.Println(err, strings.Contains(b.String(), "nvtelemetry.logs.events.v1"))
Output: <nil> true
func WriteOTLPMetrics ¶
func WriteOTLPMetrics(w io.Writer, readings []Reading, o ExportOptions) error
WriteOTLPMetrics writes an OTLP/HTTP JSON ExportMetricsServiceRequest. Gauges have no invented start time. Cumulative counters require an explicit epoch. Bitmasks/events and unavailable readings are refused, not miscast as gauges. Resource attributes preserve bounded caller-asserted entity relationships. Owner attributes require explicit process scope, complete identity and a current matching clock epoch; missing attribution remains device-only. This does not divide or duplicate whole-device measurements across allocation recipients. Point attributes preserve evidence, bounded reported provenance, and clock presence. Known clock bounds use exact decimal intValue strings. Sensor timestamps retain their declared domain without an inferred unit. timeUnixNano remains the collector wall timestamp, not a sensor timestamp. Attribute names have the nvtelemetry. prefix followed by the exposition label name, except device_uuid, which uses nvtelemetry.device.uuid. Mapped V5 histograms allow 32 ordinary attributes plus the exact 13 source-time attributes; this does not extend the closed attribute profile.
Example ¶
var b bytes.Buffer
e := WriteOTLPMetrics(&b, []Reading{{Name: "power_milliwatts", Unit: "milliwatts", DeviceUUID: "GPU-a", Evidence: EvidenceMeasured, IsInt: true, IntValue: 12500, TimestampUnix: 100}}, ExportOptions{})
fmt.Println(json.Valid(b.Bytes()), e)
Output: true <nil>
func WriteOperatorCPUContext ¶
func WriteOperatorCPUContext(w io.Writer, c OperatorCPUContext, l WorkloadLimits) error
WriteOperatorCPUContext writes validated, bounded CPU-context metadata. Successful serialization does not authenticate its producer or establish a relationship between annotations and the separately referenced code facts.
Example ¶
c, _ := cpuContextFixture()
var out bytes.Buffer
err := telemetry.WriteOperatorCPUContext(&out, c, telemetry.WorkloadLimits{})
fmt.Println(out.Len() > 0, err)
Output: true <nil>
func WriteOperatorContext ¶
func WriteOperatorContext(w io.Writer, c OperatorContext, l WorkloadLimits) error
WriteOperatorContext writes validated, bounded version1 application metadata. Derived inventory fields are omitted; readers recover them from retained raw bytes. A successful write is serialization, not framework/native evidence.
Example ¶
// Constructed application metadata; no framework or device is invoked.
c := operatorContextFixture()
var raw bytes.Buffer
err := telemetry.WriteOperatorContext(&raw, c, telemetry.WorkloadLimits{})
fmt.Println(err, raw.Len() > 0)
Output: <nil> true
func WriteRetentionRecoveryManifest ¶
func WriteRetentionRecoveryManifest(w io.Writer, m RetentionRecoveryManifest) error
WriteRetentionRecoveryManifest validates and writes one JSON recovery manifest line.
func WriteServingContext ¶
func WriteServingContext(w io.Writer, c ServingContext, l WorkloadLimits) error
WriteServingContext validates and writes the application interchange without generating any worker, request or transfer identifiers.
Example ¶
var b strings.Builder
err := WriteServingContext(&b, ServingContext{Version: 1, RunID: "r", Attempts: []ServingAttempt{}}, WorkloadLimits{})
fmt.Println(b.String(), err)
Output: {"version":1,"run_id":"r","attempts":[]} <nil>
func WriteServingContextV2 ¶
func WriteServingContextV2(w io.Writer, c ServingContextV2, l WorkloadLimits) error
WriteServingContextV2 validates and writes the version 2 interchange, checking the encoded byte budget one record at a time.
func WriteTrainingCheckpointContext ¶
func WriteTrainingCheckpointContext(w io.Writer, c TrainingCheckpointContext, l WorkloadLimits) error
WriteTrainingCheckpointContext validates and writes the bounded interchange. Validation and encoded byte-budget refusal precede any write. This writer does not publish or restore a checkpoint or generate application evidence.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
c := telemetry.TrainingCheckpointContext{Version: 1, RunID: "synthetic", Checkpoints: []telemetry.TrainingCheckpoint{}}
var b bytes.Buffer
err := telemetry.WriteTrainingCheckpointContext(&b, c, telemetry.WorkloadLimits{})
fmt.Println(b.String(), err)
}
Output: {"version":1,"run_id":"synthetic","checkpoints":[]} <nil>
func WriteTrainingContext ¶
func WriteTrainingContext(w io.Writer, c TrainingContext, l WorkloadLimits) error
WriteTrainingContext writes the versioned application interchange after validating identities and bounds. It does not create application evidence.
Example ¶
c := TrainingContext{Version: 1, RunID: "r", Updates: []TrainingUpdate{}}
var b strings.Builder
err := WriteTrainingContext(&b, c, WorkloadLimits{})
fmt.Println(b.String(), err)
Output: {"version":1,"run_id":"r","updates":[]} <nil>
func WriteTrainingPhaseContext ¶
func WriteTrainingPhaseContext(w io.Writer, c TrainingPhaseContext, l WorkloadLimits) error
WriteTrainingPhaseContext validates all bounds before writing version 2. It creates no quality evidence or optimizer outcomes and does not mutate c.
Example ¶
// Constructed application context; no optimizer outcome is invented.
c := phaseContextFixture()
var raw bytes.Buffer
err := telemetry.WriteTrainingPhaseContext(&raw, c, telemetry.WorkloadLimits{})
_, read, err2 := telemetry.ReadTrainingPhaseContext(&raw, telemetry.WorkloadSource{Provider: "application", Version: "training-context-v2", RunID: "run"}, telemetry.WorkloadLimits{})
fmt.Println(err, err2, read.Phases[0].Phase)
Output: <nil> <nil> forward
func WriteTrainingWorkloadOTLP ¶
func WriteTrainingWorkloadOTLP(w io.Writer, e WorkloadExport, o TrainingWorkloadOTLPOptions) error
WriteTrainingWorkloadOTLP writes bounded instantaneous scalar gauges from a W&B 0.19.11 history-compatible export or MLflow 2.22.0 metric-history page. W&B input may be an explicitly decoded SDK datastore derivative. It replays Raw through the matching public reader and refuses a changed digest or metric projection, missing time, ambiguous samples, and integers outside [-2^53, 2^53] before converting to float64. Other finite decimals use float64 rounding; original bytes remain identified by their hash. Only unknown units or explicitly evidenced 1, s, ms, us, bytes/By are supported. MLflow timestamps are milliseconds; W&B timestamps are seconds. MLflow points retain logged_metric_step, which may repeat at distinct times; W&B history steps must be unique. MLflow paging metadata describes only this page, never run-wide completeness. Continuation tokens remain in Raw, not attributes. Source provenance remains caller supplied; no native origin, training success, convergence, counters, epochs, clock bounds or backend acceptance is inferred. Every emitted caller/source string must be valid UTF-8. Validation completes before the first Write; an output error may leave bytes.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
// Declared example input; the regression uses a retained real SDK derivative.
source := telemetry.WorkloadSource{Provider: "wandb", Version: "0.19.11", RunID: "example", ClockDomain: "unix_utc"}
e, err := telemetry.ReadWandBHistory(strings.NewReader(`{"_timestamp":1700000000,"_step":0,"loss":1}`), source, telemetry.WorkloadLimits{})
if err != nil {
panic(err)
}
var out bytes.Buffer
err = telemetry.WriteTrainingWorkloadOTLP(&out, e, telemetry.TrainingWorkloadOTLPOptions{UnixClockProvenance: "explicit example caller declaration; no synchronization proof"})
fmt.Println(err, strings.Contains(out.String(), `"gauge"`), strings.Contains(out.String(), `"unit":""`))
}
Output: <nil> true true
Example (Mlflow) ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
// Declared example; the regression uses an actual SDK file-store response.
source := telemetry.WorkloadSource{Provider: "mlflow", Version: "2.22.0", RunID: "example", ClockDomain: "unix_utc"}
e, err := telemetry.ReadMLflowHistory(strings.NewReader(`{"metrics":[{"key":"loss","value":0.5,"timestamp":1700000000000,"step":0}]}`), source, telemetry.WorkloadLimits{})
if err != nil {
panic(err)
}
var out bytes.Buffer
err = telemetry.WriteTrainingWorkloadOTLP(&out, e, telemetry.TrainingWorkloadOTLPOptions{UnixClockProvenance: "caller-declared historical Unix milliseconds, no synchronization proof"})
fmt.Println(err, strings.Contains(out.String(), `"timeUnixNano":"1700000000000000000"`), strings.Contains(out.String(), "supplied_page_only"))
}
Output: <nil> true true
func WriteWorkloadOTLP ¶
func WriteWorkloadOTLP(w io.Writer, before, after WorkloadExport, o WorkloadOTLPOptions) error
WriteWorkloadOTLP writes bounded OTLP JSON delta sums and histograms from pinned serving exports. It recomputes typed windows, refusing visible resets. Counts/times are exact decimal strings; finite bounds/sums use doubles. Raw labels are replaced by a series hash. No NVML histogram, training progress, exact join or successful-token policy is manufactured.
Example ¶
source := WorkloadSource{Provider: "vllm", Version: "0.8.5", RunID: "cohort"}
read := func(value string, when int64) WorkloadExport {
raw := "# TYPE vllm:prompt_tokens_total counter\nvllm:prompt_tokens_total{model_name=\"model\"} " + value + "\n"
e, _ := ReadServingExposition(context.Background(), strings.NewReader(raw), source, WorkloadLimits{})
e, _ = StampWorkloadSnapshot(e, when, "mono", "epoch")
return e
}
err := WriteWorkloadOTLP(io.Discard, read("10", 0), read("13", 10), WorkloadOTLPOptions{StartNanos: 0, EndNanos: 10, ClockDomain: "mono", ClockEpochID: "epoch", HasUnixMapping: true, StartUnixNanos: 100, EndUnixNanos: 110, MappingProvenance: "receipt"})
fmt.Println(err)
Output: <nil>
Types ¶
type AccountingAllocation ¶
type AccountingAllocation struct {
ID string `json:"id"`
Assignment EntityAssignment `json:"assignment"`
CapacityPermille uint32 `json:"capacity_permille"`
Policy string `json:"policy"`
PolicyEvidence string `json:"policy_evidence"`
}
AccountingAllocation pairs an authoritative assignment with an explicit modeled share. CapacityPermille is allocated capacity, not measured work or measured per-owner energy. Policy must be capacity_time_v1.
type AccountingClock ¶
type AccountingClock struct {
Domain string `json:"domain"`
Epoch string `json:"epoch"`
UnixOffsetNanos int64 `json:"unix_offset_nanos"`
MappingKnown bool `json:"mapping_known"`
UncertaintyKnown bool `json:"uncertainty_known"`
UncertaintyNanos int64 `json:"uncertainty_nanos"`
ValidFrom int64 `json:"valid_from"`
ValidUntil int64 `json:"valid_until"`
Evidence string `json:"evidence"`
}
AccountingClock pins the caller's mapping from a monotonic epoch to Unix nanoseconds. Billing admission requires an explicitly known zero uncertainty; this implementation does not discover or qualify that mapping.
type AccountingEnergy ¶
type AccountingEnergy struct {
Evidence string `json:"evidence"` // measured, not derived
ClockDomain string `json:"clock_domain"`
ClockEpoch string `json:"clock_epoch"`
Scope string `json:"scope"` // physical_device
Summary EnergySummary `json:"summary"`
Lineage string `json:"lineage"`
RawDigest string `json:"raw_digest"`
ConfigurationEpoch string `json:"configuration_epoch,omitempty"`
}
AccountingEnergy is one complete physical cumulative counter interval. Lineage identifies the original counter, not an ingestion path. Duplicate or overlapping intervals from the same physical device are rejected.
type AccountingIdle ¶
type AccountingIdle struct {
DeviceUUID string `json:"device_uuid"`
ClockDomain string `json:"clock_domain"`
ClockEpoch string `json:"clock_epoch"`
StartNanos int64 `json:"start_nanos"`
EndNanos int64 `json:"end_nanos"`
CapacityPermille uint32 `json:"capacity_permille"`
Authoritative bool `json:"authoritative"`
Evidence string `json:"evidence"`
Policy string `json:"policy"`
}
AccountingIdle is an authoritative idle-capacity interval. Capacity is a caller-evidenced policy input, never inferred from missing allocations. The resulting energy is a uniform-rate capacity estimate, not an idle sensor.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
)
func main() {
raw, _ := os.ReadFile("testdata/accounting_v1.json")
var in telemetry.AccountingInput
json.Unmarshal(raw, &in)
in.Allocations, in.Rates, in.Work = nil, nil, nil
e := in.Energy[0].Summary
in.Idle = []telemetry.AccountingIdle{{DeviceUUID: e.DeviceUUID, ClockDomain: in.Clock.Domain, ClockEpoch: in.Clock.Epoch, StartNanos: e.StartMonoNanos, EndNanos: e.EndMonoNanos, CapacityPermille: 250, Authoritative: true, Evidence: "synthetic idle-capacity receipt", Policy: "capacity_time_v1"}}
report, err := telemetry.AccountEnergy(in)
fmt.Println(report.IdleEnergyMillijoules, report.UnclassifiedResidualMillijoules, err)
}
Output: 50000 150000 <nil>
type AccountingInput ¶
type AccountingInput struct {
Version int `json:"version"`
Nodes []AccountingNode `json:"nodes,omitempty"`
Idle []AccountingIdle `json:"idle,omitempty"`
Clock AccountingClock `json:"clock"`
Energy []AccountingEnergy `json:"energy"`
Baselines []AccountingEnergy `json:"baselines,omitempty"`
BaselinePolicy string `json:"baseline_policy,omitempty"`
BaselineEvidence string `json:"baseline_evidence,omitempty"`
WorkPolicy string `json:"work_policy,omitempty"`
Allocations []AccountingAllocation `json:"allocations"`
Rates []AccountingRate `json:"rates"`
Work []AccountingWork `json:"work,omitempty"`
}
AccountingInput is version 1 of the bounded accounting consumer format. Windows, allocations, rates and work each contain at most 128 entries. Baseline subtraction and whole-node energy are not inferred from device data.
type AccountingNode ¶
type AccountingNode struct {
NodeID string `json:"node_id"`
Energy AccountingEnergy `json:"energy"`
DeviceUUIDs []string `json:"device_uuids"`
MembershipEvidence string `json:"membership_evidence"`
}
AccountingNode supplies a measured whole-node counter and an authoritative, complete device membership for exactly that interval. Energy uses scope whole_node and Summary.DeviceUUID equals NodeID. Evidence is caller-provided provenance, not authentication performed by this package.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
)
func main() {
raw, _ := os.ReadFile("testdata/accounting_v1.json")
var in telemetry.AccountingInput
json.Unmarshal(raw, &in)
gpu := in.Energy[0]
node := gpu
node.Scope, node.Lineage, node.Summary.DeviceUUID = "whole_node", "node-counter", "node-1"
node.Summary.EnergyConsumedMJ = 300000
node.Summary.EndEnergyMJ = node.Summary.StartEnergyMJ + 300000
node.Summary.EnergyConsumedJoules = 300
in.Nodes = []telemetry.AccountingNode{{NodeID: "node-1", Energy: node, DeviceUUIDs: []string{gpu.Summary.DeviceUUID}, MembershipEvidence: "synthetic inventory receipt"}}
report, err := telemetry.AccountEnergy(in)
fmt.Println(report.Nodes[0].NodeEnergyMillijoules, report.Nodes[0].GPUComponentMillijoules, report.Nodes[0].OtherEnergyMillijoules, err)
}
Output: 300000 200000 100000 <nil>
type AccountingNodeTotal ¶
type AccountingNodeTotal struct {
GPUComponentsAvailable bool `json:"gpu_components_available"`
NodeID string `json:"node_id"`
StartNanos int64 `json:"start_nanos"`
EndNanos int64 `json:"end_nanos"`
NodeEnergyMillijoules string `json:"node_energy_millijoules"`
GPUComponentMillijoules string `json:"gpu_component_millijoules"`
OtherEnergyMillijoules string `json:"other_energy_millijoules"`
}
AccountingNodeTotal separates measured node and GPU-component totals. Missing GPU counters leave component and other totals empty, not zero. OtherEnergyMillijoules is their difference, not measured CPU or idle energy. Node energy is never added to PhysicalEnergyMillijoules or allocation shares.
type AccountingRate ¶
type AccountingRate struct {
DeviceUUID string `json:"device_uuid"`
EffectiveFromUnixNanos int64 `json:"effective_from_unix_nanos"`
EffectiveUntilUnixNanos int64 `json:"effective_until_unix_nanos"`
Currency string `json:"currency"`
MinorDigits uint32 `json:"minor_digits"`
PricePerGPUHour string `json:"price_per_gpu_hour"`
DiscountFactor string `json:"discount_factor"`
Region string `json:"region"`
SKU string `json:"sku"`
Scope string `json:"scope"` // device_usage_only
BillingQuantumNanos int64 `json:"billing_quantum_nanos"`
CommitmentAssumption string `json:"commitment_assumption"`
Source string `json:"source"`
Revision string `json:"revision"`
}
AccountingRate is a caller-pinned, effective-dated price for one physical device. Price and DiscountFactor are exact decimal or rational numbers. Rounding is per allocation and rate segment, never an invoice reconstruction.
type AccountingReport ¶
type AccountingReport struct {
Nodes []AccountingNodeTotal `json:"nodes,omitempty"`
IdleEnergyMillijoules string `json:"idle_energy_millijoules,omitempty"`
UnclassifiedResidualMillijoules string `json:"unclassified_residual_millijoules,omitempty"`
EnergyAvailable bool `json:"energy_available"`
EnergyClass string `json:"energy_class"`
CostClass string `json:"cost_class"`
Version int `json:"version"`
Input AccountingInput `json:"input"`
Method string `json:"method"`
PhysicalEnergyMillijoules string `json:"physical_energy_millijoules"`
BaselineAdjustedEnergyMillijoules string `json:"baseline_adjusted_energy_millijoules,omitempty"`
ResidualEnergyMillijoules string `json:"residual_energy_millijoules"`
}
AccountingReport preserves input lineage and assumptions alongside modeled shares. Residual energy is unallocated, not an independently measured idle quantity. Cost excludes power infrastructure, taxes and other invoice scope.
func AccountEnergy ¶
func AccountEnergy(in AccountingInput) (AccountingReport, error)
AccountEnergy apportions complete physical intervals by allocated capacity time under a uniform-energy-rate assumption, using exact rational arithmetic. It refuses unknown sharing, ambiguous clocks, missing coverage, resets, overlapping physical totals or capacity above one device. Idle and omitted capacity remain explicit residuals. Costs are model-only caller-rate estimates. With no supplied energy, allocated hours and costs remain available while physical energy, residuals and energy efficiency are explicitly unavailable. Malformed supplied counters are errors, never a cost-only fallback.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
)
func main() {
raw, err := os.ReadFile("testdata/accounting_v1.json")
if err != nil {
panic(err)
}
var input telemetry.AccountingInput
json.Unmarshal(raw, &input)
report, err := telemetry.AccountEnergy(input)
fmt.Println(report.Shares[0].CostMajor, report.Shares[0].Currency, err)
}
Output: 3/2 USD <nil>
Example (CostOnly) ¶
package main
import (
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
)
func main() {
raw, err := os.ReadFile("testdata/accounting_v1.json")
if err != nil {
panic(err)
}
var input telemetry.AccountingInput
json.Unmarshal(raw, &input)
input.Energy = nil
report, err := telemetry.AccountEnergy(input)
fmt.Println(report.EnergyAvailable, report.Shares[0].CostMajor, report.Shares[0].EfficiencyUnavailable, err)
}
Output: false 3/2 physical_energy_unavailable <nil>
func AccountTelemetry ¶
func AccountTelemetry(r io.Reader, in AccountingInput, window string, start, end, maxBytes int64) (AccountingReport, error)
AccountTelemetry reads a complete raw telemetry stream and feeds its exact cumulative counter delta into the accounting consumer. Boundary readings must have known source timestamps in the manifest clock, at the requested boundaries; query times never establish sensor timing. The caller supplies the explicit epoch/mapping evidence and allocation/rate/outcome policies. Native streams with unknown sensor timestamps are refused, not upgraded.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
)
func main() {
// Both files are synthetic known-answer contracts, not native receipts.
source, err := os.Open("testdata/accounting_v2.jsonl")
if err != nil {
panic(err)
}
defer source.Close()
policies, err := os.ReadFile("testdata/accounting_v1.json")
if err != nil {
panic(err)
}
var input telemetry.AccountingInput
json.Unmarshal(policies, &input)
input.Energy = nil
report, err := telemetry.AccountTelemetry(source, input, "measurement", 3600000000000, 10800000000000, 1<<20)
fmt.Println(report.PhysicalEnergyMillijoules, report.Shares[0].CostMajor, err)
}
Output: 200000 3/2 <nil>
func ReadAccounting ¶
func ReadAccounting(r io.Reader, maxBytes int64) (AccountingReport, error)
ReadAccounting consumes one versioned JSON document with a caller byte budget, rejecting unknown fields, trailing documents and structural defects. maxBytes must be positive and at most 16 MiB.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
)
func main() {
f, err := os.Open("testdata/accounting_v1.json")
if err != nil {
panic(err)
}
defer f.Close()
report, err := telemetry.ReadAccounting(f, 1<<20)
fmt.Println(report.PhysicalEnergyMillijoules, report.ResidualEnergyMillijoules, err)
}
Output: 200000 75000 <nil>
type AccountingShare ¶
type AccountingShare struct {
}
AccountingShare records an exact rational estimate. Rational strings use numerator/denominator notation; exact physical totals remain integer MJ.
type AccountingWork ¶
type AccountingWork struct {
ID string `json:"id"`
AllocationID string `json:"allocation_id"`
Units uint64 `json:"units"`
Unit string `json:"unit"`
Success bool `json:"success"`
Correct bool `json:"correct"`
Policy string `json:"policy"`
Evidence string `json:"evidence"`
ClockDomain string `json:"clock_domain"`
ClockEpoch string `json:"clock_epoch"`
StartNanos int64 `json:"start_nanos"`
EndNanos int64 `json:"end_nanos"`
}
AccountingWork contains independently admitted successful, correct work. Aggregate serving token metrics must not be copied here without evidence that they obey the named outcome and correctness policy.
type Applicability ¶
type Applicability uint8
Applicability distinguishes catalog coverage from product applicability.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
_, state := telemetry.LookupProduct(1, telemetry.H100)
fmt.Println(state == telemetry.NotApplicable)
}
Output: true
const ( UnknownID Applicability = iota UncoveredProduct NotApplicable Applicable )
type Architecture ¶
type Architecture string
Architecture identifies a product applicability column in NVIDIA's catalog. These names are product-specific, not claims about an architecture family.
const ( A100 Architecture = "A100" H100 Architecture = "H100" B100 Architecture = "B100" GB200 Architecture = "GB200" )
type ArmCheck ¶
type ArmCheck struct {
Arm string `json:"arm"`
DeviceUUID string `json:"device_uuid,omitempty"`
// Group names the comparison the arm belongs to. SM clocks are
// compared only among arms of one group: two concurrency levels, or
// two shapes, are not arms of each other. Empty is a group too.
Group string `json:"group,omitempty"`
// ProcessSamples counts the process-list queries that succeeded.
// Foreign lists every process seen in any of them that the caller's
// owned predicate did not claim, by PID, once each.
ProcessSamples int `json:"process_samples"`
Foreign []DeviceProcess `json:"foreign_processes,omitempty"`
// The clock fields summarize the SM clock over the arm's window.
// ClockSamples counts the samples that held an SM reading.
// ClockCoverage is the window's coverage times the fraction of its
// samples that held an SM reading, the quantity Stable holds to 0.8.
ClockSamples int `json:"clock_samples"`
ClockCoverage float64 `json:"clock_coverage"`
SMClockMinMHz uint64 `json:"sm_clock_min_mhz,omitempty"`
SMClockMaxMHz uint64 `json:"sm_clock_max_mhz,omitempty"`
SMClockMeanMHz float64 `json:"sm_clock_mean_mhz,omitempty"`
// ReasonBits is the union of the driver's clocks-event bits over the
// window, verbatim; Reasons is ClocksEventReasonNames(ReasonBits).
ReasonBits uint64 `json:"clocks_event_reason_bits"`
Reasons []string `json:"clocks_event_reasons,omitempty"`
// Unread says why a part of the evidence is missing. A zero above
// with an entry here was not read; it is not a zero reading.
Unread []string `json:"unread,omitempty"`
}
An ArmCheck is the retained evidence about the device around one timed arm: which foreign processes held a compute context on it, and what its SM clock did. It is JSON so a results file can carry it.
type ArmObserver ¶
type ArmObserver struct {
// contains filtered or unexported fields
}
An ArmObserver watches one device around timed arms: it samples the compute-process list at both ends of an arm and while it runs, and the SM clock throughout. One arm is observed at a time. An ArmObserver is safe for concurrent use.
func NewArmObserver ¶
func NewArmObserver(dev ArmObserverDevice, uuid string, cfg MonitorConfig, owned func(pid uint32) bool) *ArmObserver
NewArmObserver starts an ArmObserver for dev. owned reports whether a PID belongs to the workload being timed; a nil owned claims nothing. The caller keeps ownership of NVML; Close does not shut it down.
func OpenArmObserver ¶
func OpenArmObserver(index uint32, cfg MonitorConfig, owned func(pid uint32) bool) (*ArmObserver, error)
OpenArmObserver initializes NVML and starts an ArmObserver for the device at NVML index. Close shuts NVML down.
func OpenArmObserverPCI ¶
func OpenArmObserverPCI(busID string, cfg MonitorConfig, owned func(pid uint32) bool) (*ArmObserver, error)
OpenArmObserverPCI is OpenArmObserver for the device at PCI bus ID busID, which names the same GPU to CUDA and NVML where a CUDA ordinal and an NVML index can differ.
func (*ArmObserver) Clocks ¶
func (o *ArmObserver) Clocks(c *ArmCheck, start, end int64)
Clocks replaces the clock part of c, and its clock entries in Unread, with the summary over [start, end]. It serves a caller that learns an arm's exact window only after the arm has finished.
func (*ArmObserver) Close ¶
func (o *ArmObserver) Close() error
Close stops the ArmObserver and, for one from OpenArmObserver or OpenArmObserverPCI, shuts NVML down. Close is idempotent.
func (*ArmObserver) Finish ¶
func (o *ArmObserver) Finish(start, end int64) ArmCheck
Finish samples the process list again and returns the evidence for the arm begun by Start, with clocks summarized over [start, end] in the domain of Now. If end <= start the clock part is recorded as unread.
func (*ArmObserver) Now ¶
func (o *ArmObserver) Now() int64
Now returns the ArmObserver's clock, for bounding windows.
func (*ArmObserver) Start ¶
func (o *ArmObserver) Start(arm string) error
Start samples the process list and returns a *ContendedError if a foreign process is on the device. A query failure is returned as an error too: a device that cannot be read cannot be shown free.
The arm is open either way, so a caller that goes on despite the error still gets the foreign process or the failed query from Finish.
type ArmObserverDevice ¶
type ArmObserverDevice interface {
MonitorDevice
NVMLProcessQuery
}
ArmObserverDevice is the set of NVML queries an ArmObserver makes. nvml.Device implements it.
type AttributionRead ¶
type AttributionRead struct {
Snapshot JobAttributionSnapshot
Withheld []uint32
}
AttributionRead is one read of attribution sources. Withheld lists configured process IDs whose proc files were absent; they are omitted from Snapshot, so any earlier attribution for them is dropped on refresh.
func ReadNVMLAttributionSnapshot ¶
func ReadNVMLAttributionSnapshot(ctx context.Context, fsys fs.FS, src SlurmAttributionSource, sel NVMLProcessSelection, devices []NVMLProcessDevice) (AttributionRead, error)
ReadNVMLAttributionSnapshot queries the selected devices and then reads src with the observed PIDs, as ReadSlurmAttributionSnapshot does. src must configure no PIDs; the caller's src is not modified.
Everything is validated before the first query, and a failed query fails the read before any file is opened. Each observed PID is read once, in increasing order, however many facts name it. A successful query that observes no process reads no proc files, so a refresh with it clears earlier attribution; it does not mean that a job completed. Attribution still requires the scheduler and execution proofs in src. The proc files are read after the queries, so their stat start ticks are a later observation: they do not show that the PID was not reused in between.
func ReadSlurmAttributionSnapshot ¶
func ReadSlurmAttributionSnapshot(fsys fs.FS, src SlurmAttributionSource) (AttributionRead, error)
ReadSlurmAttributionSnapshot reads the configured files from fsys into a JobAttributionSnapshot. The source is validated before any file is opened. A configured process is withheld if its stat, status or cgroup file is absent or inaccessible, or stat identifies a zombie or dead process. Other read or parse errors, including errors in the shared source files, fail the whole read.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
)
func exampleAttributionSource() telemetry.SlurmAttributionSource {
return telemetry.SlurmAttributionSource{
Squeue: "squeue.json",
Mappings: "mappings.json",
Executions: "executions.json",
ProcDir: "proc",
PIDs: []uint32{1234},
BootID: "boot-1",
NodeID: "node-1",
PIDNamespace: "pid:[4026531836]",
Snapshot: telemetry.EntitySnapshot{
SourceRevision: "fixture-squeue-1",
Authoritative: true,
NodeID: "node-1",
ClockDomain: "synthetic_unix_utc",
ClockEpoch: "fixture-epoch-1",
StartNanos: 100,
EndNanos: 1_000_000_000_000,
},
}
}
func main() {
fsys := os.DirFS("testdata/entity/b690-refresh")
read, err := telemetry.ReadSlurmAttributionSnapshot(fsys, exampleAttributionSource())
if err != nil {
fmt.Println(err)
return
}
s := read.Snapshot
fmt.Println(len(s.Allocations), len(s.Mappings), len(s.Processes), len(s.Executions), len(read.Withheld))
}
Output: 1 1 1 1 0
type AttributionRefresher ¶
type AttributionRefresher struct {
// contains filtered or unexported fields
}
AttributionRefresher periodically reads attribution sources into a JobAttributionTable and withholds attribution when the last successful read is older than MaxAge. A failed read never refreshes or clears the table. It is exercised only against fixture sources; it does not qualify a live scheduler or procfs. The zero value is not usable; use NewAttributionRefresher.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsworkload"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
"time"
)
func exampleAttributionSource() telemetry.SlurmAttributionSource {
return telemetry.SlurmAttributionSource{
Squeue: "squeue.json",
Mappings: "mappings.json",
Executions: "executions.json",
ProcDir: "proc",
PIDs: []uint32{1234},
BootID: "boot-1",
NodeID: "node-1",
PIDNamespace: "pid:[4026531836]",
Snapshot: telemetry.EntitySnapshot{
SourceRevision: "fixture-squeue-1",
Authoritative: true,
NodeID: "node-1",
ClockDomain: "synthetic_unix_utc",
ClockEpoch: "fixture-epoch-1",
StartNanos: 100,
EndNanos: 1_000_000_000_000,
},
}
}
func main() {
fsys := os.DirFS("testdata/entity/b690-refresh")
table, _ := telemetry.NewJobAttributionTable(16, int64(time.Hour))
clock := telemetry.NewFakeClock(0, 200)
read := func(context.Context) (telemetry.AttributionRead, error) {
return telemetry.ReadSlurmAttributionSnapshot(fsys, exampleAttributionSource())
}
r, err := telemetry.NewAttributionRefresher(table, read, clock, telemetry.RefreshConfig{
Interval: time.Second, Timeout: time.Second, MaxAge: 5 * time.Second,
})
if err != nil {
fmt.Println(err)
return
}
defer r.Close()
if err := r.Step(context.Background()); err != nil {
fmt.Println(err)
return
}
proc := telemetry.EntityProcess{
Process: obsworkload.ProcessGenID{PID: 1234, Generation: 1000},
BootID: "boot-1",
NodeID: "node-1",
PIDNamespace: "pid:[4026531836]",
ExecGeneration: 1,
HasExecGeneration: true,
}
const gpu = "GPU-11111111-2222-3333-4444-555555555555"
res := r.Resolve(proc, gpu, 200)
fmt.Println(res.Assignment.State, res.Assignment.Owner.JobID)
clock.Advance(6 * time.Second)
res = r.Resolve(proc, gpu, 200)
fmt.Println(res.Assignment.State, res.Reason, r.Ready())
}
Output: assigned 42 unknown source_stale false
func NewAttributionRefresher ¶
func NewAttributionRefresher(table *JobAttributionTable, read func(context.Context) (AttributionRead, error), clock Clock, cfg RefreshConfig) (*AttributionRefresher, error)
NewAttributionRefresher returns a refresher that calls read once per cycle and refreshes table at the clock's Unix time, which must be the clock domain of the snapshot intervals. Freshness uses the clock's monotonic time.
func (*AttributionRefresher) Close ¶
func (a *AttributionRefresher) Close() error
Close stops Run, cancels an in-flight read and refuses later cycles. The table is left as it is. Close is safe to call more than once.
func (*AttributionRefresher) Ready ¶
func (a *AttributionRefresher) Ready() bool
Ready reports whether a read has succeeded within MaxAge.
func (*AttributionRefresher) Resolve ¶
func (a *AttributionRefresher) Resolve(proc EntityProcess, deviceUUID string, at int64) JobAttributionResult
Resolve returns the table's attribution for proc on deviceUUID at at, or an unknown result with reason source_stale when no read has succeeded within MaxAge, or source_closed after Close.
func (*AttributionRefresher) Run ¶
func (a *AttributionRefresher) Run(ctx context.Context) error
Run calls Step immediately and then every Interval until ctx is done or the refresher is closed. Step errors are reported by Status. Run returns ctx.Err() on cancellation and nil after Close.
func (*AttributionRefresher) Status ¶
func (a *AttributionRefresher) Status() RefreshStatus
Status returns a copy of the refresher's cycle accounting.
type BenchmarkCorrelation ¶
type BenchmarkCorrelation struct {
StartMonoNanos int64 `json:"start_mono_nanos"`
EndMonoNanos int64 `json:"end_mono_nanos"`
WindowName string `json:"window_name"`
TotalRequests int `json:"total_requests"`
SuccessfulRequests int `json:"successful_requests"`
TotalOutputTokens int `json:"total_output_tokens"`
TotalEnergyJoules float64 `json:"total_energy_joules"`
JoulesPerOutputToken float64 `json:"joules_per_output_token"`
OutputTokensPerJoule float64 `json:"output_tokens_per_joule"`
TokensAvailable bool `json:"tokens_available"`
EnergyAvailable bool `json:"energy_available"`
ClockAligned bool `json:"clock_aligned"`
RefusalReason string `json:"refusal_reason,omitempty"`
}
BenchmarkCorrelation joins a telemetry window with benchmark requests.
func CorrelateBenchmark ¶
func CorrelateBenchmark(windowName string, startMono, endMono int64, energy []EnergySummary, requests []BenchmarkRecord, opts BenchmarkOptions) (BenchmarkCorrelation, error)
CorrelateBenchmark joins telemetry energy summaries with benchmark request records for a specific window.
type BenchmarkOptions ¶
type BenchmarkOptions struct {
CountFailedTokens bool // whether to count tokens from failed requests
ClockProvenance string // clock synchronization provenance (e.g. "ptp", "ntp_synchronized", "local")
EstimatedClockSkewNanos int64 // estimated clock skew between generator and telemetry clock
MaxClockSkewNanos int64 // maximum acceptable clock skew between benchmark generator and telemetry host
MinCoverageRatio float64 // minimum acceptable energy window coverage ratio (defaults to 1.0)
}
BenchmarkOptions configures request-to-telemetry correlation.
type BenchmarkRecord ¶
type BenchmarkRecord struct {
RequestID string `json:"request_id"`
StartTimeNanos int64 `json:"start_time_nanos"`
EndTimeNanos int64 `json:"end_time_nanos"`
PromptTokens int `json:"prompt_tokens"`
OutputTokens int `json:"output_tokens"`
Success bool `json:"success"`
Endpoint string `json:"endpoint,omitempty"`
}
BenchmarkRecord represents one request record from an external load generator.
type Binding ¶
type Binding struct {
Launch LaunchKey `json:"launch"`
Identity obsevidence.EvidenceIdentity `json:"identity"`
}
Binding is an external producer's explicit launch-to-artifact receipt. It is not vendor CSV metadata and is never inferred from a capture.
type Bridge ¶
type Bridge struct {
// contains filtered or unexported fields
}
Bridge owns its supplied descriptor. Its zero value is not usable.
func New ¶
func New(store Store, info Info, opts BridgeOptions) (*Bridge, error)
New checks the map layout and adopts store on success. The caller closes store if New fails. A newly created hash map has no snapshot until Publish.
func (*Bridge) Close ¶
Close releases the descriptor once. Reused and retained pins survive. An owned removal failure is returned alongside a descriptor-close failure. A later explicit Close retries a failed pin removal only; descriptor close is never retried, and its first error remains visible on subsequent calls.
func (*Bridge) Publish ¶
Publish replaces the whole map value. Oversized or contradictory snapshots are refused before the map is updated. now is the publication wall time.
func (*Bridge) Read ¶
Read copies and validates a single hash entry. A positive maxAge is required; publications in the future are refused rather than assumed synchronized. Wall time is sampled after Lookup so concurrent publication cannot create a false future timestamp from a caller clock sampled before the lookup.
type BridgeOptions ¶
type BridgeOptions struct {
ReadOnly bool
OwnPin bool
RetainPin bool
PinPath string
RemovePin func(path string, expectedID uint32) error
}
Options selects descriptor access and pin retention. RemovePin must verify the expected kernel map ID under the caller's namespace ownership protocol. A nil callback is permitted only when the pin is retained or not owned.
type CalibratedClock ¶
type CalibratedClock interface {
Clock
ClockMetadata
Calibration() (validFrom, validUntil, bounds int64, ok bool)
}
CalibratedClock provides clock calibration bounds and mapping validity.
type Candidate ¶
type Candidate struct {
Capture *obsprofcore.Capture
Artifact *kernel.Artifact
Workload nvrtc.WorkloadIdentity
CompilerKey string
}
Candidate supplies actual artifact and compiler/workload producer receipts alongside the capture to which a launch may be joined. Capture and Artifact must not be mutated during Import. Missing receipts never acquire defaults.
type CapabilitySet ¶
CapabilitySet reports the latest probe status of each query on one GPU. Unsupported queries are omitted after their first definitive rejection.
type CapturePolicy ¶
type CapturePolicy struct {
Version int `json:"version"`
SourceID string `json:"source_id"`
AllowedDevices []string `json:"allowed_devices"`
MaxReadings int `json:"max_readings"`
MaxSampleBytes int `json:"max_sample_bytes"`
AllowedSourceLabels []string `json:"allowed_source_labels,omitempty"`
Collector CollectorConfig `json:"collector"`
}
CapturePolicy is an opt-in, bounded NVIDIA capture profile. It authorizes only the listed device UUIDs. The source must already be configured to that exact set; filtering after a broad hardware query is not target isolation. No environment, command line, model input or credential data is collected.
func ReadCapturePolicy ¶
func ReadCapturePolicy(r io.Reader, maxBytes int64) (*CapturePolicy, error)
ReadCapturePolicy reads one strict version 1 profile with a bounded size.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
input := `{"version":1,"source_id":"nvml","allowed_devices":["GPU-0"],"max_readings":32,"max_sample_bytes":4096,"collector":{"interval_nanos":1000000,"max_record_budget":20,"max_byte_budget":32768,"max_buffered_records":4,"budget_policy":"fail"}}`
p, err := telemetry.ReadCapturePolicy(strings.NewReader(input), 4096)
if err != nil {
panic(err)
}
fmt.Println(p.SourceID, p.AllowedDevices[0])
}
Output: nvml GPU-0
func (CapturePolicy) Validate ¶
func (p CapturePolicy) Validate() error
Validate checks a capture policy before the sampler or collector starts.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"time"
)
func exampleCapturePolicy() telemetry.CapturePolicy {
return telemetry.CapturePolicy{
Version: 1, SourceID: "nvml", AllowedDevices: []string{"GPU-0"}, MaxReadings: 32, MaxSampleBytes: 4096,
Collector: telemetry.CollectorConfig{IntervalNanos: int64(time.Millisecond), MaxRecordBudget: 20, MaxByteBudget: 32768, MaxBufferedRecords: 4, BudgetPolicy: telemetry.BudgetPolicyFail},
}
}
func main() {
p := exampleCapturePolicy()
fmt.Println(p.Validate())
p.AllowedDevices = nil
fmt.Println(p.Validate() != nil)
}
Output: <nil> true
type CaptureRegistry ¶
type CaptureRegistry struct {
// contains filtered or unexported fields
}
CaptureRegistry prevents duplicate governed capture of a GPU in one process. Its zero value is usable. It is not a cross-process lock, tenant authorization system or replacement for a native GPU lease.
func (*CaptureRegistry) NewSampler ¶
func (r *CaptureRegistry) NewSampler(source Sampler, clock Clock, p CapturePolicy) (*GovernedSampler, error)
NewSampler acquires process-local ownership of the policy's devices. Source metadata must describe precisely the allowed set before any sample. The caller still owns the underlying sampler and any NVML initialization.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"time"
)
func exampleCapturePolicy() telemetry.CapturePolicy {
return telemetry.CapturePolicy{
Version: 1, SourceID: "nvml", AllowedDevices: []string{"GPU-0"}, MaxReadings: 32, MaxSampleBytes: 4096,
Collector: telemetry.CollectorConfig{IntervalNanos: int64(time.Millisecond), MaxRecordBudget: 20, MaxByteBudget: 32768, MaxBufferedRecords: 4, BudgetPolicy: telemetry.BudgetPolicyFail},
}
}
func main() {
var registry telemetry.CaptureRegistry
source := telemetry.NewFakeSampler(telemetry.DeviceMetadata{UUID: "GPU-0"})
s, err := registry.NewSampler(source, telemetry.NewFakeClock(1, 1), exampleCapturePolicy())
if err != nil {
panic(err)
}
defer s.Close(context.Background())
_, err = registry.NewSampler(source, telemetry.NewFakeClock(1, 1), exampleCapturePolicy())
fmt.Println(err != nil)
}
Output: true
type CaptureStatus ¶
type CaptureStatus struct {
Closed bool
InFlight bool
SuccessfulQueries uint64
FailedQueries uint64
LastSuccessNanos int64
HasLastSuccess bool
LastQueryDurationNanos int64
SuppressedDiagnostics uint64
LastQueryFailed bool
SuppressedSourceLabels uint64
}
CaptureStatus contains collector self-observation, not device health.
type Category ¶
type Category struct {
Name string
Tests []Test
Unknown map[string]json.RawMessage
}
Category groups named tests, preserving uninterpreted additional fields.
type ClockDriftError ¶
type ClockDriftError struct {
Low, High int // indexes of the windows with the lowest minimum and highest maximum
LowMHz, HighMHz float64
Spread float64 // (HighMHz - LowMHz) / LowMHz
Tolerance float64
// missing or unqualified clock evidence.
Unavailable string
}
A ClockDriftError reports insufficient clock evidence, limiting clock event reasons, or observed SM clock extrema outside the tolerance.
func (*ClockDriftError) Error ¶
func (e *ClockDriftError) Error() string
type ClockEventReasons ¶
type ClockEventReasons struct {
GPUIdle Value
ApplicationsClocksSetting Value
SWPowerCap Value
HWSlowdown Value
HWThermalSlowdown Value
HWPowerBrakeSlowdown Value
SyncBoost Value
SWThermalSlowdown Value
DisplayClocksSetting Value
// Other holds reasons with no field above, keyed by element name
// without its clocks_event_reason_ or clocks_throttle_reason_ prefix.
Other map[string]Value
}
ClockEventReasons reports why clocks are below their maximum, each as "Active" or "Not Active".
func (*ClockEventReasons) UnmarshalXML ¶
func (r *ClockEventReasons) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
UnmarshalXML decodes a clocks_event_reasons or clocks_throttle_reasons element.
type ClockMetadata ¶
type ClockMetadata interface {
MonotonicDomain() string
MonotonicEpochID() string
WallDomain() string
Provenance() string
}
ClockMetadata provides clock domain, epoch, and synchronization metadata.
type Clocks ¶
type Clocks struct {
Graphics Value `xml:"graphics_clock"`
SM Value `xml:"sm_clock"`
Memory Value `xml:"mem_clock"`
Video Value `xml:"video_clock"`
}
Clocks holds clock frequencies in MHz.
type CollectedXID ¶
type CollectedXID struct {
Observation HealthObservation
Applicability Applicability
Err error
}
CollectedXID carries the raw XID event and its catalog lookup. NVML event sets do not supply the interrupt and error-status registers for decoding.
type Collector ¶
type Collector struct {
// contains filtered or unexported fields
}
Collector coordinates scheduled sampling from a hardware or fake Sampler.
func NewCollector ¶
func NewCollector(runID string, sampler Sampler, clock Clock, cfg CollectorConfig, w *Writer) *Collector
NewCollector creates an unstarted Collector.
func (*Collector) InitStream ¶
InitStream writes the initial manifest header to the stream sink.
func (*Collector) Run ¶
Run executes the scheduled collection loop until ctx is canceled or Stop is called.
func (*Collector) SetPhase ¶
SetPhase transitions the collector into a new named phase. Completed and active phases share MaxBufferedRecords with retained samples. MaxRecordBudget also caps phases, including the active phase, independently of the Writer's existing sample counter. MaxByteBudget additionally caps the encoded retained phase history and active marker, even without a Writer. Zero limits remain unlimited. A refused or failed transition retains the old active phase and does not append history. Phase refusals are never dropped.
func (*Collector) SetSampleHook ¶
SetSampleHook configures an optional callback invoked for each collected sample.
type CollectorConfig ¶
type CollectorConfig struct {
// SchemaVersion selects the stream version. Zero retains V2. V3 emits exact
// Number values; its Receipt preserves caller-supplied capture provenance.
SchemaVersion int `json:"schema_version,omitempty"`
Receipt *tracecontract.Receipt `json:"-"`
IntervalNanos int64 `json:"interval_nanos"`
MaxDurationNanos int64 `json:"max_duration_nanos"`
MaxRecordBudget int `json:"max_record_budget"`
MaxByteBudget int `json:"max_byte_budget"`
MaxBufferedRecords int `json:"max_buffered_records"`
BudgetPolicy string `json:"budget_policy,omitempty"`
DropOnFull bool `json:"drop_on_full"`
}
CollectorConfig configures sampling and limits.
type CollectorDaemon ¶
type CollectorDaemon struct {
// contains filtered or unexported fields
}
CollectorDaemon serializes metric polling and drains XID events separately.
func (*CollectorDaemon) Run ¶
func (d *CollectorDaemon) Run(ctx context.Context, batches chan<- GPUCollection, events chan<- CollectedXID) (err error)
Run sends fresh batches until ctx is canceled. It does not close caller-owned channels. A nil XID channel disables event collection.
type CollectorIntervals ¶
CollectorIntervals sets polling periods. Zero uses 10s, 30s, and 250ms for fast, medium, and draining the XID event sets, respectively.
type Column ¶
Column is a documented SQLite column. Nullable distinguishes an unavailable field from an integer zero. Order is the declared table order.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
c := telemetry.Column{Name: "end", Type: "INTEGER", Nullable: true}
fmt.Println(c.Name, c.Nullable)
}
Output: end true
type ContendedError ¶
type ContendedError struct {
Arm string
Processes []DeviceProcess
}
A ContendedError reports foreign processes on the device.
func (*ContendedError) Error ¶
func (e *ContendedError) Error() string
type DCGMClient ¶
type DCGMClient interface {
NewGroup(string, dcgm.GroupType) (dcgm.GpuGrp, error)
AddEntity(dcgm.GpuGrp, dcgm.FieldEntityGroup, dcgm.FieldEid) error
NewFieldGroup(string, []dcgm.FieldID) (dcgm.FieldGrp, error)
Watch(dcgm.GpuGrp, dcgm.FieldGrp, time.Duration, time.Duration, int32) error
LatestValues(uint32, []dcgm.FieldID) ([]dcgm.FieldValueV1, error)
Close() error
}
DCGMClient owns one exclusive connection and all objects it creates. Close must remove only its own watches/groups and retain externally owned engines. Native calls need not support interruption; contexts are checked between calls.
func OpenDCGMClient ¶
func OpenDCGMClient(ctx context.Context, address string, opts dcgm.ConnectOptions) (DCGMClient, error)
OpenDCGMClient explicitly connects to an existing host engine. The caller initializes the DCGM library and owns process-wide shutdown. Persisted watches are refused. No embedded engine, automatic Init or global Shutdown is used.
Example ¶
_, e := OpenDCGMClient(context.Background(), "not-contacted", dcgm.ConnectOptions{Timeout: time.Second, PersistAfterDisconnect: true})
fmt.Println(e)
Output: dcgm sampler: bounded nonpersistent connection required
type DCGMConfig ¶
type DCGMConfig struct {
SourceID, ProducerVersion, NativeOrigin string
Devices []DCGMDevice
Fields []DCGMField
Interval, MaxKeepAge time.Duration
MaxKeepSamples int32
MaxSampleAge, MaxFutureSkew time.Duration
}
DCGMConfig bounds the watch and records actual version and origin provenance.
type DCGMDevice ¶
DCGMDevice binds an explicitly selected physical engine ID to its UUID. The caller must verify this association against the admitted host inventory. MIG, switch and link entities require separate entity-aware adapters.
type DCGMField ¶
type DCGMField struct {
ID dcgm.FieldID
Mapping ManagedField
}
DCGMField binds a generated DCGM field ID to a replayable scalar mapping.
func DCGMIMEXFields ¶
func DCGMIMEXFields() []DCGMField
DCGMIMEXFields selects raw status fields from the existing generated IDs. No enum-to-health judgment mapping or IMEX action is performed. String-typed results remain unavailable to the numeric model, with RawText retained.
Example ¶
for _, field := range DCGMIMEXFields() {
fmt.Println(field.Mapping.Name, field.Mapping.SourceUnit)
}
Output: imex_domain_status code imex_daemon_status code
type DCGMFieldPolicyV3Binder ¶
type DCGMFieldPolicyV3Binder struct {
Register func(handle dcgm.Handle, fieldID uint16, policyID uint64, callback dcgm.FpRecvPolicyViolation, userData uint64) error
Unregister func(handle dcgm.Handle, fieldID uint16, policyID uint64) error
}
DCGMFieldPolicyV3Binder binds the read-only v3 field-policy registration pair. Policy creation, mutation, triggering, and remediation are excluded.
type DCGMFieldPolicyV3Config ¶
type DCGMFieldPolicyV3Config struct {
SourceID string
ProducerVersion string
NativeOrigin string
ClockDomain string
ClockEpoch string
FieldID uint16
PolicyID uint64
DeviceIDs map[uint32]string
}
DCGMFieldPolicyV3Config identifies one read-only v3 field-policy callback source. DeviceIDs must be a caller-verified inventory of physical GPU entity IDs (1..64 GPUs). Optional non-zero FieldID and PolicyID pin the expected registration key; callbacks outside that key or with malformed strings/enums are marked LayoutKnown=false.
type DCGMFieldPolicyV3Event ¶
type DCGMFieldPolicyV3Event struct {
Schema string `json:"schema"`
SourceID string `json:"source_id"`
ProducerVersion string `json:"producer_version"`
NativeOrigin string `json:"native_origin"`
ClockDomain string `json:"clock_domain"`
ClockEpoch string `json:"clock_epoch"`
ReceivedNanos int64 `json:"received_nanos"`
DeviceUUID string `json:"device_uuid,omitempty"`
PolicyID uint64 `json:"policy_id"`
PolicyName string `json:"policy_name,omitempty"`
FieldID uint16 `json:"field_id"`
FieldName string `json:"field_name,omitempty"`
EntityGroup dcgm.FieldEntityGroup `json:"entity_group"`
EntityID uint32 `json:"entity_id"`
CurrentValueBits uint64 `json:"current_value_bits"`
ThresholdValueBits uint64 `json:"threshold_value_bits"`
PolicyOperator dcgm.PolicyOperator `json:"policy_operator"`
ChannelMask uint32 `json:"channel_mask"`
ViolationTimestamp int64 `json:"violation_timestamp"`
LayoutKnown bool `json:"layout_known"`
DeviceKnown bool `json:"device_known"`
Dropped uint64 `json:"dropped"`
LossUnknown bool `json:"loss_unknown"`
}
DCGMFieldPolicyV3Event preserves a v3 field-policy violation payload with raw 64-bit IEEE-754 bit patterns and provenance. ReceivedNanos is consumer arrival time, never DCGM or sensor acquisition time. ViolationTimestamp is the raw callback field without independent sensor-clock verification. LossUnknown is always true because zero helper drops do not prove no upstream DCGM loss.
func ReadDCGMFieldPolicyV3Event ¶
func ReadDCGMFieldPolicyV3Event(r io.Reader) (DCGMFieldPolicyV3Event, error)
ReadDCGMFieldPolicyV3Event strictly decodes and validates one JSON diagnostic event.
func (DCGMFieldPolicyV3Event) CurrentValueFloat64 ¶
func (e DCGMFieldPolicyV3Event) CurrentValueFloat64() float64
CurrentValueFloat64 returns the IEEE-754 float64 value of CurrentValueBits.
func (DCGMFieldPolicyV3Event) ThresholdValueFloat64 ¶
func (e DCGMFieldPolicyV3Event) ThresholdValueFloat64() float64
ThresholdValueFloat64 returns the IEEE-754 float64 value of ThresholdValueBits.
type DCGMFieldPolicyV3Notifications ¶
type DCGMFieldPolicyV3Notifications struct {
// contains filtered or unexported fields
}
DCGMFieldPolicyV3Notifications owns one v3 field-policy registration (handle, fieldID, policyID). Close must succeed before its connection, host engine, or library is closed. The zero value is not usable.
func NewDCGMFieldPolicyV3Notifications ¶
func NewDCGMFieldPolicyV3Notifications(handle dcgm.Handle, fieldID uint16, policyID uint64, capacity int) (*DCGMFieldPolicyV3Notifications, error)
NewDCGMFieldPolicyV3Notifications registers a v3 field-policy violation callback using the generated dcgm.PolicyRegisterV3 and dcgm.PolicyUnregisterV3 bindings. It never creates, sets, or triggers policies.
func NewDCGMFieldPolicyV3NotificationsWithBinder ¶
func NewDCGMFieldPolicyV3NotificationsWithBinder(handle dcgm.Handle, fieldID uint16, policyID uint64, capacity int, binder DCGMFieldPolicyV3Binder) (*DCGMFieldPolicyV3Notifications, error)
NewDCGMFieldPolicyV3NotificationsWithBinder registers a v3 field-policy callback using an explicit register/unregister pair. Capacity must be between 1 and 4096. At most 64 v3 subscriptions can be active in a process. Duplicate (handle, fieldID, policyID) registrations are refused because dcgmPolicyUnregister_v3 unregisters by key rather than token. On a registration error, a non-nil subscription is returned alongside the error unless a dcgm.SymbolError proves registration was never called. The caller must Close a returned subscription before releasing the connection.
func (*DCGMFieldPolicyV3Notifications) Close ¶
func (s *DCGMFieldPolicyV3Notifications) Close() error
Close unregisters the (handle, fieldID, policyID) subscription and retires its token. A failed unregister preserves ownership and keeps the subscription active for retry. Successful unregister does not prove vendor worker quiescence; late callbacks for retired tokens are ignored by the permanent trampoline.
func (*DCGMFieldPolicyV3Notifications) Dropped ¶
func (s *DCGMFieldPolicyV3Notifications) Dropped() uint64
Dropped reports callbacks discarded because the queue was full, a concurrent callback or Close held the lock, or a nil violation pointer was delivered.
func (*DCGMFieldPolicyV3Notifications) Violations ¶
func (s *DCGMFieldPolicyV3Notifications) Violations() <-chan dcgm.FieldPolicyViolation
Violations returns the channel of copied v3 violation structs. Close closes the channel after unregistration succeeds; queued violations remain readable.
type DCGMFieldPolicyV3Reader ¶
type DCGMFieldPolicyV3Reader interface {
Violations() <-chan dcgm.FieldPolicyViolation
Dropped() uint64
Close() error
}
DCGMFieldPolicyV3Reader supplies copied native v3 field-policy violation responses. Implementations must keep their connection and registration live until Close succeeds.
type DCGMFieldPolicyV3Source ¶
type DCGMFieldPolicyV3Source struct {
// contains filtered or unexported fields
}
DCGMFieldPolicyV3Source owns a DCGMFieldPolicyV3Reader. The zero value is not usable. Close failure preserves the live source for an explicit caller retry.
func NewDCGMFieldPolicyV3Source ¶
func NewDCGMFieldPolicyV3Source(reader DCGMFieldPolicyV3Reader, clock Clock, c DCGMFieldPolicyV3Config) (*DCGMFieldPolicyV3Source, error)
NewDCGMFieldPolicyV3Source takes ownership of a v3 reader after validating clock provenance and device inventory.
Example ¶
var token uint64
sub, _ := NewDCGMFieldPolicyV3NotificationsWithBinder(1, uint16(dcgm.FieldDevGpuTempCelsius), 42, 2, DCGMFieldPolicyV3Binder{
Register: func(_ dcgm.Handle, _ uint16, _ uint64, _ dcgm.FpRecvPolicyViolation, u uint64) error {
token = u
return nil
},
Unregister: func(dcgm.Handle, uint16, uint64) error { return nil },
})
v := sampleViolation()
DispatchDCGMFieldPolicyV3Callback(&v, token)
source, _ := NewDCGMFieldPolicyV3Source(sub, policyClock(), fieldPolicyV3Config())
event, _ := source.Next(context.Background())
fmt.Println(event.Schema, event.DeviceUUID, event.PolicyName, event.CurrentValueFloat64(), event.LayoutKnown, event.LossUnknown)
_ = source.Close()
Output: nvtelemetry.dcgm-field-policy.v3 GPU-a thermal_ceiling 88.5 true true
func (*DCGMFieldPolicyV3Source) Close ¶
func (s *DCGMFieldPolicyV3Source) Close() error
Close unregisters only the owned v3 reader; it never closes the caller's connection or shuts down the DCGM engine or library.
func (*DCGMFieldPolicyV3Source) Next ¶
func (s *DCGMFieldPolicyV3Source) Next(ctx context.Context) (DCGMFieldPolicyV3Event, error)
Next waits for one copied v3 violation event or context cancellation.
type DCGMLimits ¶
type DCGMLimits struct{ Bytes, Records int }
Limits bounds bytes and total categories/tests/results/warnings/info records. Zero fields use 4 MiB and 65536 records; maxima are 16 MiB and 262144.
type DCGMNotificationReader ¶
type DCGMNotificationReader interface {
Notifications() <-chan dcgm.PolicyCallbackResponse
Dropped() uint64
Close() error
}
DCGMNotificationReader supplies copied native responses. Implementations must keep their connection and group live until Close succeeds.
type DCGMPolicyConfig ¶
type DCGMPolicyConfig struct {
SourceID string
ProducerVersion string
NativeOrigin string
ClockDomain string
ClockEpoch string
DeviceIDs map[uint32]string
}
DCGMPolicyConfig identifies one read-only native callback source. DeviceIDs must be a caller-verified inventory of the registered group, at most 64 GPUs.
type DCGMPolicyEvent ¶
type DCGMPolicyEvent struct {
Schema string `json:"schema"`
SourceID string `json:"source_id"`
ProducerVersion string `json:"producer_version"`
NativeOrigin string `json:"native_origin"`
ClockDomain string `json:"clock_domain"`
ClockEpoch string `json:"clock_epoch"`
ReceivedNanos int64 `json:"received_nanos"`
DeviceUUID string `json:"device_uuid,omitempty"`
Version uint32 `json:"version"`
Condition dcgm.PolicyCondition `json:"condition"`
RawPayload [2]uint64 `json:"raw_payload"`
GPUIndex uint32 `json:"gpu_index"`
LayoutKnown bool `json:"layout_known"`
DeviceKnown bool `json:"device_known"`
Dropped uint64 `json:"dropped"`
LossUnknown bool `json:"loss_unknown"`
}
DCGMPolicyEvent preserves the v2 callback payload without interpreting the condition-dependent union as a reading or sensor timestamp. ReceivedNanos is consumer arrival time, not DCGM acquisition time. Loss is cumulative.
type DCGMPolicySource ¶
type DCGMPolicySource struct {
// contains filtered or unexported fields
}
DCGMPolicySource owns a notification reader. The zero value is not usable. Close failure preserves the live source for an explicit caller retry.
func NewDCGMPolicySource ¶
func NewDCGMPolicySource(reader DCGMNotificationReader, clock Clock, c DCGMPolicyConfig) (*DCGMPolicySource, error)
NewDCGMPolicySource takes ownership after validation, without registering, setting or triggering native policy itself. Unknown layouts/devices remain raw diagnostic events, never admitted numeric or health measurements.
Example ¶
f := &fakeNotifications{queue: make(chan dcgm.PolicyCallbackResponse, 1)}
f.queue <- dcgm.PolicyCallbackResponse{Version: 0x2000020, GpuId: 7, Val: [2]uint64{17, 23}}
source, _ := NewDCGMPolicySource(f, policyClock(), policyConfig())
event, _ := source.Next(context.Background())
fmt.Println(event.DeviceUUID, event.RawPayload, event.LayoutKnown, event.Dropped)
source.Close()
Output: GPU-a [17 23] true 3
func (*DCGMPolicySource) Close ¶
func (s *DCGMPolicySource) Close() error
Close unregisters only the owned source; it never closes its connection, destroys its group or shuts down the DCGM engine or library.
Example ¶
var s DCGMPolicySource fmt.Println(errors.Is(s.Close(), ErrDCGMPolicySourceClosed))
Output: true
func (*DCGMPolicySource) Next ¶
func (s *DCGMPolicySource) Next(ctx context.Context) (DCGMPolicyEvent, error)
Next waits for one copied event or cancellation. Successful Close ends the reader after buffered callbacks drain. Concurrent Next calls divide events; they do not each receive a broadcast.
type DCGMReadingSource ¶
type DCGMReadingSource struct {
Version uint32 `json:"version"`
FieldID uint16 `json:"field_id"`
FieldName string `json:"field_name"`
FieldType uint16 `json:"field_type"`
Status int32 `json:"status"`
RawBits uint64 `json:"raw_bits"`
TimestampMicroseconds int64 `json:"timestamp_microseconds"`
RawText string `json:"raw_text,omitempty"`
}
DCGMReadingSource retains native scalar bits, status and DCGM cache timestamp. TimestampMicroseconds is a DCGM field sampling timestamp (zero means unknown), not independent proof of when the underlying sensor acquired a value.
type DCGMReport ¶
type DCGMReport struct {
Version string
CategoriesAvailable bool
Categories []Category
Unknown map[string]json.RawMessage
DiagnosticUnknown map[string]json.RawMessage
Raw []byte
}
Report contains the actual producer version and independently available fields. CategoriesAvailable distinguishes omission from a reported empty list. Unknown retains root fields, including raw entity inventory and metadata.
func ReadDCGMJSON ¶
func ReadDCGMJSON(r io.Reader, l DCGMLimits) (*DCGMReport, error)
Read parses a complete bounded document without synthesizing missing fields. Only the source-pinned 4.6.1 single-iteration profile is supported. Multi- iteration, older gpu_id profiles and runtime-error-only documents are refused. The caller must cancel an io.Reader that can block.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
report, err := telemetry.ReadDCGMJSON(strings.NewReader(`{"metadata":{"version":"4.6.1"},"DCGM Diagnostic":{}}`), telemetry.DCGMLimits{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(report.Version, report.CategoriesAvailable)
}
Output: 4.6.1 false
type DCGMSampler ¶
type DCGMSampler struct {
// contains filtered or unexported fields
}
DCGMSampler implements Sampler with an owned, bounded DCGM watch. Its zero value is closed. Close waits for an active native query; no goroutine is left behind to pretend a blocked native call has been cancelled.
func NewDCGMSampler ¶
func NewDCGMSampler(ctx context.Context, client DCGMClient, clock Clock, c DCGMConfig) (*DCGMSampler, error)
NewDCGMSampler takes ownership of a fresh exclusive client after validation. Setup failures close that client and preserve cleanup errors. Invalid config leaves ownership with the caller. Another agent's watches are never borrowed.
Example ¶
client := &fakeDCGMClient{values: []dcgm.FieldValueV1{dcgmTestValue()}}
sampler, err := NewDCGMSampler(context.Background(), client, NewFakeClock(10, 100), dcgmTestConfig())
readings, err := sampler.Sample(context.Background())
fmt.Println(readings[0].IntValue, readings[0].Source.Native.TimestampMicroseconds, readings[0].HasSourceTimestamp, err)
sampler.Close()
Output: 9007199254740993 123456 false <nil>
func (*DCGMSampler) Close ¶
func (s *DCGMSampler) Close() error
Close closes the owned client once and consistently returns its cleanup error.
Example ¶
var s DCGMSampler fmt.Println(s.Close())
Output: <nil>
func (*DCGMSampler) Devices ¶
func (s *DCGMSampler) Devices() []DeviceMetadata
type DDMetricMapping ¶
type DDMetricMapping struct {
Datadog, OTLP, Unit, Type string
// Conversion describes required derivation or scaling before export.
Conversion string
}
DDMetricMapping describes a Datadog source metric and its OTLP projection. Sum entries describe cumulative monotonic counters. Names under hw.gpu include GPU-specific extensions where no standard instrument exists.
type DecodeMatch ¶
type DecodeMatch struct {
Rule DecodeRule
Variant DecodeVariant
Bucket string
StatusConstrained bool
}
DecodeMatch retains the actual matching source row and raw bucket. A blank status cell is unconstrained by this source, not an implicit zero value.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
result := telemetry.DecodeXID(144, telemetry.B100, "575.0", 1, 1)
match := result.Matches[0]
fmt.Println(match.StatusConstrained, match.Bucket)
}
Output: true IGNORE
type DecodeOutcome ¶
type DecodeOutcome uint8
DecodeOutcome describes matching evidence, never a health or recovery policy.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
result := telemetry.DecodeXID(144, telemetry.B100, "unknown", 1, 1)
fmt.Println(result.Outcome == telemetry.UnknownDriver)
}
Output: true
const ( UnknownDriver DecodeOutcome = iota UnsupportedProduct NoDecodeMatch OneDecodeMatch AmbiguousDecode )
type DecodeResult ¶
type DecodeResult struct {
Driver string
DriverMajor uint32
Outcome DecodeOutcome
Applicability Applicability
Matches []DecodeMatch
}
DecodeResult preserves caller driver identity and every matching variant. More than one match is ambiguous; no first or preferred action is selected.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
result := telemetry.DecodeXID(144, telemetry.B100, "575.0", 1, 1)
fmt.Println(result.Driver, result.DriverMajor)
}
Output: 575.0 575
func DecodeXID ¶
func DecodeXID(id uint64, product Architecture, driver string, intrInfo, errorStatus uint32) DecodeResult
Decode matches the caller's IntrInfo and errorStatus against the pinned source for a documented product and a numeric driver version (one to three decimal components). Unknown or malformed drivers do not select V1. Drivers below R575 select V1; R575 and later select V2. Secondary masks are tested independently of primary masks. No other registers or remediation are inferred.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
result := telemetry.DecodeXID(145, telemetry.B100, "575.0", 0x86, 1)
fmt.Println(result.Outcome == telemetry.OneDecodeMatch, result.Matches[0].Rule.Row, result.Matches[0].Bucket)
}
Output: true 23 RESET_GPU
type DecodeRule ¶
DecodeRule preserves one row of the pinned Xid 144-150 Decode sheet. Cells are the unmodified A through M values, including blank cells. Row is the actual workbook row number. SourceSHA256 identifies the workbook.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
rule := telemetry.DecodeRules(144)[0]
fmt.Println(rule.Code, rule.Row)
}
Output: 144 2
func DecodeRules ¶
func DecodeRules(id uint64) []DecodeRule
DecodeRules returns detached source rows for id, in workbook order.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
rules := telemetry.DecodeRules(144)
fmt.Println(len(rules), rules[0].Row, rules[0].Cells[5])
}
Output: 6 2 IGNORE
type DecodeVariant ¶
type DecodeVariant uint8
DecodeVariant identifies the independent primary or secondary IntrInfo mask.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
result := telemetry.DecodeXID(145, telemetry.B100, "575.0", 0x86, 1)
fmt.Println(result.Matches[0].Variant == telemetry.SecondaryDecode)
}
Output: true
const ( PrimaryDecode DecodeVariant = iota SecondaryDecode )
type Delivery ¶
type Delivery struct {
// contains filtered or unexported fields
}
Delivery sends bounded OTLP HTTP batches on one worker. The zero value is not usable. Call Close to stop its worker and report incomplete delivery. A failing exporter never logs request headers, payloads, response bodies or transport error text. Statistics describe acceptance, not backend storage.
func NewDelivery ¶
func NewDelivery(c DeliveryConfig) (*Delivery, error)
NewDelivery starts a worker for the caller-supplied endpoint. It performs no network operation until Enqueue admits a batch. All limits must be explicit.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/tmc/lib/nvidia/x/host/otlp"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
s := otlp.NewSink()
defer s.Close()
d, err := telemetry.NewDelivery(telemetry.DeliveryConfig{Endpoint: s.URL + "/v1/metrics", Client: s.Client(), MaxQueuedBatches: 2, MaxQueuedBytes: 4096, MaxBatchBytes: 2048, MaxBatchDataPoints: 10, MaxResponseBytes: 1024, MaxAttempts: 1, BatchTimeout: 10 * time.Second, RequestTimeout: 5 * time.Second, ShutdownTimeout: 10 * time.Second})
if err != nil {
panic(err)
}
// Each item is a complete encoded OTLP ExportMetricsServiceRequest.
payload := []byte(`{"resourceMetrics":[{"scopeMetrics":[{"metrics":[{"name":"nvtelemetry.power","unit":"W","gauge":{"dataPoints":[{"asDouble":46}]}}]}]}]}`)
if err := d.Enqueue(context.Background(), payload); err != nil {
panic(err)
}
if err := d.Close(context.Background()); err != nil {
panic(err)
}
fmt.Println(d.Stats().SucceededBatches)
}
Output: 1
func NewLogsDelivery ¶
func NewLogsDelivery(c DeliveryConfig) (*Delivery, error)
NewLogsDelivery starts an OTLP HTTP logs export worker for the caller-supplied endpoint. It shares bounded queueing, worker lifecycle, retry hysteresis, and shutdown semantics with NewDelivery while validating ExportLogsServiceRequest batches and reporting rejected log records separately.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/tmc/lib/nvidia/x/host/otlp"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
s := otlp.NewSink()
defer s.Close()
d, err := telemetry.NewLogsDelivery(telemetry.DeliveryConfig{
Endpoint: s.URL + "/v1/logs",
Client: s.Client(),
MaxQueuedBatches: 2,
MaxQueuedBytes: 4096,
MaxBatchBytes: 2048,
MaxBatchDataPoints: 10,
MaxResponseBytes: 1024,
MaxAttempts: 1,
BatchTimeout: 10 * time.Second,
RequestTimeout: 5 * time.Second,
ShutdownTimeout: 10 * time.Second,
})
if err != nil {
panic(err)
}
// Each item is a complete encoded OTLP ExportLogsServiceRequest.
payload := []byte(`{"resourceLogs":[{"scopeLogs":[{"logRecords":[{"timeUnixNano":"100","body":{"stringValue":"gpu throttle resolved"}}]}]}]}`)
if err := d.Enqueue(context.Background(), payload); err != nil {
panic(err)
}
if err := d.Close(context.Background()); err != nil {
panic(err)
}
fmt.Println(d.Stats().SucceededBatches)
}
Output: 1
func (*Delivery) Close ¶
Close stops admission and drains within ShutdownTimeout or the first caller's context deadline. A timed-out or partially rejected drain returns ErrDeliveryIncomplete. Later callers may stop waiting with their own contexts, but do not shorten the shared drain. After completion, repeated Close calls return the stored outcome even if their contexts are canceled. HTTP transports must honor request context cancellation; a custom transport that ignores it cannot be forcibly terminated by this package.
func (*Delivery) Done ¶
func (d *Delivery) Done() <-chan struct{}
Done returns a channel closed after the delivery worker exits. A nil or zero Delivery returns nil. Worker exit is distinct from successful delivery; Close reports the final delivery outcome.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"net/http"
"time"
)
func main() {
d, err := telemetry.NewDelivery(telemetry.DeliveryConfig{Endpoint: "http://offline.invalid/v1/metrics", Client: &http.Client{}, MaxQueuedBatches: 1, MaxQueuedBytes: 1024, MaxBatchBytes: 1024, MaxBatchDataPoints: 1, MaxResponseBytes: 1024, MaxAttempts: 1, BatchTimeout: time.Second, RequestTimeout: time.Second, ShutdownTimeout: time.Second})
if err != nil {
fmt.Println(err)
return
}
err = d.Close(context.Background())
<-d.Done()
fmt.Println(err)
}
Output: <nil>
func (*Delivery) Enqueue ¶
Enqueue copies one encoded OTLP request. It fails immediately when full; it never waits for the network. Caller cancellation refuses admission.
func (*Delivery) Stats ¶
func (d *Delivery) Stats() DeliveryStats
Stats returns a coherent copy of exporter counters without payload metadata.
type DeliveryConfig ¶
type DeliveryConfig struct {
// Format defaults to FormatJSON.
Format OTLPFormat
// Gzip compresses the HTTP request body. Queue budgets count uncompressed bytes.
Gzip bool
Endpoint string
Client *http.Client
Headers http.Header
MaxQueuedBatches int
MaxQueuedBytes int
MaxBatchBytes int
MaxBatchDataPoints int
MaxResponseBytes int64
MaxAttempts int
InitialBackoff time.Duration
MaxBackoff time.Duration
BatchTimeout time.Duration
RequestTimeout time.Duration
ShutdownTimeout time.Duration
}
DeliveryConfig sets explicit HTTP export and lifetime bounds. Endpoint is an absolute HTTP(S) OTLP metrics URL. Client supplies TLS and authentication behavior; Headers may supply credentials and are cloned. No endpoint, client or background exporter is installed by default. Redirects are refused so success cannot be attributed to a different endpoint.
An item is one already encoded ExportMetricsServiceRequest or ExportLogsServiceRequest, not a reading. Outstanding budgets include the batch being sent. MaxBatchDataPoints bounds gauge/sum/histogram/summary points or log records independently of the byte limit. Delivery preserves item order but retry can duplicate a previously accepted request.
type DeliveryStats ¶
type DeliveryStats struct {
EnqueuedBatches uint64
SucceededBatches uint64
SentBatches uint64
FailedBatches uint64
DroppedBatches uint64
RetryAttempts uint64
PartialBatches uint64
RejectedDataPoints uint64
RejectedLogRecords uint64
AuthFailures uint64
RejectedBatches uint64
TransportFailures uint64
OutageResponses uint64
InvalidResponses uint64
PendingBatches int
PendingBytes int
}
DeliveryStats records cumulative delivery outcomes. SentBatches includes partial-success responses, but SucceededBatches only includes full acceptance. DroppedBatches counts budget-refused Enqueue calls; FailedBatches counts admitted items not fully delivered. Pending budgets include the in-flight item.
type DeviceMetadata ¶
type DeviceMetadata struct {
UUID string `json:"uuid"`
Index int `json:"index"`
Model string `json:"model"`
Architecture string `json:"architecture,omitempty"`
DriverVersion string `json:"driver_version,omitempty"`
LibraryVersion string `json:"library_version,omitempty"`
PowerLimitMW uint32 `json:"power_limit_mw,omitempty"`
MaxSMClockMHz uint32 `json:"max_sm_clock_mhz,omitempty"`
MaxMemoryClockMHz uint32 `json:"max_memory_clock_mhz,omitempty"`
MIGEnabled bool `json:"mig_enabled,omitempty"`
MIGParentUUID string `json:"mig_parent_uuid,omitempty"`
MIGInstanceID int `json:"mig_instance_id,omitempty"`
FieldCapabilities []string `json:"field_capabilities,omitempty"`
ClockSettings string `json:"clock_settings,omitempty"`
MIGScope string `json:"mig_scope,omitempty"`
HasMIGInstanceID bool `json:"has_mig_instance_id,omitempty"`
MIGComputeInstanceID int `json:"mig_compute_instance_id,omitempty"`
HasMIGComputeInstanceID bool `json:"has_mig_compute_instance_id,omitempty"`
Status string `json:"status,omitempty"`
Warnings []string `json:"warnings,omitempty"`
MetadataFailures []MetadataFailure `json:"metadata_failures,omitempty"`
FieldStatuses map[string]string `json:"field_statuses,omitempty"`
}
DeviceMetadata records static or discovered device identity.
type DeviceProcess ¶
type DeviceProcess struct {
PID uint32 `json:"pid"`
UsedMemoryBytes uint64 `json:"used_memory_bytes"`
}
A DeviceProcess is one process NVML reported holding a compute context on the observed device.
type DeviceSample ¶
type DeviceSample struct {
QueryStart int64
QueryEnd int64
TemperatureC Field
SMClockMHz Field
MemClockMHz Field
PowerMW Field
GPUUtilPct Field
MemUtilPct Field
MemoryUsedBytes Field
ClocksEventReasons Field
}
A DeviceSample is one pass over the monitored device's fields.
QueryStart and QueryEnd bound the NVML calls on the monitor's host monotonic clock. They are query times, not sensor times: NVML does not say when the driver last refreshed a value, and some refresh slowly (a GB10 held one power value for 400-600 ms). A sample is the driver's most recent value at the time of the query.
type DurableDelivery ¶
type DurableDelivery struct {
// contains filtered or unexported fields
}
DurableDelivery sends bounded OTLP HTTP JSON batches on one background worker backed by a persistent disk spool queue. The zero value is not usable.
Delivery semantics:
Durable: Once Enqueue returns nil, the batch has been validated and committed to the private, task-owned spool directory on disk via file and directory fsync. Spooled batches survive graceful and ungraceful process termination. Durability against host power loss depends on the underlying filesystem mount and disk write-barrier semantics; callers must not assume guarantees stronger than POSIX fsync.
Duplicated: Delivery guarantees at-least-once transport within configured retry bounds. If a network interruption, client timeout, or process restart occurs before an HTTP 200 response acknowledgment is processed, the spooled batch will be retried or recovered on restart. Exactly-once delivery is impossible across distributed systems and is never promised.
Discarded: When the spool queue or byte budget is exhausted, Enqueue immediately rejects new batches with ErrDeliveryFull and increments DroppedBatches (producer loss). If an admitted batch encounters an unretryable response (a 4xx status other than 429, a partial success or an invalid response), it is removed from the spool to preserve queue progress, incrementing FailedBatches (delivery loss). A batch that meets only transport failures or outage statuses (429, 502, 503, 504) stays at the head of the spool: after MaxAttempts it is retried again after MaxBackoff, until it is delivered, Close stops the worker, or it is older than a positive MaxSpoolAge, which removes it and increments EvictedBatches (delivery loss).
Unknown: When Close times out or is cancelled, pending spooled batches remain on disk; their eventual delivery status is unknown until a subsequent process instance recovers the spool directory.
Privacy & Security: Authorization credentials, endpoint query strings, payload contents, and raw response bodies are never exposed in error messages, statistics, or logs.
func NewDurableDelivery ¶
func NewDurableDelivery(c DurableDeliveryConfig) (*DurableDelivery, error)
NewDurableDelivery starts a disk-backed OTLP HTTP metrics delivery worker. Batches enqueued to DurableDelivery are durably spooled to SpoolDir before admission is acknowledged. The spool directory must be exclusively owned by Owner and private to the calling user (0700). On startup, pending spooled records from any previous instance are cleanly reloaded and scheduled for delivery.
Example ¶
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/tmc/lib/nvidia/x/host/otlp"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
s := otlp.NewSink()
defer s.Close()
spoolDir, err := os.MkdirTemp("", "spool-example-*")
if err != nil {
panic(err)
}
defer os.RemoveAll(spoolDir)
d, err := telemetry.NewDurableDelivery(telemetry.DurableDeliveryConfig{
Delivery: telemetry.DeliveryConfig{
Endpoint: s.URL + "/v1/metrics",
Client: s.Client(),
MaxQueuedBatches: 2,
MaxQueuedBytes: 4096,
MaxBatchBytes: 2048,
MaxBatchDataPoints: 10,
MaxResponseBytes: 1024,
MaxAttempts: 1,
BatchTimeout: 5 * time.Second,
RequestTimeout: 2 * time.Second,
ShutdownTimeout: 5 * time.Second,
},
SpoolDir: filepath.Join(spoolDir, "task-spool"),
Owner: "example-task",
MaxSpoolBatches: 10,
MaxSpoolBytes: 65536,
})
if err != nil {
panic(err)
}
payload := []byte(`{"resourceMetrics":[{"scopeMetrics":[{"metrics":[{"name":"nvtelemetry.power","unit":"W","gauge":{"dataPoints":[{"asDouble":46}]}}]}]}]}`)
if err := d.Enqueue(context.Background(), payload); err != nil {
panic(err)
}
if err := d.Close(context.Background()); err != nil {
panic(err)
}
fmt.Println(d.Stats().SucceededBatches)
}
Output: 1
func NewLogsDurableDelivery ¶
func NewLogsDurableDelivery(c DurableDeliveryConfig) (*DurableDelivery, error)
NewLogsDurableDelivery starts a disk-backed OTLP HTTP logs delivery worker. It shares disk spooling, worker lifecycle, retry hysteresis, and recovery semantics with NewDurableDelivery while validating ExportLogsServiceRequest batches and reporting rejected log records.
Example ¶
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/tmc/lib/nvidia/x/host/otlp"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
s := otlp.NewSink()
defer s.Close()
spoolDir, err := os.MkdirTemp("", "spool-logs-example-*")
if err != nil {
panic(err)
}
defer os.RemoveAll(spoolDir)
d, err := telemetry.NewLogsDurableDelivery(telemetry.DurableDeliveryConfig{
Delivery: telemetry.DeliveryConfig{
Endpoint: s.URL + "/v1/logs",
Client: s.Client(),
MaxQueuedBatches: 2,
MaxQueuedBytes: 4096,
MaxBatchBytes: 2048,
MaxBatchDataPoints: 10,
MaxResponseBytes: 1024,
MaxAttempts: 1,
BatchTimeout: 5 * time.Second,
RequestTimeout: 2 * time.Second,
ShutdownTimeout: 5 * time.Second,
},
SpoolDir: filepath.Join(spoolDir, "task-spool"),
Owner: "example-logs-task",
MaxSpoolBatches: 10,
MaxSpoolBytes: 65536,
})
if err != nil {
panic(err)
}
payload := []byte(`{"resourceLogs":[{"scopeLogs":[{"logRecords":[{"timeUnixNano":"100","body":{"stringValue":"gpu throttle cleared"}}]}]}]}`)
if err := d.Enqueue(context.Background(), payload); err != nil {
panic(err)
}
if err := d.Close(context.Background()); err != nil {
panic(err)
}
fmt.Println(d.Stats().SucceededBatches)
}
Output: 1
func (*DurableDelivery) Close ¶
func (d *DurableDelivery) Close(ctx context.Context) error
Close stops admission and drains spooled batches within ShutdownTimeout or caller's context deadline. If shutdown expires or is cancelled before draining, pending batches remain spooled on disk for restart recovery, and ErrDeliveryIncomplete is returned. After the worker and admissions finish, Close releases the writer lease. A cleanup error is returned without discarding handles needed to retry; after correcting its cause, call Close again. A file or root Close consumes that handle even when it reports an error; that error remains visible on later calls. Cleanup does not resume admission or retry delivery.
func (*DurableDelivery) Done ¶
func (d *DurableDelivery) Done() <-chan struct{}
Done returns a channel closed after the delivery worker exits. If no admission is in progress then, the worker has released the writer lease first. Close can return before this, once its deadline expires.
func (*DurableDelivery) Enqueue ¶
func (d *DurableDelivery) Enqueue(ctx context.Context, payload []byte) error
Enqueue validates and commits one encoded OTLP request to the disk spool. It reserves capacity under the writer lock before committing to disk, guaranteeing that concurrent admissions strictly observe spool limits. Caller cancellation refuses admission.
func (*DurableDelivery) Recover ¶
func (d *DurableDelivery) Recover(ctx context.Context) error
Recover flushes pending spooled records to the endpoint until the spool queue is drained or ctx is done. It returns ErrDeliveryIncomplete if any batch failed delivery.
func (*DurableDelivery) Stats ¶
func (d *DurableDelivery) Stats() DurableDeliveryStats
Stats returns a coherent copy of delivery and spool counters without payload metadata.
type DurableDeliveryConfig ¶
type DurableDeliveryConfig struct {
Delivery DeliveryConfig
SpoolDir string
Owner string
MaxSpoolBatches int
MaxSpoolBytes int64
MaxSpoolAge time.Duration
}
DurableDeliveryConfig sets explicit bounds for disk-spooled OTLP HTTP delivery. SpoolDir must be an exclusively task-owned directory private to the calling user (permissions 0700, no group/other access). Owner is a non-empty, non-secret task identifier (printable ASCII, max 128 bytes). MaxSpoolBatches bounds the maximum number of spooled batches stored on disk. MaxSpoolBytes bounds the cumulative disk bytes of spooled batch payloads. MaxSpoolAge, if positive, bounds how long an undeliverable batch is kept; zero keeps it until it is delivered. Delivery sets HTTP transport bounds and timeouts.
type DurableDeliveryRecoveryManifest ¶
type DurableDeliveryRecoveryManifest struct {
SchemaVersion int `json:"schema_version"`
MarkerVersion int `json:"marker_version"`
Owner string `json:"owner"`
RecoveredLease bool `json:"recovered_lease"`
RemovedTempFiles int `json:"removed_temp_files"`
PendingBatches int `json:"pending_batches"`
PendingBytes int64 `json:"pending_bytes"`
}
DurableDeliveryRecoveryManifest records the versioned recovery state of an owned durable delivery spool.
func ReadDurableDeliveryRecoveryManifest ¶
func ReadDurableDeliveryRecoveryManifest(r io.Reader) (DurableDeliveryRecoveryManifest, error)
ReadDurableDeliveryRecoveryManifest strictly decodes and validates a JSON recovery manifest.
func RecoverDurableDeliveryManifest ¶
func RecoverDurableDeliveryManifest(path, owner string) (m DurableDeliveryRecoveryManifest, err error)
RecoverDurableDeliveryManifest cleans stale writer leases and temporary files after an ungraceful process termination and returns a versioned recovery manifest describing the recovered spool state. It requires an existing owned marker and validates all committed OTLP requests and accounting bounds before removing anything. Payloads may be metrics or logs; opening a writer applies its smaller limits. Cleanup failures return an error and no manifest. Any unfinished on-disk state remains for an explicit subsequent recovery after the failure is corrected; this call closes its handles and does not retain a writer lease on return.
type DurableDeliveryStats ¶
type DurableDeliveryStats struct {
DeliveryStats
SpooledBatches uint64 // Batches successfully committed to disk
SpooledBytes uint64 // Payload bytes committed to disk
RecoveredBatches uint64 // Batches recovered from disk on startup
EvictedBatches uint64 // Undelivered batches removed for exceeding MaxSpoolAge
PendingSpool int // Current uncompleted batches on disk
PendingSpoolBytes int64 // Current uncompleted payload bytes on disk
}
DurableDeliveryStats records cumulative durable delivery outcomes. It separates producer admission drops (budget exhaustion) from downstream delivery failures.
type ECCCounts ¶
type ECCCounts struct {
SRAMCorrectable Value `xml:"sram_correctable"`
SRAMUncorrectable Value `xml:"sram_uncorrectable"`
SRAMUncorrectableParity Value `xml:"sram_uncorrectable_parity"`
SRAMUncorrectableSECDED Value `xml:"sram_uncorrectable_secded"`
DRAMCorrectable Value `xml:"dram_correctable"`
DRAMUncorrectable Value `xml:"dram_uncorrectable"`
SRAMThresholdExceeded Value `xml:"sram_threshold_exceeded"`
SingleBit ECCLocations `xml:"single_bit"`
DoubleBit ECCLocations `xml:"double_bit"`
}
ECCCounts holds one set of ECC error counts. Most reports use the SRAM and DRAM fields; newer ones split SRAMUncorrectable into SRAMUncorrectableParity and SRAMUncorrectableSECDED, and some older ones use SingleBit and DoubleBit instead.
type ECCErrors ¶
ECCErrors holds ECC error counts since the driver loaded (Volatile) and over the GPU's lifetime (Aggregate).
type ECCLocations ¶
type ECCLocations struct {
DeviceMemory Value `xml:"device_memory"`
RegisterFile Value `xml:"register_file"`
L1Cache Value `xml:"l1_cache"`
L2Cache Value `xml:"l2_cache"`
TextureMemory Value `xml:"texture_memory"`
TextureShm Value `xml:"texture_shm"`
CBU Value `xml:"cbu"`
Total Value `xml:"total"`
}
ECCLocations holds ECC error counts by location, as in some older reports.
type Element ¶
type Element struct {
XMLName xml.Name
Attrs []xml.Attr `xml:",any,attr"`
Text string `xml:",chardata"`
Children []Element `xml:",any"`
}
An Element is an XML element kept without interpretation.
type EnergySummary ¶
type EnergySummary struct {
StartMonoNanos int64 `json:"start_mono_nanos"`
EndMonoNanos int64 `json:"end_mono_nanos"`
DeviceUUID string `json:"device_uuid"`
WindowName string `json:"window_name"`
Method string `json:"method"` // "cumulative_counter" or "integrated_power"
StartEnergyMJ uint64 `json:"start_energy_mj"`
EndEnergyMJ uint64 `json:"end_energy_mj"`
EnergyConsumedMJ uint64 `json:"energy_consumed_mj"`
EnergyConsumedJoules float64 `json:"energy_consumed_joules"`
CoveredDurationNanos int64 `json:"covered_duration_nanos"`
TotalDurationNanos int64 `json:"total_duration_nanos"`
CoverageRatio float64 `json:"coverage_ratio"`
ResetDetected bool `json:"reset_detected"`
Valid bool `json:"valid"`
Reason string `json:"reason,omitempty"`
}
EnergySummary reports energy consumed in a window.
func IntegratePowerToEnergy ¶
func IntegratePowerToEnergy(windowName, deviceUUID string, powerReadings []SamplePoint, startMono, endMono int64, opts WindowOptions) EnergySummary
IntegratePowerToEnergy computes energy by integrating milliwatt readings over time as a fallback. Timestamps must be strictly increasing, including for unavailable points. Unsorted points and all duplicate timestamps (even equal values) are refused, rather than selecting or counting a repeated interval.
Example (TimeOrder) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
points := []telemetry.SamplePoint{
{Timestamp: 0, Value: 1000, Available: true},
{Timestamp: 1e9, Value: 1000, Available: true},
{Timestamp: 0, Value: 1000, Available: true},
{Timestamp: 1e9, Value: 1000, Available: true},
}
energy := telemetry.IntegratePowerToEnergy("measurement", "GPU-example", points, 0, 1e9, telemetry.WindowOptions{})
fmt.Println(energy.Valid, energy.Reason)
}
Output: false non_increasing_sample_time
type Entity ¶
Entity is an explicitly reported entity, not necessarily a GPU. The GPU group is identified by the producer's numeric entity_group_id value 1.
type EntityAssignment ¶
type EntityAssignment struct {
Process EntityProcess `json:"process"`
Device DeviceMetadata `json:"device"`
Owner EntityOwner `json:"owner"`
Source string `json:"source"`
SourceRevision string `json:"source_revision"`
Provenance []EntityProvenance `json:"provenance,omitempty"`
Authoritative bool `json:"authoritative"`
State string `json:"state"` // assigned, unknown, or contradictory
ClockDomain string `json:"clock_domain"`
ClockEpoch string `json:"clock_epoch"`
StartNanos int64 `json:"start_nanos"`
EndNanos int64 `json:"end_nanos"`
Sharing string `json:"sharing"` // unknown, exclusive, time_slice, mig, or mps
MIGConfigurationEpoch string `json:"mig_configuration_epoch,omitempty"`
MPSRole string `json:"mps_role,omitempty"` // unknown, server, or client
MPSServer *EntityProcess `json:"mps_server,omitempty"`
}
EntityAssignment records a relationship valid in [StartNanos, EndNanos). It does not assign device consumption, power, or a kernel to its owner. Authoritative means the supplying metadata authority asserted the relationship; reading JSON does not authenticate that authority.
func ComposeEntityAssignment ¶
func ComposeEntityAssignment(allocation, execution EntityAssignment) (EntityAssignment, error)
ComposeEntityAssignment intersects independently supplied allocation and execution proofs. Both proofs must assert an authoritative assigned relation with the same device and an explicit stable owner ID in common. Display names, bare scheduler job IDs and raw opaque plugin IDs cannot establish that bridge. Execution identity must include independently known birth, namespace and exec generation. The caller, not this function, authenticates supplying authorities. Neither allocation nor process presence assigns device consumption or kernels.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsworkload"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
allocation := telemetry.EntityAssignment{Device: telemetry.DeviceMetadata{UUID: "GPU-a"}, Owner: telemetry.EntityOwner{PodUID: "verified-uid"}, Source: "allocation_export", SourceRevision: "fixture-a", Authoritative: true, State: "assigned", ClockDomain: "monotonic", ClockEpoch: "boot-a", StartNanos: 10, EndNanos: 50, Sharing: "unknown"}
execution := allocation
execution.Source = "process_binding"
execution.SourceRevision = "fixture-b"
execution.StartNanos = 20
execution.Process = telemetry.EntityProcess{Process: obsworkload.ProcessGenID{PID: 12, Generation: 400}, BootID: "boot-a", NodeID: "node-a", PIDNamespace: "pid:[100]", HasExecGeneration: true}
joined, err := telemetry.ComposeEntityAssignment(allocation, execution)
if err != nil {
panic(err)
}
fmt.Println(joined.StartNanos, joined.EndNanos, len(joined.Provenance), joined.Sharing)
}
Output: 20 50 2 unknown
func EntityRelationships ¶
func EntityRelationships(assignments []EntityAssignment, deviceUUID, clockDomain, clockEpoch string, at int64) ([]EntityAssignment, error)
EntityRelationships returns all asserted, authoritative relationships at a timestamp in the supplied clock epoch. Multiple results mean shared or ambiguous allocation, never multiple copies of whole-device consumption.
func (EntityAssignment) Validate ¶
func (a EntityAssignment) Validate() error
Validate checks structural consistency, without upgrading metadata trust.
type EntityCache ¶
type EntityCache struct {
// contains filtered or unexported fields
}
EntityCache is a bounded relationship cache keyed by boot, process birth, namespace and exec generation. The zero value is not usable; use NewEntityCache. Entries expire at the lesser of their interval end and a caller supplied TTL. It neither discovers nor authenticates assignments.
func NewEntityCache ¶
func NewEntityCache(capacity int, ttlNanos int64) (*EntityCache, error)
NewEntityCache creates a cache with a positive capacity and TTL in nanoseconds.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsworkload"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
c, err := telemetry.NewEntityCache(2, 10)
if err != nil {
panic(err)
}
a := telemetry.EntityAssignment{Process: telemetry.EntityProcess{Process: obsworkload.ProcessGenID{PID: 12, Generation: 400}, BootID: "boot-a", NodeID: "node-a", PIDNamespace: "pid:[100]", HasExecGeneration: true}, Device: telemetry.DeviceMetadata{UUID: "GPU-a"}, Owner: telemetry.EntityOwner{JobID: "42"}, Source: "scheduler", SourceRevision: "fixture-v1", Authoritative: true, State: "assigned", ClockDomain: "monotonic", ClockEpoch: "boot-a", StartNanos: 10, EndNanos: 30, Sharing: "time_slice"}
if err := c.Put([]telemetry.EntityAssignment{a}, 10); err != nil {
panic(err)
}
fmt.Println(len(c.Get(a, 19)), len(c.Get(a, 20)))
}
Output: 1 0
func (*EntityCache) Clear ¶
func (c *EntityCache) Clear()
Clear removes all relationships and job completion markers, for example after a metadata authority restart.
func (*EntityCache) CompleteJob ¶
func (c *EntityCache) CompleteJob(owner EntityOwner) error
CompleteJob removes every relationship set containing the exact owner and prevents that owner from being reinserted until Clear. JobID must be present; callers must supply the original stable allocation and attempt fields too. Completion markers are bounded by the cache capacity and persisted by SaveFile.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsworkload"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
"path/filepath"
)
func entityCacheExample() (*telemetry.EntityCache, telemetry.EntityAssignment, string, func()) {
base, err := os.UserCacheDir()
if err != nil {
panic(err)
}
base = filepath.Join(base, "nvtelemetry-examples")
if err := os.MkdirAll(base, 0700); err != nil {
panic(err)
}
base, err = filepath.EvalSymlinks(base)
if err != nil {
panic(err)
}
dir, err := os.MkdirTemp(base, "entity-")
if err != nil {
panic(err)
}
cache, err := telemetry.NewEntityCache(8, 10)
if err != nil {
panic(err)
}
a := telemetry.EntityAssignment{Process: telemetry.EntityProcess{Process: obsworkload.ProcessGenID{PID: 12, Generation: 400}, BootID: "boot-a", NodeID: "node-a", PIDNamespace: "pid:[100]", HasExecGeneration: true}, Device: telemetry.DeviceMetadata{UUID: "GPU-a"}, Owner: telemetry.EntityOwner{JobID: "42", Attempt: "1"}, Source: "scheduler", SourceRevision: "fixture-v1", State: "assigned", ClockDomain: "monotonic", ClockEpoch: "boot-a", StartNanos: 10, EndNanos: 30, Sharing: "unknown"}
return cache, a, filepath.Join(dir, "entities.json"), func() { os.RemoveAll(dir) }
}
func main() {
cache, a, _, cleanup := entityCacheExample()
defer cleanup()
if err := cache.Put([]telemetry.EntityAssignment{a}, 10); err != nil {
panic(err)
}
if err := cache.CompleteJob(a.Owner); err != nil {
panic(err)
}
fmt.Println(len(cache.Get(a, 11)), cache.Put([]telemetry.EntityAssignment{a}, 11) != nil)
}
Output: 0 true
func (*EntityCache) Get ¶
func (c *EntityCache) Get(query EntityAssignment, now int64) []EntityAssignment
Get returns a cloned relationship set for the exact key of query. Misses, incomplete generations and expired entries yield no relationships.
func (*EntityCache) LoadFile ¶
func (c *EntityCache) LoadFile(path string, scope EntityCacheScope, now int64) (discarded bool, err error)
LoadFile replaces relationships with current entries from path. It preserves their original expiry and caps it by this cache's TTL from the original insert time. Entries from other hosts, boots or clock domains/epochs are discarded. Completion markers already in memory and those saved in the file prevent stale relationships for an exactly matching owner from being loaded again. Clear explicitly resets those markers.
Missing files leave a clean relationship cache. Corrupt, oversized, invalid or unsupported files also leave it clean and return discarded=true, err=nil; the corrupt file is retained until a successful SaveFile replaces it. I/O and path errors return an error and leave memory unchanged. The file checksum is not authentication or rollback protection. No TTL restarts on load.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsworkload"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
"path/filepath"
)
func entityCacheExample() (*telemetry.EntityCache, telemetry.EntityAssignment, string, func()) {
base, err := os.UserCacheDir()
if err != nil {
panic(err)
}
base = filepath.Join(base, "nvtelemetry-examples")
if err := os.MkdirAll(base, 0700); err != nil {
panic(err)
}
base, err = filepath.EvalSymlinks(base)
if err != nil {
panic(err)
}
dir, err := os.MkdirTemp(base, "entity-")
if err != nil {
panic(err)
}
cache, err := telemetry.NewEntityCache(8, 10)
if err != nil {
panic(err)
}
a := telemetry.EntityAssignment{Process: telemetry.EntityProcess{Process: obsworkload.ProcessGenID{PID: 12, Generation: 400}, BootID: "boot-a", NodeID: "node-a", PIDNamespace: "pid:[100]", HasExecGeneration: true}, Device: telemetry.DeviceMetadata{UUID: "GPU-a"}, Owner: telemetry.EntityOwner{JobID: "42", Attempt: "1"}, Source: "scheduler", SourceRevision: "fixture-v1", State: "assigned", ClockDomain: "monotonic", ClockEpoch: "boot-a", StartNanos: 10, EndNanos: 30, Sharing: "unknown"}
return cache, a, filepath.Join(dir, "entities.json"), func() { os.RemoveAll(dir) }
}
func main() {
cache, a, path, cleanup := entityCacheExample()
defer cleanup()
if err := cache.Put([]telemetry.EntityAssignment{a}, 10); err != nil {
panic(err)
}
if err := cache.SaveFile(path); err != nil {
panic(err)
}
restored, err := telemetry.NewEntityCache(8, 100)
if err != nil {
panic(err)
}
scope := telemetry.EntityCacheScope{BootID: a.Process.BootID, NodeID: a.Process.NodeID, ClockDomain: a.ClockDomain, ClockEpoch: a.ClockEpoch}
discarded, err := restored.LoadFile(path, scope, 19)
if err != nil {
panic(err)
}
fmt.Println(discarded, len(restored.Get(a, 19)), len(restored.Get(a, 20)))
}
Output: false 1 0
func (*EntityCache) Put ¶
func (c *EntityCache) Put(assignments []EntityAssignment, now int64) error
Put replaces relationships for a single exact cache key at now in the assignment clock. Contradictions and unknown state are retained, not promoted. Reusing a PID without the same birth and exec generation cannot hit this entry.
func (*EntityCache) SaveFile ¶
func (c *EntityCache) SaveFile(path string) (err error)
SaveFile atomically replaces path with a bounded versioned cache snapshot. The caller must exclusively own its existing private parent directory and serialize other processes using the same file. Path must be absolute, clean, outside OS temporary directories and free of symlinks. Use a persistent project scratch directory; this method creates neither parent directories nor a second attribution model. Files have mode 0600.
SaveFile syncs the new file, renames it and syncs the parent directory. An error after rename can leave the new file installed; an error is not a rollback promise. The checksum detects corruption, not malicious replacement or rollback, and persistence does not authenticate or upgrade metadata trust.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsworkload"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"os"
"path/filepath"
)
func entityCacheExample() (*telemetry.EntityCache, telemetry.EntityAssignment, string, func()) {
base, err := os.UserCacheDir()
if err != nil {
panic(err)
}
base = filepath.Join(base, "nvtelemetry-examples")
if err := os.MkdirAll(base, 0700); err != nil {
panic(err)
}
base, err = filepath.EvalSymlinks(base)
if err != nil {
panic(err)
}
dir, err := os.MkdirTemp(base, "entity-")
if err != nil {
panic(err)
}
cache, err := telemetry.NewEntityCache(8, 10)
if err != nil {
panic(err)
}
a := telemetry.EntityAssignment{Process: telemetry.EntityProcess{Process: obsworkload.ProcessGenID{PID: 12, Generation: 400}, BootID: "boot-a", NodeID: "node-a", PIDNamespace: "pid:[100]", HasExecGeneration: true}, Device: telemetry.DeviceMetadata{UUID: "GPU-a"}, Owner: telemetry.EntityOwner{JobID: "42", Attempt: "1"}, Source: "scheduler", SourceRevision: "fixture-v1", State: "assigned", ClockDomain: "monotonic", ClockEpoch: "boot-a", StartNanos: 10, EndNanos: 30, Sharing: "unknown"}
return cache, a, filepath.Join(dir, "entities.json"), func() { os.RemoveAll(dir) }
}
func main() {
cache, a, path, cleanup := entityCacheExample()
defer cleanup()
if err := cache.Put([]telemetry.EntityAssignment{a}, 10); err != nil {
panic(err)
}
if err := cache.SaveFile(path); err != nil {
panic(err)
}
fmt.Println(len(cache.Get(a, 19)))
}
Output: 1
type EntityCacheScope ¶
EntityCacheScope identifies the host and clock in which LoadFile's now is meaningful. All four fields are required. A matching scope does not establish that a saved assignment's supplying authority is authentic.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
scope := telemetry.EntityCacheScope{BootID: "boot-a", NodeID: "node-a", ClockDomain: "monotonic", ClockEpoch: "boot-a"}
fmt.Println(scope.BootID, scope.ClockDomain)
}
Output: boot-a monotonic
type EntityEvaluation ¶
type EntityEvaluation struct {
Matched, Wrong, Missing, Ambiguous int
Precision, Recall float64
HasPrecision, HasRecall bool
}
EntityEvaluation reports results against caller-provided positive ground truth in corresponding slice order. No score establishes native accuracy.
func EvaluateEntityResolutions ¶
func EvaluateEntityResolutions(truth []EntityAssignment, observed []EntityResolution) (EntityEvaluation, error)
EvaluateEntityResolutions evaluates bounded, independently supplied ground truth. Wrong exact identities return ErrIdentityMismatch with the counts.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
result, err := telemetry.EvaluateEntityResolutions(nil, nil)
fmt.Println(result.HasPrecision, result.HasRecall, err)
}
Output: false false <nil>
type EntityExport ¶
type EntityExport struct {
Version int `json:"version"`
Assignments []EntityAssignment `json:"assignments"`
}
EntityExport is the version 1 allocation relationship interchange document. It is not a Kubernetes, Slurm, or NVML native response.
func ReadEntityExport ¶
func ReadEntityExport(r io.Reader) (EntityExport, error)
ReadEntityExport reads a bounded strict version 1 interchange document.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
a := telemetry.EntityAssignment{Device: telemetry.DeviceMetadata{UUID: "GPU-a"}, Owner: telemetry.EntityOwner{PodUID: "uid-a"}, Source: "allocation_authority", SourceRevision: "fixture-v1", Authoritative: true, State: "assigned", ClockDomain: "monotonic", ClockEpoch: "boot-a", StartNanos: 10, EndNanos: 30, Sharing: "time_slice"}
var b bytes.Buffer
if err := telemetry.WriteEntityExport(&b, telemetry.EntityExport{Version: 1, Assignments: []telemetry.EntityAssignment{a}}); err != nil {
panic(err)
}
export, err := telemetry.ReadEntityExport(&b)
if err != nil {
panic(err)
}
relationships, err := telemetry.EntityRelationships(export.Assignments, "GPU-a", "monotonic", "boot-a", 20)
if err != nil {
panic(err)
}
fmt.Println(len(relationships), relationships[0].Owner.PodUID)
}
Output: 1 uid-a
type EntityOwner ¶
type EntityOwner struct {
PodUID string `json:"pod_uid,omitempty"`
ContainerID string `json:"container_id,omitempty"`
JobID string `json:"job_id,omitempty"`
AllocationID string `json:"allocation_id,omitempty"`
Attempt string `json:"attempt,omitempty"`
}
EntityOwner identifies an allocation recipient by stable identifiers rather than display names. Empty identifiers remain unknown.
type EntityProcess ¶
type EntityProcess struct {
Process obsworkload.ProcessGenID `json:"process"`
BootID string `json:"boot_id"`
NodeID string `json:"node_id"`
PIDNamespace string `json:"pid_namespace,omitempty"`
NamespacePIDs []uint32 `json:"namespace_pids,omitempty"`
ExecGeneration uint64 `json:"exec_generation,omitempty"`
HasExecGeneration bool `json:"has_exec_generation"`
}
type EntityProvenance ¶
type EntityProvenance struct {
Source string `json:"source"`
Revision string `json:"revision"`
StartNanos int64 `json:"start_nanos"`
EndNanos int64 `json:"end_nanos"`
}
EntityProvenance identifies a supplying assignment observation and its original validity interval in the containing assignment's clock domain and epoch.
type EntityResolution ¶
type EntityResolution struct {
Assignment EntityAssignment
Reason string
}
EntityResolution retains an unresolved observation instead of guessing a relationship. Reason is empty only for an assigned relationship.
func ResolvePodResourceAssignments ¶
func ResolvePodResourceAssignments(resources []PodResourceAllocation, pods []PodEntityMetadata, bindings []PluginDeviceBinding, execution []EntityAssignment) ([]EntityResolution, error)
ResolvePodResourceAssignments joins actual PodResources names with core/v1 stable UID/container identities, authenticated plugin mappings and execution proofs. It returns one result per opaque device ID. Overlapping metadata or mappings are ambiguous even when they happen to name the same GPU.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
s := telemetry.EntitySnapshot{SourceRevision: "v1.32.0", ClockDomain: "mono", ClockEpoch: "boot", StartNanos: 0, EndNanos: 10}
r := telemetry.PodResourceAllocation{Namespace: "default", PodName: "worker", ContainerName: "worker", ResourceName: "nvidia.com/gpu", DeviceIDs: []string{"opaque"}, Snapshot: s}
result, err := telemetry.ResolvePodResourceAssignments([]telemetry.PodResourceAllocation{r}, nil, nil, nil)
fmt.Println(result[0].Assignment.State, result[0].Reason, err)
}
Output: unknown missing_authoritative_mapping <nil>
func ResolveSlurmAssignments ¶
func ResolveSlurmAssignments(jobs []SlurmAllocation, mappings, execution []EntityAssignment) ([]EntityResolution, error)
ResolveSlurmAssignments requires a separate authoritative allocation attempt and device mapping. Job ID, TRES counts, environment variables and node-list spelling do not establish GPU or process identity. Multiple matching mappings remain ambiguous; callers should split observations by device when necessary.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
s := telemetry.EntitySnapshot{SourceRevision: "25.05", ClockDomain: "mono", ClockEpoch: "boot", StartNanos: 0, EndNanos: 10}
result, err := telemetry.ResolveSlurmAssignments([]telemetry.SlurmAllocation{{JobID: "42", State: []string{"RUNNING"}, Snapshot: s}}, nil, nil)
fmt.Println(result[0].Assignment.State, result[0].Reason, err)
}
Output: unknown missing_allocation_attempt <nil>
type EntitySnapshot ¶
type EntitySnapshot struct {
SourceRevision string
Authoritative bool
NodeID string
ClockDomain string
ClockEpoch string
StartNanos int64
EndNanos int64
}
EntitySnapshot supplies independently collected provenance and observation validity to vendor exports, whose content does not authenticate the collector.
type Entry ¶
type Entry struct {
Code uint64
Name string
Description string
ImmediateAction string
InvestigatoryAction string
RecoveryActionEvent bool
}
Entry describes an XID. Action fields are NVIDIA's resolution bucket names, including workflow identifiers requiring further investigation. An empty action is unspecified; it is not evidence that no action is required.
func Lookup ¶
func Lookup(id uint64, architecture Architecture) (Entry, bool)
Lookup returns a catalog entry only if it applies to architecture. XID154 reports a change to the GPU's recovery action; inspect the actual event's recovery value rather than inferring a reset or reboot from its ID alone.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
e, ok := telemetry.Lookup(13, telemetry.H100)
fmt.Println(ok, e.Description, e.ImmediateAction)
_, ok = telemetry.Lookup(999, telemetry.H100)
fmt.Println(ok)
}
Output: true Graphics Engine Exception RESTART_APP false
func LookupRaw ¶
LookupRaw returns the catalog row without interpreting product coverage.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
entry, known := telemetry.LookupRaw(154)
fmt.Println(entry.Name, known)
}
Output: GPU_RECOVERY_ACTION_CHANGED true
type Envelope ¶
type Envelope struct {
SchemaVersion int `json:"schema_version"`
ToolVersion string `json:"tool_version"`
Format string `json:"format"`
SourcePath string `json:"source_path"`
ReportDigest string `json:"report_digest"`
CSVDigest string `json:"csv_digest"`
CSV string `json:"csv"`
Bindings []Binding `json:"bindings"`
}
Envelope versions the project export contract. ReportDigest identifies the original opaque report, as supplied by its producer; CSVDigest is checked against CSV. SourcePath is provenance only and is never opened.
func ReadNCU ¶
Read reads one strict envelope with a positive byte budget no larger than MaxBytes. The original encoded input, including whitespace, counts against the budget. Duplicate, aliased, unknown, and trailing JSON fields are refused.
Example ¶
package main
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
// exampleEnvelope is a synthetic exporter control, not a vendor report.
func exampleEnvelope() telemetry.Envelope {
csv := "ID,Process ID,Process Name,Host Name,Kernel Name,Context,Stream,Block Size,Grid Size,Device,CC,Section Name,Metric Name,Metric Unit,Metric Value,Rule Name,Rule Type,Rule Description,Estimated Speedup Type,Estimated Speedup\n" +
"0,1,example,host,kernel,1,1,\"(1, 1, 1)\",\"(1, 1, 1)\",0,9.0,Timing,gpu__time_duration.sum,ns,42,\n"
return telemetry.Envelope{SchemaVersion: 1, ToolVersion: telemetry.ToolVersion, Format: telemetry.NCUFormat, SourcePath: "synthetic example", ReportDigest: fmt.Sprintf("%x", sha256.Sum256([]byte("synthetic example"))), CSVDigest: fmt.Sprintf("%x", sha256.Sum256([]byte(csv))), CSV: csv}
}
func main() {
b, _ := json.Marshal(exampleEnvelope())
e, err := telemetry.ReadNCU(bytes.NewReader(b), 1<<20)
fmt.Println(err, e.ToolVersion, e.Format)
}
Output: <nil> 2026.3.0.0 ncu-details-csv-2026.3.0
type Environment ¶
type Environment struct {
State string `json:"state"`
Reasons []EnvironmentReason `json:"reasons"` // empty, never nil, when State is clear
Arms []ArmCheck `json:"arms"`
Limits string `json:"limits"`
}
An Environment is the verdict over the arms of one comparison.
func JudgeArms ¶
func JudgeArms(arms []ArmCheck, tolerance float64) Environment
JudgeArms judges arms together. tolerance is Stable's.
A foreign process, a clock-reducing event (any clocks-event bit other than gpu_idle, applications_clocks_setting and display_clocks_setting, named or not), or SM clocks further apart than tolerance among the arms of one group make the environment void. Missing or thin evidence makes it unchecked. It is clear only when every arm has at least two process samples and the clock evidence Stable requires, and nothing was seen.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
// A real caller gets each ArmCheck from an ArmObserver:
// o, err := telemetry.OpenArmObserver(0, telemetry.MonitorConfig{}, owned)
// err = o.Start("target")
// start := o.Now()
// ... run the arm ...
// check := o.Finish(start, o.Now())
arms := []telemetry.ArmCheck{{
Arm: "base",
ProcessSamples: 2,
ClockSamples: 5, ClockCoverage: 1,
SMClockMinMHz: 2040, SMClockMaxMHz: 2040, SMClockMeanMHz: 2040,
}, {
Arm: "target",
ProcessSamples: 2,
Foreign: []telemetry.DeviceProcess{{PID: 4242}},
ClockSamples: 5, ClockCoverage: 1,
SMClockMinMHz: 2040, SMClockMaxMHz: 2040, SMClockMeanMHz: 2040,
}}
env := telemetry.JudgeArms(arms, 0)
fmt.Println(env.State)
for _, r := range env.Reasons {
fmt.Printf("%s: %s\n", r.Kind, r.Text)
}
}
Output: void foreign_process: arm target: foreign process 4242 on the device
func (Environment) Require ¶
func (e Environment) Require(clear bool) error
Require returns an error if e is void, or, when clear is set, if e is anything but clear. The error names the state and every reason's Text.
type EnvironmentReason ¶
type EnvironmentReason struct {
Kind string `json:"kind"`
Arm string `json:"arm,omitempty"` // empty for a finding about a group of arms
Text string `json:"text"`
}
An EnvironmentReason is one finding of JudgeArms. Callers decide by Kind; Text is for people and may be reworded.
type Error ¶
type Error struct {
Args []string // arguments after "nvidia-smi"
Code int // exit status
Stdout []byte
Stderr []byte
}
An Error reports that nvidia-smi exited with a nonzero status. nvidia-smi writes some failure reasons to standard output rather than standard error, so both are kept.
type Event ¶
type Event struct {
Table string
StartNS int64
EndNS *int64
Name string
Correlation *int64
Process *uint64
Bytes *int64
Raw json.RawMessage
}
Event retains one exported row. StartNS/EndNS use the source's clock domain; nil EndNS can be a marker or an open range and is not replaced with StartNS. Process retains the serialized target/process part of GlobalId. Raw retains all documented fields, including geometry, payload and enum values.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
e := telemetry.Event{StartNS: 100}
fmt.Println(e.StartNS, e.EndNS == nil)
}
Output: 100 true
type ExportOptions ¶
type ExportOptions struct {
UnixTimeMapping *UnixTimeMapping
HistogramBindings []HistogramBinding
MaxMetrics int
MaxExplicitBounds int
MaxReadings, MaxBytes int
OpenMetrics bool
CounterStartUnixNanos int64
HasCounterStart bool
// ClockDomain identifies the caller-declared fixed clock cohort. Empty is unknown.
ClockDomain string
// HasClockCalibration distinguishes a known zero bound from an unknown bound.
// It requires ClockDomain; the caller supplies the calibration evidence.
HasClockCalibration bool
ClockCalibrationBoundsNanos int64
}
ExportOptions selects a bounded snapshot encoding. Metrics use private names gpu.* for registered device metrics, not the developmental OpenTelemetry hardware conventions. Resource and point attributes remain nvtelemetry.*. CounterStartUnixNanos must be explicitly known for cumulative OTLP counters.
type ExpositionOptions ¶
type ExpositionOptions struct {
Format string
MaxBytes int64
MaxSamples, MaxLabels, MaxLabelBytes, MaxLineBytes int
}
ExpositionOptions bounds an offline exposition read. Zero limits use defaults.
type ExpositionSample ¶
type ExpositionSample struct {
Name string
Labels map[string]string
RawValue, Type, Unit string
TimestampUnix int64
HasTimestamp bool
RawTimestamp string
TimestampUnit string
}
ExpositionSample retains a producer's numeric text without float conversion. TimestampUnix is an exposition timestamp, not a sensor timestamp.
func ReadExposition ¶
func ReadExposition(ctx context.Context, r io.Reader, o ExpositionOptions) ([]ExpositionSample, error)
ReadExposition reads Prometheus text or OpenMetrics. It preserves histogram components without interpreting their buckets. Summaries and exemplars are refused. Cancellation is checked between reads; callers must close a blocked reader or use a context-aware transport to interrupt its Read call.
Example ¶
s, err := ReadExposition(context.Background(), strings.NewReader("power_watts{UUID=\"GPU-a\"} 12.5\n"), ExpositionOptions{})
fmt.Println(s[0].Name, s[0].RawValue, err)
Output: power_watts 12.5 <nil>
type Fabric ¶
type Fabric struct {
State Value `xml:"state"`
Status Value `xml:"status"`
CliqueID Value `xml:"cliqueId"`
ClusterUUID Value `xml:"clusterUuid"`
HealthSummary Value `xml:"health>summary"`
Bandwidth Value `xml:"health>bandwidth"`
RouteRecoveryInProgress Value `xml:"health>route_recovery_in_progress"`
RouteUnhealthy Value `xml:"health>route_unhealthy"`
AccessTimeoutRecovery Value `xml:"health>access_timeout_recovery"`
IncorrectConfiguration Value `xml:"health>incorrect_configuration"`
PartitionAssigned Value `xml:"health>partition_assigned"`
}
Fabric reports NVLink fabric registration, as on GB200 and H100 NVSwitch systems. Other GPUs report N/A.
type FakeClock ¶
type FakeClock struct {
// contains filtered or unexported fields
}
FakeClock provides deterministic time control for reproducible testing.
func NewFakeClock ¶
NewFakeClock creates a FakeClock with initialized timestamps and a distinct epoch ID.
func (*FakeClock) MonotonicDomain ¶
MonotonicDomain returns the synthetic domain of FakeClock.
func (*FakeClock) MonotonicEpochID ¶
MonotonicEpochID returns the synthetic epoch ID of FakeClock. If unconfigured or zero-valued, it returns an empty string (unqualified identity).
func (*FakeClock) NowMonotonic ¶
NowMonotonic returns the current fake monotonic time.
func (*FakeClock) Provenance ¶
Provenance returns the synthetic provenance.
func (*FakeClock) SetEpochID ¶
SetEpochID configures the monotonic epoch ID explicitly (e.g. for coordinated test fixtures).
func (*FakeClock) StepWall ¶
StepWall simulates a wall-clock jump (e.g. NTP adjustment) without changing monotonic time.
func (*FakeClock) WallDomain ¶
WallDomain returns the synthetic wall domain.
type FakeSampler ¶
type FakeSampler struct {
// contains filtered or unexported fields
}
FakeSampler provides deterministic scripted telemetry for offline testing.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
sampler := telemetry.NewFakeSampler(telemetry.DeviceMetadata{
UUID: "GPU-EXAMPLE-1",
Index: 0,
Model: "NVIDIA L4",
})
sampler.Enqueue([]telemetry.Reading{
{
Name: telemetry.MetricGPUUtilization,
Unit: telemetry.UnitPercent,
Backend: "fake",
DeviceUUID: "GPU-EXAMPLE-1",
Evidence: telemetry.EvidenceMeasured,
Value: 78.5,
},
})
readings, err := sampler.Sample(context.Background())
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
for _, r := range readings {
fmt.Printf("%s: %.1f %s (%s)\n", r.Name, r.Value, r.Unit, r.Evidence)
}
}
Output: gpu_utilization_pct: 78.5 percent (measured)
func NewFakeSampler ¶
func NewFakeSampler(devices ...DeviceMetadata) *FakeSampler
NewFakeSampler creates a fake sampler with the provided device metadata.
func (*FakeSampler) Devices ¶
func (f *FakeSampler) Devices() []DeviceMetadata
Devices returns the configured fake devices.
func (*FakeSampler) Enqueue ¶
func (f *FakeSampler) Enqueue(batches ...[]Reading)
Enqueue appends batches of scripted readings to be returned by successive calls to Sample.
func (*FakeSampler) Sample ¶
func (f *FakeSampler) Sample(ctx context.Context) ([]Reading, error)
Sample returns the next scripted batch of readings.
func (*FakeSampler) SetFallback ¶
func (f *FakeSampler) SetFallback(fn func(ctx context.Context) ([]Reading, error))
SetFallback configures a handler invoked when scripted batches are exhausted.
type Field ¶
type Field struct {
Value uint64
}
A Field is one sampled value. A field NVML did not return is recorded with the reason in Unavailable and a zero Value that is not a reading.
type FieldSummary ¶
A FieldSummary summarizes one field over a window. Samples counts the samples that held a reading. When it is zero, Unavailable says why and Min, Max and Mean are not readings.
type Fitness ¶
Fitness is the verdict of CheckFitness. Unfit holds why a GPU is not fit to run work. Unknown holds what could not be judged because a GPU does not support the query or no snapshot observed it.
func CheckFitness ¶
func CheckFitness(health []HealthSnapshot, procs map[string][]NVMLProcessFact, want FitnessWant) Fitness
CheckFitness reports whether each GPU in health is fit to run work. A GPU is every device in a snapshot's DeviceStates; a GPU may appear in several snapshots, such as those of NVMLHealthReader and NVMLFabricReader.
A GPU is unfit if it is lost or its state is unknown, if it has uncorrected volatile ECC errors, a pending page retirement or row remap, or a failed row remap, if its fabric probe has not completed or completed with an error, or if a health query failed. Retired pages are judged only for a failed query: retirement is the remedy, a pending one the fault. A health reading the GPU does not support, or that no snapshot holds, is unknown, not unfit; a GPU reporting no fabric is neither.
If want.Free is set, procs must hold the process facts of each GPU by UUID, as QueryNVMLProcesses returns them, and a GPU with a fact or without an entry is unfit. If want.MaxMemoryUsed is set, a GPU whose memory_used_bytes observation is above it, or missing, is unfit. Neither NVMLHealthReader nor NVMLFabricReader reads memory: the caller must add a raw memory_used_bytes observation to a snapshot, for example from nvml.Device.MemoryInfo. An asked-for requirement that cannot be judged is unfit, so a busy GPU never reads as free. No GPUs is unfit.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
reading := func(name string, v uint64) telemetry.HealthObservation {
return telemetry.HealthObservation{SourceID: "nvml", Class: "raw", Reading: telemetry.Reading{
Name: name, DeviceUUID: "GPU-0", Evidence: telemetry.EvidenceMeasured, IsInt: true, IntValue: v,
}}
}
health := telemetry.HealthSnapshot{
DeviceStates: map[string]string{"GPU-0": "present"},
Observations: []telemetry.HealthObservation{
reading("ecc_uncorrected_errors", 0),
reading("retired_pages_multiple_single_bit_ecc", 2),
reading("retired_pages_double_bit_ecc", 0),
reading("retired_pages_pending", 1),
reading("repair_pending", 0),
reading("remap_failure", 0),
},
}
procs := map[string][]telemetry.NVMLProcessFact{"GPU-0": {{PID: 4242}}}
f := telemetry.CheckFitness([]telemetry.HealthSnapshot{health}, procs, telemetry.FitnessWant{Free: true})
fmt.Println("fit:", f.Fit())
for _, why := range f.Unfit {
fmt.Println("unfit:", why)
}
for _, what := range f.Unknown {
fmt.Println("unknown:", what)
}
}
Output: fit: false unfit: gpu GPU-0: page retirement pending; reset the GPU unfit: gpu GPU-0: process count 1 unknown: gpu GPU-0: fabric_state not observed
type FitnessWant ¶
type FitnessWant struct {
Free bool // the GPU has no process
MaxMemoryUsed uint64 // if not zero, the GPU uses at most this many bytes
}
FitnessWant is what CheckFitness requires of each GPU beyond health.
type GPUCollection ¶
type GPUCollection struct {
DeviceUUID string
Tier string
Readings []Reading
Capabilities CapabilitySet
GPM []nvml.GpmMetric
Processes []GPUProcess
ProcessUtilization []nvml.ProcessUtilizationInfoV1
Err error
}
GPUCollection is one polling tier's observations for a device.
type GPUProcess ¶
type GPUProcess struct {
Kind string
Info nvml.ProcessInfo
MemoryAvailable bool
}
GPUProcess records a live compute or graphics context and its memory.
type GovernedSampler ¶
type GovernedSampler struct {
// contains filtered or unexported fields
}
GovernedSampler wraps an already target-scoped Sampler for use by Collector. It bounds each returned batch, rejects identity changes, and serializes sampling without queueing. Close cancels in-flight work and retains registry ownership until Sample returns. Sources must honor context cancellation; cancellation does not establish device completion. Use CaptureRegistry.NewSampler; the zero value is not a usable sampler. GovernedSampler is safe for concurrent use.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"time"
)
func exampleCapturePolicy() telemetry.CapturePolicy {
return telemetry.CapturePolicy{
Version: 1, SourceID: "nvml", AllowedDevices: []string{"GPU-0"}, MaxReadings: 32, MaxSampleBytes: 4096,
Collector: telemetry.CollectorConfig{IntervalNanos: int64(time.Millisecond), MaxRecordBudget: 20, MaxByteBudget: 32768, MaxBufferedRecords: 4, BudgetPolicy: telemetry.BudgetPolicyFail},
}
}
func main() {
p := exampleCapturePolicy()
clock := telemetry.NewFakeClock(1, 1)
var registry telemetry.CaptureRegistry
s, err := registry.NewSampler(telemetry.NewFakeSampler(telemetry.DeviceMetadata{UUID: "GPU-0"}), clock, p)
if err != nil {
panic(err)
}
defer s.Close(context.Background())
var raw bytes.Buffer
c := telemetry.NewCollector("governed", s, clock, p.Collector, telemetry.NewWriter(&raw, p.Collector))
if err := c.InitStream(); err != nil {
panic(err)
}
clock.Advance(time.Millisecond)
if err := c.Step(context.Background()); err != nil {
panic(err)
}
clock.Advance(time.Millisecond)
if _, err := c.Stop(); err != nil {
panic(err)
}
m, _, samples, err := telemetry.ReadStreamStrict(&raw, int64(p.Collector.MaxByteBudget))
if err != nil {
panic(err)
}
fmt.Println(m.IsComplete, len(samples), s.Status().SuccessfulQueries)
}
Output: true 1 1
func (*GovernedSampler) Close ¶
func (s *GovernedSampler) Close(ctx context.Context) error
Close prevents new queries, cancels the current query and waits for its return, bounded by ctx. A timeout retains ownership until the query returns; it never permits a second collector to race an unfinished source.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"time"
)
func exampleCapturePolicy() telemetry.CapturePolicy {
return telemetry.CapturePolicy{
Version: 1, SourceID: "nvml", AllowedDevices: []string{"GPU-0"}, MaxReadings: 32, MaxSampleBytes: 4096,
Collector: telemetry.CollectorConfig{IntervalNanos: int64(time.Millisecond), MaxRecordBudget: 20, MaxByteBudget: 32768, MaxBufferedRecords: 4, BudgetPolicy: telemetry.BudgetPolicyFail},
}
}
func main() {
var registry telemetry.CaptureRegistry
s, err := registry.NewSampler(telemetry.NewFakeSampler(telemetry.DeviceMetadata{UUID: "GPU-0"}), telemetry.NewFakeClock(1, 1), exampleCapturePolicy())
if err != nil {
panic(err)
}
fmt.Println(s.Close(context.Background()), s.Status().Closed)
}
Output: <nil> true
func (*GovernedSampler) Devices ¶
func (s *GovernedSampler) Devices() []DeviceMetadata
Devices returns the target-scoped metadata with independent slice/map storage.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"time"
)
func exampleCapturePolicy() telemetry.CapturePolicy {
return telemetry.CapturePolicy{
Version: 1, SourceID: "nvml", AllowedDevices: []string{"GPU-0"}, MaxReadings: 32, MaxSampleBytes: 4096,
Collector: telemetry.CollectorConfig{IntervalNanos: int64(time.Millisecond), MaxRecordBudget: 20, MaxByteBudget: 32768, MaxBufferedRecords: 4, BudgetPolicy: telemetry.BudgetPolicyFail},
}
}
func main() {
var registry telemetry.CaptureRegistry
s, err := registry.NewSampler(telemetry.NewFakeSampler(telemetry.DeviceMetadata{UUID: "GPU-0"}), telemetry.NewFakeClock(1, 1), exampleCapturePolicy())
if err != nil {
panic(err)
}
defer s.Close(context.Background())
fmt.Println(s.Devices()[0].UUID)
}
Output: GPU-0
func (*GovernedSampler) Ready ¶
func (s *GovernedSampler) Ready(nowNanos, maxAgeNanos int64) error
Ready reports query readiness against this sampler's monotonic clock. Unavailable optional fields do not make a successful query fail readiness.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"time"
)
func exampleCapturePolicy() telemetry.CapturePolicy {
return telemetry.CapturePolicy{
Version: 1, SourceID: "nvml", AllowedDevices: []string{"GPU-0"}, MaxReadings: 32, MaxSampleBytes: 4096,
Collector: telemetry.CollectorConfig{IntervalNanos: int64(time.Millisecond), MaxRecordBudget: 20, MaxByteBudget: 32768, MaxBufferedRecords: 4, BudgetPolicy: telemetry.BudgetPolicyFail},
}
}
func main() {
var registry telemetry.CaptureRegistry
s, err := registry.NewSampler(telemetry.NewFakeSampler(telemetry.DeviceMetadata{UUID: "GPU-0"}), telemetry.NewFakeClock(1, 1), exampleCapturePolicy())
if err != nil {
panic(err)
}
defer s.Close(context.Background())
if _, err := s.Sample(context.Background()); err != nil {
panic(err)
}
fmt.Println(s.Ready(1, 0))
}
Output: <nil>
func (*GovernedSampler) Sample ¶
func (s *GovernedSampler) Sample(ctx context.Context) (readings []Reading, err error)
Sample implements Sampler with no queue or background capture. Rejected batches are never returned to Collector's writer or sample hook. Opaque native string/binary diagnostics are refused because their raw bytes may contain secrets. A caller choosing the raw sampler path must separately authorize private raw capture; this wrapper never fabricates redacted bits.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"time"
)
func exampleCapturePolicy() telemetry.CapturePolicy {
return telemetry.CapturePolicy{
Version: 1, SourceID: "nvml", AllowedDevices: []string{"GPU-0"}, MaxReadings: 32, MaxSampleBytes: 4096,
Collector: telemetry.CollectorConfig{IntervalNanos: int64(time.Millisecond), MaxRecordBudget: 20, MaxByteBudget: 32768, MaxBufferedRecords: 4, BudgetPolicy: telemetry.BudgetPolicyFail},
}
}
func main() {
var registry telemetry.CaptureRegistry
s, err := registry.NewSampler(telemetry.NewFakeSampler(telemetry.DeviceMetadata{UUID: "GPU-0"}), telemetry.NewFakeClock(1, 1), exampleCapturePolicy())
if err != nil {
panic(err)
}
defer s.Close(context.Background())
readings, err := s.Sample(context.Background())
fmt.Println(len(readings), err)
}
Output: 1 <nil>
func (*GovernedSampler) Status ¶
func (s *GovernedSampler) Status() CaptureStatus
Status returns a coherent snapshot of bounded collector self-observation.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"time"
)
func exampleCapturePolicy() telemetry.CapturePolicy {
return telemetry.CapturePolicy{
Version: 1, SourceID: "nvml", AllowedDevices: []string{"GPU-0"}, MaxReadings: 32, MaxSampleBytes: 4096,
Collector: telemetry.CollectorConfig{IntervalNanos: int64(time.Millisecond), MaxRecordBudget: 20, MaxByteBudget: 32768, MaxBufferedRecords: 4, BudgetPolicy: telemetry.BudgetPolicyFail},
}
}
func main() {
var registry telemetry.CaptureRegistry
s, err := registry.NewSampler(telemetry.NewFakeSampler(telemetry.DeviceMetadata{UUID: "GPU-0"}), telemetry.NewFakeClock(1, 1), exampleCapturePolicy())
if err != nil {
panic(err)
}
defer s.Close(context.Background())
fmt.Println(s.Status().HasLastSuccess)
}
Output: false
type HealthGPU ¶
type HealthGPU struct {
PCIBusID string `json:"pci_bus_id"`
Name string `json:"name"`
UUID string `json:"uuid"`
Minor int `json:"minor"` // -1 when the XML has none, as on some platforms
}
A GPU is one <gpu> element of nvidia-smi -q -x.
func ParseSMIXML ¶
ParseSMIXML parses the output of nvidia-smi -q -x. A minor_number that is not a decimal in 0..254 (such as "N/A") gives Minor -1.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
out := `<?xml version="1.0" ?>
<nvidia_smi_log>
<gpu id="00000000:19:00.0">
<product_name>NVIDIA H200</product_name>
<uuid>GPU-1234-abcd</uuid>
<minor_number>7</minor_number>
</gpu>
</nvidia_smi_log>`
gpus, err := telemetry.ParseSMIXML([]byte(out))
if err != nil {
panic(err)
}
g, err := telemetry.Select(gpus, "GPU-1234-abcd")
if err != nil {
panic(err)
}
args, _ := telemetry.DockerArgs(g)
fmt.Println(g.Name, g.DevicePath())
fmt.Println(strings.Join(args[:2], " "))
}
Output: NVIDIA H200 /dev/nvidia7 --device /dev/nvidia7:/dev/nvidia7:rw
func (HealthGPU) DevicePath ¶
DevicePath returns /dev/nvidia<minor>, or "" if the minor is unknown.
type HealthLimits ¶
type HealthLimits struct {
MaxBytes int64
MaxDevices int
MaxSources int
MaxObservations int
MaxEdges int
}
HealthLimits bounds a bundle before decoding. All limits must be positive.
type HealthObservation ¶
type HealthObservation struct {
SourceID string `json:"source_id"`
Reading Reading `json:"reading"`
Class string `json:"class"` // raw, vendor_judgment, inference
Judgment string `json:"judgment,omitempty"`
Scope string `json:"scope,omitempty"`
NativeError string `json:"native_error,omitempty"`
}
HealthObservation records raw evidence or a separately labeled judgment. Reading timestamps use the enclosing snapshot's clock domain and epoch.
type HealthOptions ¶
type HealthOptions struct {
UUID string // GPU expected; empty accepts exactly one GPU
SMI string // nvidia-smi path; default "nvidia-smi"
Timeout time.Duration // limit for nvidia-smi; default 5s
Root string // prefix for /dev and /proc paths, for tests
}
Options configures Probe.
type HealthReport ¶
type HealthReport struct {
Time time.Time `json:"time"`
OK bool `json:"ok"`
Problems []string `json:"problems,omitempty"`
GPU *HealthGPU `json:"gpu,omitempty"`
Nodes []Node `json:"nodes"`
SMI SMIResult `json:"nvidia_smi"`
Driver string `json:"driver,omitempty"` // first line of /proc/driver/nvidia/version
Cgroup string `json:"cgroup,omitempty"` // /proc/self/cgroup
Env []string `json:"env,omitempty"` // CUDA_VISIBLE_DEVICES and NVIDIA_VISIBLE_DEVICES
}
A Report is one probe's evidence and verdict.
func Probe ¶
func Probe(ctx context.Context, opt HealthOptions) *HealthReport
Probe runs nvidia-smi -q -x, selects the GPU, opens its node and the control nodes, and reads the driver version and cgroup. OK reports whether every check passed; Problems explains each failure.
type HealthSnapshot ¶
type HealthSnapshot struct {
Version int `json:"version"`
NodeID string `json:"node_id"`
TopologyEpoch string `json:"topology_epoch"`
ClockDomain string `json:"clock_domain"`
ClockEpoch string `json:"clock_epoch"`
AtNanos int64 `json:"at_nanos"`
DeviceStates map[string]string `json:"device_states"` // present, lost, unknown
Sources []HealthSource `json:"sources"`
Observations []HealthObservation `json:"observations"`
Edges []TopologyEdge `json:"edges"`
LostRecords uint64 `json:"lost_records"`
Complete bool `json:"complete"`
}
HealthSnapshot is a read-only NVIDIA incident bundle. It has no action or remediation API. DeviceStates are reported explicitly; a failed source does not imply that a GPU disappeared. Node fields require an explicit GPU join.
func JoinNVLinkHealth ¶
func JoinNVLinkHealth(s HealthSnapshot, report NVLinkSnapshot, l HealthLimits) (*HealthSnapshot, error)
JoinNVLinkHealth adds mapped active GPU edges after explicit node, clock and topology joins. Raw unresolved/non-GPU/inactive observations stay in report; callers must retain it alongside the health graph. No throughput is derived.
Example ¶
d, c, cfg := linkFixture()
reader, _ := telemetry.NewNVLinkReader(d, c, cfg)
report, _ := reader.Read(context.Background())
s := telemetry.HealthSnapshot{Version: 1, NodeID: "n", TopologyEpoch: "t", ClockDomain: report.ClockDomain, ClockEpoch: report.ClockEpoch, AtNanos: 10, DeviceStates: map[string]string{"GPU-0": "present", "GPU-1": "present"}}
limits := telemetry.HealthLimits{MaxBytes: 8192, MaxDevices: 2, MaxSources: 2, MaxObservations: 4, MaxEdges: 4}
out, _ := telemetry.JoinNVLinkHealth(s, *report, limits)
fmt.Println(out.Edges[0].From, out.Edges[0].To, out.Edges[0].Capability)
Output: GPU-0 GPU-1 nominal_version=4
func JoinNodeHealth ¶
func JoinNodeHealth(s HealthSnapshot, n hostmetrics.Snapshot, uuid string, l HealthLimits) (*HealthSnapshot, error)
JoinNodeHealth adds explicitly associated node evidence. The caller's join does not establish device consumption or causation. Sensor times stay unknown. The original snapshot is not modified.
Example ¶
package main
import (
"bytes"
"fmt"
"strings"
"github.com/tmc/lib/ebpfhost/hostmetrics"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func nodeFixture() (telemetry.HealthSnapshot, hostmetrics.Snapshot, telemetry.HealthLimits) {
l := telemetry.HealthLimits{MaxBytes: 4096, MaxDevices: 1, MaxSources: 2, MaxObservations: 8, MaxEdges: 1}
s := telemetry.HealthSnapshot{Version: 1, NodeID: "n", TopologyEpoch: "t", ClockDomain: "mono", ClockEpoch: "b", AtNanos: 20, DeviceStates: map[string]string{"GPU": "present"}}
n, _ := hostmetrics.ReadCounter(strings.NewReader("9007199254740993"), hostmetrics.Context{NodeID: "n", SourceID: "net", Version: "linux6.8", ClockDomain: "mono", ClockEpoch: "b", QueryStartNanos: 10, QueryEndNanos: 20}, "node.net.rx_bytes", "eth0", 128)
return s, n, l
}
func main() {
s, n, l := nodeFixture()
joined, _ := telemetry.JoinNodeHealth(s, n, "GPU", l)
var b bytes.Buffer
_ = telemetry.WriteHealthSnapshot(&b, *joined, l)
got, _ := telemetry.ReadHealthSnapshot(&b, l)
fmt.Println(got.Observations[0].Reading.IntValue, got.Observations[0].Scope)
}
Output: 9007199254740993 node/n/eth0
func JoinRedfishHealth ¶
func JoinRedfishHealth(s HealthSnapshot, sensor hostmetrics.RedfishSensor, uuid string, l HealthLimits) (*HealthSnapshot, error)
JoinRedfishHealth associates a selected node sensor with a device explicitly. It does not convert chassis power to GPU power. Vendor health and source ReadingTime remain in the supplied sensor artifact; no clock mapping is inferred. Inactive or unknown sensor states remain unavailable even when the artifact retains a numeric reading. Synthesized enabled readings remain separately labeled inferences.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/ebpfhost/hostmetrics"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func nodeFixture() (telemetry.HealthSnapshot, hostmetrics.Snapshot, telemetry.HealthLimits) {
l := telemetry.HealthLimits{MaxBytes: 4096, MaxDevices: 1, MaxSources: 2, MaxObservations: 8, MaxEdges: 1}
s := telemetry.HealthSnapshot{Version: 1, NodeID: "n", TopologyEpoch: "t", ClockDomain: "mono", ClockEpoch: "b", AtNanos: 20, DeviceStates: map[string]string{"GPU": "present"}}
n, _ := hostmetrics.ReadCounter(strings.NewReader("9007199254740993"), hostmetrics.Context{NodeID: "n", SourceID: "net", Version: "linux6.8", ClockDomain: "mono", ClockEpoch: "b", QueryStartNanos: 10, QueryEndNanos: 20}, "node.net.rx_bytes", "eth0", 128)
return s, n, l
}
func main() {
s, _, l := nodeFixture()
raw := `{"@odata.type":"#Sensor.v1_9_0.Sensor","@odata.id":"/redfish/v1/Chassis/1/Sensors/p","Id":"p","ReadingType":"Power","ReadingUnits":"W","Implementation":"PhysicalSensor","Status":{"State":"Enabled"},"Reading":null}`
sensor, _ := hostmetrics.ReadRedfishSensor(strings.NewReader(raw), hostmetrics.Context{NodeID: "n", SourceID: "bmc", Version: "Sensor.v1_9_0", ClockDomain: "mono", ClockEpoch: "b", QueryEndNanos: 20}, "/redfish/v1/Chassis/1/Sensors/p", "p", 1024)
out, _ := telemetry.JoinRedfishHealth(s, sensor, "GPU", l)
fmt.Println(out.Observations[0].Reading.Evidence, out.Observations[0].Reading.HasSourceTimestamp)
}
Output: unavailable false
func ReadHealthSnapshot ¶
func ReadHealthSnapshot(r io.Reader, limits HealthLimits) (*HealthSnapshot, error)
ReadHealthSnapshot reads one version 1 bundle, rejecting unknown fields, excess input, invalid units and joins, duplicate evidence and contradictions.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func exampleHealth() (telemetry.HealthSnapshot, telemetry.HealthLimits) {
limits := telemetry.HealthLimits{MaxBytes: 4096, MaxDevices: 1, MaxSources: 1, MaxObservations: 4, MaxEdges: 1}
s := telemetry.HealthSnapshot{
Version: 1, NodeID: "node-0", TopologyEpoch: "topology-1", ClockDomain: "synthetic", ClockEpoch: "fixture-1", AtNanos: 10,
DeviceStates: map[string]string{"GPU-0": "present"},
Sources: []telemetry.HealthSource{{ID: "nvml", Kind: "nvml", Version: "fixture-v1", State: "available", HasLastSuccess: true, LastSuccessNanos: 10}},
Observations: []telemetry.HealthObservation{{SourceID: "nvml", Class: "raw", Reading: telemetry.Reading{
Name: telemetry.MetricTemperatureC, Unit: telemetry.UnitCelsius, Backend: "nvml", DeviceUUID: "GPU-0", Evidence: telemetry.EvidenceMeasured, Value: 31, TimestampMonotonic: 10,
}}},
Complete: true,
}
return s, limits
}
func main() {
s, limits := exampleHealth()
var b bytes.Buffer
if err := telemetry.WriteHealthSnapshot(&b, s, limits); err != nil {
panic(err)
}
got, err := telemetry.ReadHealthSnapshot(&b, limits)
if err != nil {
panic(err)
}
fmt.Println(got.DeviceStates["GPU-0"], got.Observations[0].Reading.Value)
fmt.Println(got.Observations[0].Reading.HasSourceTimestamp)
}
Output: present 31 false
func (HealthSnapshot) Validate ¶
func (s HealthSnapshot) Validate(l HealthLimits) error
Validate checks the snapshot contract without assigning health judgments.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func exampleHealth() (telemetry.HealthSnapshot, telemetry.HealthLimits) {
limits := telemetry.HealthLimits{MaxBytes: 4096, MaxDevices: 1, MaxSources: 1, MaxObservations: 4, MaxEdges: 1}
s := telemetry.HealthSnapshot{
Version: 1, NodeID: "node-0", TopologyEpoch: "topology-1", ClockDomain: "synthetic", ClockEpoch: "fixture-1", AtNanos: 10,
DeviceStates: map[string]string{"GPU-0": "present"},
Sources: []telemetry.HealthSource{{ID: "nvml", Kind: "nvml", Version: "fixture-v1", State: "available", HasLastSuccess: true, LastSuccessNanos: 10}},
Observations: []telemetry.HealthObservation{{SourceID: "nvml", Class: "raw", Reading: telemetry.Reading{
Name: telemetry.MetricTemperatureC, Unit: telemetry.UnitCelsius, Backend: "nvml", DeviceUUID: "GPU-0", Evidence: telemetry.EvidenceMeasured, Value: 31, TimestampMonotonic: 10,
}}},
Complete: true,
}
return s, limits
}
func main() {
s, limits := exampleHealth()
fmt.Println(s.Validate(limits))
s.Observations[0].Reading.Unit = "fahrenheit"
fmt.Println(s.Validate(limits) != nil)
}
Output: <nil> true
type HealthSource ¶
type HealthSource struct {
ID string `json:"id"`
Kind string `json:"kind"`
Version string `json:"version"`
State string `json:"state"` // available, unsupported, denied, failed
LastSuccessNanos int64 `json:"last_success_nanos"`
HasLastSuccess bool `json:"has_last_success"`
}
HealthSource describes the availability of an explicitly configured reader. Its state describes the reader, not the health of its device.
func (HealthSource) QueryStale ¶
func (s HealthSource) QueryStale(nowNanos, maxAgeNanos int64) bool
QueryStale reports whether a reader's last successful query is too old. It does not establish sensor freshness or convert query time to sensor time.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
s := telemetry.HealthSource{HasLastSuccess: true, LastSuccessNanos: 10}
fmt.Println(s.QueryStale(11, 5), s.QueryStale(16, 5))
}
Output: false true
type Histogram ¶
type Histogram struct {
Bounds []string `json:"bounds"`
Counts []uint64 `json:"counts"`
// V5 fields preserve count and optional summary presence.
Count *uint64 `json:"count,omitempty"`
Sum *float64 `json:"sum,omitempty"`
Min *float64 `json:"min,omitempty"`
Max *float64 `json:"max,omitempty"`
Temporality string `json:"temporality,omitempty"`
Flags uint32 `json:"flags,omitempty"`
}
Histogram preserves cumulative bucket counts and their ordered upper bounds. Bounds use finite decimal strings or the final "+Inf" bound. The zero value is absent; a present histogram requires equally sized Bounds and Counts.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
b, _ := json.Marshal(telemetry.Histogram{Bounds: []string{"1", "+Inf"}, Counts: []uint64{0, 2}})
fmt.Println(string(b))
}
Output: {"bounds":["1","+Inf"],"counts":[0,2]}
type HistogramBinding ¶
type HistogramBinding struct{ Name, Unit string }
HistogramBinding binds one private canonical metric name to its unscaled unit. Names use [a-z][a-z0-9_]{0,127} and must not shadow a scalar registry entry.
type HistogramWindowCoverageStatus ¶
type HistogramWindowCoverageStatus string
HistogramWindowCoverageStatus concerns declared intervals, not observer population.
const ( HistogramWindowCompleteDeclaredIntervals HistogramWindowCoverageStatus = "complete_declared_intervals" HistogramWindowIncompleteIntervals HistogramWindowCoverageStatus = "incomplete" HistogramWindowUnknownIntervals HistogramWindowCoverageStatus = "unknown" )
type HistogramWindowFieldStatus ¶
type HistogramWindowFieldStatus string
HistogramWindowFieldStatus describes optional summary presence and arithmetic.
const ( HistogramWindowFieldAvailable HistogramWindowFieldStatus = "available" HistogramWindowFieldMissing HistogramWindowFieldStatus = "missing" HistogramWindowFieldEmpty HistogramWindowFieldStatus = "empty" HistogramWindowFieldNotDerivable HistogramWindowFieldStatus = "not_derivable" HistogramWindowFieldNonfinite HistogramWindowFieldStatus = "nonfinite" HistogramWindowFieldInconsistent HistogramWindowFieldStatus = "inconsistent" )
type HistogramWindowOptions ¶
type HistogramWindowOptions struct {
Manifest *Manifest
Policy HistogramWindowPolicy
ClockDomain string
ClockEpoch string
UnixTimeMapping *UnixTimeMapping
MaxReadings int
MaxSeries int
MaxBounds int
}
HistogramWindowOptions admits a bounded recorded distribution window. Manifest is the completed canonical manifest for all supplied samples. Zero limits select 4096 readings, 4096 series and 257 bounds; maxima are 65536, 65536 and 4097. At most 65536 samples are admitted, including empty samples. Exact boundary arithmetic supports declared known-zero uncertainty only. Mapping is an optional caller assertion from local source time to Unix, not calibration.
type HistogramWindowPolicy ¶
type HistogramWindowPolicy string
HistogramWindowPolicy selects declared temporal semantics; CDF counts do not select it.
const ( HistogramWindowDelta HistogramWindowPolicy = "delta" HistogramWindowCumulativeDifference HistogramWindowPolicy = "cumulative_difference" )
type HistogramWindowReason ¶
type HistogramWindowReason string
HistogramWindowReason explains a withheld distribution or scalar boundary.
const ( HistogramWindowReasonMissingManifest HistogramWindowReason = "missing_manifest" HistogramWindowReasonTemporalUnknown HistogramWindowReason = "temporal_unknown" HistogramWindowReasonTemporalityMismatch HistogramWindowReason = "temporality_mismatch" HistogramWindowReasonMissingInterval HistogramWindowReason = "missing_interval" HistogramWindowReasonMissingClock HistogramWindowReason = "missing_clock" HistogramWindowReasonClockMismatch HistogramWindowReason = "clock_mismatch" HistogramWindowReasonMissingEpoch HistogramWindowReason = "missing_epoch" HistogramWindowReasonEpochMismatch HistogramWindowReason = "epoch_mismatch" HistogramWindowReasonUnknownUncertainty HistogramWindowReason = "unknown_uncertainty" HistogramWindowReasonBoundaryUncertainty HistogramWindowReason = "boundary_uncertainty" HistogramWindowReasonIncompleteStream HistogramWindowReason = "incomplete_stream" HistogramWindowReasonUnknownLoss HistogramWindowReason = "unknown_loss" HistogramWindowReasonLostReadings HistogramWindowReason = "lost_readings" HistogramWindowReasonNoRecordedValue HistogramWindowReason = "no_recorded_value" HistogramWindowReasonMissingBuckets HistogramWindowReason = "missing_buckets" HistogramWindowReasonMissingEndpoint HistogramWindowReason = "missing_endpoint" HistogramWindowReasonGap HistogramWindowReason = "gap" HistogramWindowReasonOverlap HistogramWindowReason = "overlap" HistogramWindowReasonStraddlingInterval HistogramWindowReason = "straddling_interval" HistogramWindowReasonDuplicateInterval HistogramWindowReason = "duplicate_interval" HistogramWindowReasonScalarNameCollision HistogramWindowReason = "scalar_name_collision" HistogramWindowReasonMixedValueKinds HistogramWindowReason = "mixed_value_kinds" HistogramWindowReasonMissingIdentity HistogramWindowReason = "missing_identity" HistogramWindowReasonIdentityChanged HistogramWindowReason = "identity_changed" HistogramWindowReasonSourceProfileMismatch HistogramWindowReason = "source_profile_mismatch" HistogramWindowReasonSchemaChanged HistogramWindowReason = "schema_changed" HistogramWindowReasonAggregationEpochChanged HistogramWindowReason = "aggregation_epoch_changed" HistogramWindowReasonCounterDecrease HistogramWindowReason = "counter_decrease" HistogramWindowReasonInvalidIntervalCDF HistogramWindowReason = "invalid_interval_c_d_f" HistogramWindowReasonCountOverflow HistogramWindowReason = "count_overflow" )
type HistogramWindowSource ¶
type HistogramWindowSource struct {
SampleSeq uint64
ReadingIndex int
Interval *tracecontract.Interval
ClockEpoch string
SourceClass, Producer, ProducerVersion, ProducerSchema string
RawSHA256, Transform, TransformSHA256 string
ReadingSource *ReadingSource
AppliedUnixTimeMapping *UnixTimeMapping
Observer Observer
OTLPClock *OTLPClockMetadata
OTLPSourceTime *OTLPSourceTime
UncertaintyNS *int64
}
HistogramWindowSource owns original point lineage. Locators are not clock or physical identity proof. A mapping and calibration are caller assertions.
type HistogramWindowStatus ¶
type HistogramWindowStatus string
HistogramWindowStatus describes distribution availability, not scalar precision.
const ( HistogramWindowAvailable HistogramWindowStatus = "available" HistogramWindowUnsupported HistogramWindowStatus = "unsupported" HistogramWindowRefused HistogramWindowStatus = "refused" )
type HistogramWindowSummary ¶
type HistogramWindowSummary struct {
WindowName, DeviceUUID, MetricName, Unit string
Policy HistogramWindowPolicy
ClockDomain, ClockEpoch string
StartNanos, EndNanos int64
Status HistogramWindowStatus
Reason HistogramWindowReason
Histogram *Histogram
SumStatus, MinStatus, MaxStatus HistogramWindowFieldStatus
InputCount int
CoveredDurationNanos int64
CoverageStatus HistogramWindowCoverageStatus
ObserverCoverage *SamplingCoverage
Sources []HistogramWindowSource
}
HistogramWindowSummary describes exact recorded CDF counts over declared intervals. An available Sum is finite float64 arithmetic, not an exact real sum. A nil Histogram with a status is not measured zero or a scalar mean.
func AggregateHistogramWindow ¶
func AggregateHistogramWindow(name string, start, end int64, samples []Sample, opts HistogramWindowOptions) ([]HistogramWindowSummary, error)
AggregateHistogramWindow accumulates V5 delta intervals or differences V5 cumulative endpoints in [startNanos,endNanos). It never substitutes collector query time, interpolates buckets, derives cumulative extrema, or estimates individual latency. V3/V4 temporal semantics are unsupported. A recovered reset between observations remains unobservable. Supplied samples must be the complete decoded manifest population; host fixtures do not authenticate a producer, calibration, observer coverage or physical execution.
Example (CumulativeDifference) ¶
samples := hwSamples(hwReading(1, 10, []uint64{1, 2}, "cumulative"), hwReading(1, 30, []uint64{3, 5}, "cumulative"))
manifest := hwManifest(samples, telemetry.SchemaVersionV5)
manifest.LostRecordsByFamily = map[string]tracecontract.Loss{"histograms": {Total: 2}}
summaries, err := telemetry.AggregateHistogramWindow("work", 10, 30, samples, hwOptions(manifest, telemetry.HistogramWindowCumulativeDifference))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(summaries[0].Histogram.Counts, summaries[0].MinStatus)
Output: [2 3] not_derivable
Example (Delta) ¶
// Constructed source assertions, not a qualified producer capture.
samples := hwSamples(hwReading(10, 20, []uint64{1, 2}, "delta"), hwReading(20, 30, []uint64{2, 3}, "delta"))
manifest := hwManifest(samples, telemetry.SchemaVersionV5)
manifest.LostRecordsByFamily = map[string]tracecontract.Loss{"histograms": {Total: 2}}
summaries, err := telemetry.AggregateHistogramWindow("work", 10, 30, samples, hwOptions(manifest, telemetry.HistogramWindowDelta))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(summaries[0].Status, summaries[0].Histogram.Counts, summaries[0].ObserverCoverage.Status)
Output: available [3 5] unknown
Example (Unsupported) ¶
reading := hwReading(10, 30, []uint64{1, 2}, "")
reading.Observation.Histogram.Count = nil
reading.Observation.Observer = telemetry.Observer{}
samples := hwSamples(reading)
summaries, err := telemetry.AggregateHistogramWindow("work", 10, 30, samples, hwOptions(hwManifest(samples, telemetry.SchemaVersionV3), telemetry.HistogramWindowDelta))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(summaries[0].Status, summaries[0].Reason)
Output: unsupported temporal_unknown
type IBPortSampler ¶
type IBPortSampler struct {
// contains filtered or unexported fields
}
IBPortSampler samples rolling InfiniBand/RoCE port utilization in [0, 1] from Linux sysfs counters (port_xmit_data, port_rcv_data, 4-octet words) with NETLINK_RDMA fallback (rdma_tx_bytes, rdma_rx_bytes) for SR-IOV VF pods.
On non-Linux hosts without injected test sources, IBPortSampler.Sample returns cuda.ErrUnsupported. When establishing the initial baseline or when no byte counters are exposed, Sample returns (0, false, nil) so callers never spoof 0.0 idle utilization.
Example ¶
package main
import (
"fmt"
"testing/fstest"
"time"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
fsys := fstest.MapFS{
"mlx5_0/ports/1/rate": {Data: []byte("400 Gb/sec (4X NDR)\n")},
"mlx5_0/ports/1/counters/port_xmit_data": {Data: []byte("0\n")},
"mlx5_0/ports/1/counters/port_rcv_data": {Data: []byte("0\n")},
}
now := time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC)
s, err := telemetry.NewIBPortSampler("mlx5_0", 1,
telemetry.WithIBSysfsRoot(fsys),
telemetry.WithIBClock(func() time.Time { return now }),
)
if err != nil {
panic(err)
}
_, ok1, err := s.Sample()
if err != nil {
panic(err)
}
now = now.Add(time.Second)
fsys["mlx5_0/ports/1/counters/port_xmit_data"] = &fstest.MapFile{Data: []byte("6250000000\n")}
u, ok2, err := s.Sample()
if err != nil {
panic(err)
}
fmt.Printf("baseline_ok=%v sample_ok=%v util=%.2f\n", ok1, ok2, u)
}
Output: baseline_ok=false sample_ok=true util=0.50
func NewIBPortSampler ¶
func NewIBPortSampler(device string, port int, opts ...IBSamplerOption) (*IBPortSampler, error)
NewIBPortSampler constructs an IBPortSampler for the given IB device and 1-based port number.
type IBSamplerOption ¶
type IBSamplerOption func(*IBPortSampler)
IBSamplerOption configures NewIBPortSampler.
func WithIBClock ¶
func WithIBClock(clock func() time.Time) IBSamplerOption
WithIBClock injects the monotonic clock used to compute counter deltas.
func WithIBLinkBytesPerSec ¶
func WithIBLinkBytesPerSec(bps float64) IBSamplerOption
WithIBLinkBytesPerSec overrides the link capacity (bytes/sec per direction) instead of reading <device>/ports/<port>/rate from sysfs.
func WithIBNetlinkCounters ¶
func WithIBNetlinkCounters(fn func(device string, port int) (map[string]uint64, error)) IBSamplerOption
WithIBNetlinkCounters injects a custom NETLINK_RDMA hardware counter reader.
func WithIBSysfsRoot ¶
func WithIBSysfsRoot(root fs.FS) IBSamplerOption
WithIBSysfsRoot injects an fs.FS rooted at the InfiniBand sysfs directory (equivalent to /sys/class/infiniband).
type Info ¶
type Info struct {
ID, Type, KeySize, ValueSize, MaxEntries uint32
BTFID, BTFKeyTypeID, BTFValueTypeID, BTFVmlinuxValueTypeID uint32
}
Info is the inspected kernel map identity and layout. BTF-backed layouts are refused: this wire schema is independent of BTF and does not permit relocation.
type InfoROM ¶
type InfoROM struct {
Image Value `xml:"img_version"`
OEM Value `xml:"oem_object"`
ECC Value `xml:"ecc_object"`
Power Value `xml:"pwr_object"`
}
InfoROM holds the versions of the GPU's InfoROM objects.
type JobAttributionResult ¶
type JobAttributionResult struct {
Assignment EntityAssignment `json:"assignment"`
Reason string `json:"reason,omitempty"`
Cgroup SlurmCgroupIdentity `json:"cgroup,omitempty"`
}
JobAttributionResult captures the outcome of joining a process/cgroup to an allocation. The Reason field describes why attribution was withheld whenever Assignment.State is not "assigned".
func JoinSlurmAttribution ¶
func JoinSlurmAttribution(allocations []SlurmAllocation, mappings []SlurmGPUMapping, procs []ProcEntityFacts, executions []EntityAssignment, at int64) ([]JobAttributionResult, error)
JoinSlurmAttribution performs a pure, replayable process/cgroup-to-allocation join across the supplied allocations, device mappings, process facts, and execution proofs at timestamp at.
type JobAttributionSnapshot ¶
type JobAttributionSnapshot struct {
Allocations []SlurmAllocation `json:"allocations,omitempty"`
Mappings []SlurmGPUMapping `json:"mappings,omitempty"`
Processes []ProcEntityFacts `json:"processes,omitempty"`
Executions []EntityAssignment `json:"executions,omitempty"`
}
JobAttributionSnapshot contains the inputs for an attribution refresh cycle.
type JobAttributionTable ¶
type JobAttributionTable struct {
// contains filtered or unexported fields
}
JobAttributionTable is a bounded relationship table and cache providing replayable process/cgroup-to-allocation joins with TTL expiration. The zero value is not usable; use NewJobAttributionTable.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsworkload"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
table, err := telemetry.NewJobAttributionTable(10, 1000)
if err != nil {
panic(err)
}
snap := telemetry.JobAttributionSnapshot{
Allocations: []telemetry.SlurmAllocation{
{
JobID: "42",
TRESAlloc: "gres/gpu=1",
State: []string{"RUNNING"},
Snapshot: telemetry.EntitySnapshot{SourceRevision: "v1", ClockDomain: "monotonic", ClockEpoch: "boot-1", StartNanos: 10, EndNanos: 500},
},
},
Mappings: []telemetry.SlurmGPUMapping{
{
JobID: "42",
Device: telemetry.DeviceMetadata{UUID: "GPU-1"},
Sharing: "exclusive",
Authoritative: true,
ClockDomain: "monotonic",
ClockEpoch: "boot-1",
StartNanos: 10,
EndNanos: 500,
},
},
Processes: []telemetry.ProcEntityFacts{
{
Process: telemetry.EntityProcess{
Process: obsworkload.ProcessGenID{PID: 100, Generation: 20},
BootID: "boot-1",
NodeID: "node-1",
PIDNamespace: "pid:[1]",
},
Cgroups: []string{"0::/system.slice/slurmstepd.scope/job_42/step_0/task_0"},
},
},
Executions: []telemetry.EntityAssignment{
{
Process: telemetry.EntityProcess{
Process: obsworkload.ProcessGenID{PID: 100, Generation: 20},
BootID: "boot-1",
NodeID: "node-1",
PIDNamespace: "pid:[1]",
ExecGeneration: 1,
HasExecGeneration: true,
},
Device: telemetry.DeviceMetadata{UUID: "GPU-1"},
Owner: telemetry.EntityOwner{JobID: "42"},
Source: "process_proof",
SourceRevision: "v1",
Authoritative: true,
State: "assigned",
ClockDomain: "monotonic",
ClockEpoch: "boot-1",
StartNanos: 10,
EndNanos: 500,
Sharing: "exclusive",
},
},
}
results, err := table.Refresh(snap, 50)
if err != nil {
panic(err)
}
fmt.Printf("%d state=%s job=%s device=%s\n",
len(results),
results[0].Assignment.State,
results[0].Assignment.Owner.JobID,
results[0].Assignment.Device.UUID,
)
}
Output: 1 state=assigned job=42 device=GPU-1
func NewJobAttributionTable ¶
func NewJobAttributionTable(capacity int, ttlNanos int64) (*JobAttributionTable, error)
NewJobAttributionTable creates a table with positive capacity and TTL in nanoseconds.
func (*JobAttributionTable) Clear ¶
func (t *JobAttributionTable) Clear()
Clear removes all cached relationships.
func (*JobAttributionTable) Refresh ¶
func (t *JobAttributionTable) Refresh(snap JobAttributionSnapshot, now int64) ([]JobAttributionResult, error)
Refresh replaces all cached relationships with the newly evaluated snapshot at timestamp now. It enforces atomic replacement semantics: if evaluation or capacity validation fails, the existing cache is left completely unmutated. Refreshes with an empty snapshot clear previous assignments.
func (*JobAttributionTable) Resolve ¶
func (t *JobAttributionTable) Resolve(proc EntityProcess, deviceUUID string, at int64) JobAttributionResult
Resolve queries attribution for a specific process on a device at timestamp at. Misses, expired entries, and generation mismatches return an unresolved result.
type Join ¶
type Join struct{ Event, API int }
Join is a unique within-report CUDA API/activity correlation. It makes no performance or cross-report causal claim.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
j := telemetry.Join{Event: 0, API: 3}
fmt.Println(j.Event, j.API)
}
Output: 0 3
type K8sAttribution ¶
type K8sAttribution struct {
PodUID, PodName, Namespace, Container, ContainerID, Node, GPUUUID, AllocationState string
}
K8sAttribution describes an observed GPU allocation or process.
type K8sAttributionResolver ¶
type K8sAttributionResolver struct {
// contains filtered or unexported fields
}
K8sAttributionResolver joins one immutable pair of Kubernetes snapshots with live procfs membership. Construct a new resolver when snapshots are refreshed.
func NewK8sAttributionResolver ¶
func NewK8sAttributionResolver(root, boot, node string, allocations []PodResourceAllocation, pods []PodEntityMetadata) *K8sAttributionResolver
NewK8sAttributionResolver indexes allocations and metadata for one node.
func (*K8sAttributionResolver) LookupGPU ¶
func (r *K8sAttributionResolver) LookupGPU(uuid string) K8sAttribution
LookupGPU returns allocation metadata even when the GPU has no active processes.
Example ¶
resolver := NewK8sAttributionResolver("", "boot", "node", nil, nil)
fmt.Println(resolver.LookupGPU("GPU-example").AllocationState)
Output: unallocated
func (*K8sAttributionResolver) LookupProcess ¶
func (r *K8sAttributionResolver) LookupProcess(pid int) (K8sAttribution, error)
LookupProcess resolves the currently observed generation of pid.
type KernelGaps ¶
KernelGaps aggregates the launches of one kernel within a step. GapNS is the idle time between the end of all earlier kernels and this kernel's start, summed over its launches.
type Kind ¶
type Kind uint8
Kind identifies a fact, uninterpreted input, malformed record or loss notice.
type Kmsg ¶
type Kmsg struct {
Priority, Sequence, MonotonicMicroseconds uint64
Flags string
Extensions, Metadata []string
}
Kmsg preserves the Linux record header. Extension fields and continuation metadata are raw observations, not invented timestamps or device identities.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
h := telemetry.Kmsg{Sequence: 10}
fmt.Println(h.Sequence)
}
Output: 10
type KubernetesPods ¶
KubernetesPods configures a node-scoped PodList fetch. With no URL or file, it uses in-cluster credentials. Client supplies transport settings for a URL.
func (KubernetesPods) Fetch ¶
func (p KubernetesPods) Fetch(ctx context.Context, snapshot EntitySnapshot) ([]PodEntityMetadata, error)
Fetch reads node-scoped pod metadata from the configured source.
type LaunchGaps ¶
type LaunchGaps struct {
Launches int
SpanNS int64
BusyNS int64
IdleNS int64
MaxGapNS int64
// Kernels aggregates the step's kernels by name, in descending order of
// the idle time before them.
Kernels []KernelGaps
}
LaunchGaps summarizes the device timeline of one step: a sequence of kernels that run as a dependent chain.
SpanNS runs from the first kernel's start to the last kernel's end. BusyNS is the time covered by at least one kernel and IdleNS the rest of the span: the device-side cost of launching and retiring the step's kernels, which does not shrink when the kernels get faster. Under programmatic dependent launch a kernel may start before its predecessor ends; the overlap counts once in BusyNS. Such a kernel's duration includes its wait for the predecessor, so the launch latency it hides moves from IdleNS into BusyNS: compare SpanNS, not IdleNS, across launch modes.
func AnalyzeLaunchGaps ¶
func AnalyzeLaunchGaps(step []Span) LaunchGaps
AnalyzeLaunchGaps summarizes step, a sequence of kernels in start order.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
step := []telemetry.Span{
{Name: "rmsnorm", StartNS: 0, EndNS: 4000},
{Name: "gemv", StartNS: 6000, EndNS: 20000},
{Name: "argmax", StartNS: 23000, EndNS: 24000},
}
g := telemetry.AnalyzeLaunchGaps(step)
fmt.Println(g.Launches, g.IdleNS, g.GapPerLaunchNS())
fmt.Println(g.Project(2000))
}
Output: 3 5000 2500 7000
func (LaunchGaps) GapPerLaunchNS ¶
func (g LaunchGaps) GapPerLaunchNS() float64
GapPerLaunchNS returns the mean idle time between consecutive launches.
func (LaunchGaps) Project ¶
func (g LaunchGaps) Project(floorNS int64) int64
Project models the step on a device whose kernels together take floorNS, the step's bandwidth or compute floor, while the idle time between launches stays what it was here: floorNS + IdleNS. It is a model, not a measurement: launch and drain latency differ between devices, and a faster device can expose host submission cost that this trace hid.
type LaunchKey ¶
type LaunchKey struct {
ID string `json:"id"`
Process string `json:"process"`
Context string `json:"context"`
Stream string `json:"stream"`
}
LaunchKey is the CSV launch identifier, scoped by process, context and stream. Its fields are decimal strings retained exactly from the export.
type Link ¶
type Link string
A Link is one cell of the nvidia-smi topo -m matrix: how traffic between two devices travels. Cells other than the constants below and NV# are kept as printed.
const ( LinkSelf Link = "X" // the device itself LinkSYS Link = "SYS" // PCIe and the SMP interconnect between NUMA nodes (QPI/UPI) LinkNode Link = "NODE" // PCIe and the interconnect between PCIe host bridges within a NUMA node LinkPHB Link = "PHB" // PCIe and a PCIe host bridge (typically the CPU) LinkPXB Link = "PXB" // multiple PCIe bridges, without the PCIe host bridge LinkPIX Link = "PIX" // at most a single PCIe bridge )
Link types from the nvidia-smi topo -m legend.
type Log ¶
type Log struct {
// DTD is the system identifier from the report's DOCTYPE,
// such as "nvsmi_device_v12.dtd", or "" if there is none.
DTD string `xml:"-"`
// DTDVersion is the NN in nvsmi_device_vNN.dtd, or 0 if DTD
// does not have that form.
DTDVersion int `xml:"-"`
Timestamp string `xml:"timestamp"`
DriverVersion string `xml:"driver_version"`
CUDAVersion string `xml:"cuda_version"`
// AttachedGPUs is the count nvidia-smi reports. It can differ
// from len(GPUs) when the report was filtered or edited.
AttachedGPUs int `xml:"attached_gpus"`
GPUs []SMIGPU `xml:"gpu"`
// Other holds top-level elements with no field above.
Other []Element `xml:",any"`
}
A Log is one nvidia-smi -q -x report.
type MIGDevice ¶
type MIGDevice struct {
Index Value `xml:"index"`
GPUInstanceID Value `xml:"gpu_instance_id"`
ComputeInstanceID Value `xml:"compute_instance_id"`
MultiprocessorCount Value `xml:"device_attributes>shared>multiprocessor_count"`
CopyEngineCount Value `xml:"device_attributes>shared>copy_engine_count"`
EncoderCount Value `xml:"device_attributes>shared>encoder_count"`
DecoderCount Value `xml:"device_attributes>shared>decoder_count"`
OFACount Value `xml:"device_attributes>shared>ofa_count"`
JPEGCount Value `xml:"device_attributes>shared>jpg_count"`
FBMemory Memory `xml:"fb_memory_usage"`
BAR1Memory Memory `xml:"bar1_memory_usage"`
}
A MIGDevice is one MIG instance of a GPU in MIG mode.
type ManagedField ¶
type ManagedField struct {
Metric, Name, Type string
Numerator, Denominator int64
Integer bool
SourceUnit string
}
ManagedField selects an explicit producer metric and canonical conversion. Numerator/Denominator must be positive. Integer fields require exact scaling.
func DCGMExporterFields ¶
func DCGMExporterFields() []ManagedField
DCGMExporterFields returns mappings from the default counter configuration at dcgm-exporter revision fafd151148052628061a80450b4ee037a5fa0c3c. ProducerVersion must still identify the actual exporter that wrote the input.
Example ¶
fmt.Println(len(DCGMExporterFields()))
Output: 8
type ManagedImport ¶
type ManagedImport struct {
SourceID, Producer, ProducerVersion, NativeOrigin string
Fields []ManagedField
AllowedLabels []string
QueryStartNanos, QueryEndNanos, TimestampUnix int64
Exposition ExpositionOptions
MaxAgeNanos, MaxFutureNanos int64
}
ManagedImport configures one bounded offline snapshot. Query bounds belong to the caller's collector clock; exposition timestamps never populate them.
type Manifest ¶
type Manifest struct {
// Receipt preserves producer-defined record and loss units independently
// of the canonical readings below. Absence means unassessed.
Receipt *tracecontract.Receipt `json:"receipt,omitempty"`
// In V3, LostRecordsByFamily counts canonical readings carrying each family.
// Total is attempted readings; Dropped is readings lost by the stream writer.
// At completion, known Total equals retained readings plus Dropped. Unknown
// or missing families cannot establish known-zero loss. An initial header
// or a stream without completion cannot establish final population counts.
// LostRecords separately counts dropped JSONL records, not readings.
LostRecordsByFamily map[string]tracecontract.Loss `json:"lost_records_by_family,omitempty"`
RunID string `json:"run_id"`
SchemaVersion int `json:"schema_version"`
CollectorVersion string `json:"collector_version"`
BuildRevision string `json:"build_revision,omitempty"`
BuildModified bool `json:"build_modified,omitempty"`
BinaryDigest string `json:"binary_digest,omitempty"`
MetricRegistryVersion string `json:"metric_registry_version,omitempty"`
ClockMonotonicDomain string `json:"clock_monotonic_domain,omitempty"`
ClockMonotonicEpochID string `json:"clock_monotonic_epoch_id,omitempty"`
ClockWallDomain string `json:"clock_wall_domain,omitempty"`
ClockProvenance string `json:"clock_provenance,omitempty"`
ClockMappingValidFrom int64 `json:"clock_mapping_valid_from,omitempty"`
ClockMappingValidUntil int64 `json:"clock_mapping_valid_until,omitempty"`
ClockCalibrationBoundsNanos int64 `json:"clock_calibration_bounds_nanos,omitempty"`
HasClockCalibration bool `json:"has_clock_calibration,omitempty"`
Devices []DeviceMetadata `json:"devices"`
Config CollectorConfig `json:"config"`
StartTimeMonotonic int64 `json:"start_time_monotonic"`
StartTimeUnix int64 `json:"start_time_unix"`
EndTimeMonotonic int64 `json:"end_time_monotonic"`
EndTimeUnix int64 `json:"end_time_unix"`
Phases []PhaseMarker `json:"phases,omitempty"`
// TotalSamples counts collected samples, retained or dropped.
TotalSamples uint64 `json:"total_samples"`
MissedTicks uint64 `json:"missed_ticks"`
// DroppedSamples counts the samples in TotalSamples that a full buffer
// did not retain under the drop policy. They were still written and
// passed to the sample hook, so they are not data loss and do not make
// a run incomplete.
DroppedSamples uint64 `json:"dropped_samples,omitempty"`
// LostRecords counts records that reached no sink: records the Writer
// dropped at its budget and samples whose write failed.
LostRecords uint64 `json:"lost_records"`
IsComplete bool `json:"is_complete"`
IncompleteReason string `json:"incomplete_reason,omitempty"`
}
Manifest describes a telemetry run and its summary properties.
func Replay ¶
func Replay(r io.Reader, maxBytes int64, opts WindowOptions) (*Manifest, map[string][]WindowSummary, map[string][]EnergySummary, error)
Replay reads a recorded stream and computes window and energy summaries across all declared phases.
type Memory ¶
type Memory struct {
Total Value `xml:"total"`
Reserved Value `xml:"reserved"`
Used Value `xml:"used"`
Free Value `xml:"free"`
}
Memory is a memory usage report, in MiB.
type MetadataFailure ¶
type MetadataFailure struct {
Property string `json:"property"`
Reason string `json:"reason"`
Error string `json:"error"`
}
MetadataFailure records a typed failure during device metadata discovery.
type Metric ¶
type Metric struct {
Name string `json:"name"`
Unit string `json:"unit"`
RawValue string `json:"raw_value"`
Unsigned *uint64 `json:"unsigned,omitempty"`
Denominator string `json:"denominator"`
Value obsevidence.EvidenceValue `json:"value"`
}
Metric retains an exported scalar and its classified interpretation. Unsigned, when present, is exact even when it cannot be represented by the evidence model's float64 number. Such an interpretation remains Unread.
type MetricKind ¶
type MetricKind = string
MetricKind represents the aggregation and temporal semantics of a metric.
const ( KindGauge MetricKind = "gauge" KindCounter MetricKind = "counter" KindBitmask MetricKind = "bitmask" KindEvent MetricKind = "event" )
type MetricsHandler ¶
type MetricsHandler struct {
// contains filtered or unexported fields
}
MetricsHandler serves a bounded, previously published telemetry snapshot. Scrapes never query hardware. The zero value returns service unavailable. Publication age describes the HTTP snapshot, not sensor freshness.
Example ¶
h, _ := NewMetricsHandler(ExportOptions{}, time.Minute)
_ = h.Update(nil)
fmt.Println(h.Ready())
Output: true
func NewMetricsHandler ¶
func NewMetricsHandler(options ExportOptions, maxAge time.Duration) (*MetricsHandler, error)
NewMetricsHandler creates a handler with an explicit publication-age limit. It serves Prometheus text by default, or OpenMetrics when options.OpenMetrics is set. An Accept header can select either supported format.
Example ¶
h, _ := NewMetricsHandler(ExportOptions{}, time.Minute)
fmt.Println(h.Ready())
Output: false
func (*MetricsHandler) Invalidate ¶
func (h *MetricsHandler) Invalidate()
Invalidate makes the handler unavailable until the next successful Update.
Example ¶
h, _ := NewMetricsHandler(ExportOptions{}, time.Minute)
_ = h.Update(nil)
h.Invalidate()
fmt.Println(h.Ready())
Output: false
func (*MetricsHandler) Ready ¶
func (h *MetricsHandler) Ready() bool
Ready reports whether a published snapshot is within its publication-age limit.
Example ¶
h, _ := NewMetricsHandler(ExportOptions{}, time.Minute)
fmt.Println(h.Ready())
Output: false
func (*MetricsHandler) ServeHTTP ¶
func (h *MetricsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves GET and HEAD scrapes. Unsupported formats return 406; unavailable or expired snapshots return 503 without stale measurements.
Example ¶
h, _ := NewMetricsHandler(ExportOptions{}, time.Minute)
_ = h.Update(nil)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
fmt.Println(rec.Code)
Output: 200
func (*MetricsHandler) Update ¶
func (h *MetricsHandler) Update(readings []Reading) error
Update validates and copies readings into both exposition formats before publishing them atomically. An invalid update invalidates the old snapshot.
Example ¶
h, _ := NewMetricsHandler(ExportOptions{}, time.Minute)
fmt.Println(h.Update([]Reading{{Name: MetricPowerUsageMW, Unit: UnitMilliwatts, DeviceUUID: "GPU-a", Evidence: EvidenceMeasured, Value: 12500}}), h.Ready())
Output: <nil> true
type Monitor ¶
type Monitor struct {
// contains filtered or unexported fields
}
A Monitor samples one GPU through NVML on its own goroutine and keeps the samples in a bounded ring, so that a trace span can be annotated with the GPU state during it (see Monitor.Window). It is safe for concurrent use.
The cost is off the caller's thread: one sample is seven NVML reads, and an NVML read cost 1.5-2 µs on an L4.
func NewMonitor ¶
func NewMonitor(dev MonitorDevice, cfg MonitorConfig) *Monitor
NewMonitor starts a Monitor for dev. It takes the first sample before returning, which absorbs NVML's slow first reads. The caller keeps ownership of NVML; Close does not shut it down.
func OpenMonitor ¶
func OpenMonitor(index uint32, cfg MonitorConfig) (*Monitor, error)
OpenMonitor initializes NVML and starts a Monitor for the device at NVML index. Close shuts NVML down.
func OpenMonitorPCI ¶
func OpenMonitorPCI(busID string, cfg MonitorConfig) (*Monitor, error)
OpenMonitorPCI is OpenMonitor for the device at PCI bus ID busID, as CUDA's cuDeviceGetPCIBusId and NVML both spell it ("0000:00:04.0"). A bus ID names the same GPU to CUDA and NVML, while a CUDA ordinal and an NVML index can differ: under CUDA_VISIBLE_DEVICES=1, CUDA device 0 is NVML device 1.
func (*Monitor) Close ¶
Close stops sampling and, for a Monitor from OpenMonitor, shuts NVML down. Samples remain readable. Close is idempotent.
func (*Monitor) Now ¶
Now returns the current time in the monitor's clock domain, the domain of DeviceSample query times and Window bounds.
func (*Monitor) Samples ¶
func (m *Monitor) Samples(start, end int64) []DeviceSample
Samples returns the retained samples whose queries lie within [start, end], oldest first.
func (*Monitor) Stats ¶
func (m *Monitor) Stats() MonitorStats
Stats returns the sample and loss counts so far.
func (*Monitor) StepGroups ¶
func (m *Monitor) StepGroups(min time.Duration) *StepGroups
StepGroups returns step groups whose first group starts now and whose windows span at least min. A min of zero means DefaultGroupPeriods sampling periods.
func (*Monitor) Window ¶
func (m *Monitor) Window(start, end int64) SpanWindow
Window summarizes the retained samples whose queries lie within [start, end], in the clock domain of Now. A window shorter than the period often holds no samples; it then reports ReasonNoSamples rather than zeros.
Example ¶
package main
import (
"fmt"
"maps"
"slices"
"time"
"github.com/tmc/lib/nvidia/nvml"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
// l4 is a fake NVML device. Real callers use OpenMonitor, which opens
// the device through NVML.
type l4 struct{ sm uint32 }
func (l4) Temperature(nvml.TemperatureSensors) (uint32, error) { return 58, nil }
func (d l4) ClockInfo(c nvml.ClockType) (uint32, error) {
if c == nvml.ClockSm {
return d.sm, nil
}
return 6251, nil
}
func (l4) PowerUsage() (uint32, error) { return 71500, nil }
func (l4) UtilizationRates() (nvml.Utilization, error) {
return nvml.Utilization{Gpu: 97, Memory: 40}, nil
}
func (l4) MemoryInfoV2() (nvml.MemoryV2, error) { return nvml.MemoryV2{}, nvml.ErrNotSupported }
func (l4) CurrentClocksEventReasons() (uint64, error) {
return nvml.ClocksEventReasonSwPowerCap, nil
}
func main() {
// A real caller writes:
// m, err := nvtelemetry.OpenMonitor(0, nvtelemetry.MonitorConfig{})
// The fake clock and long period keep this example to the one sample
// NewMonitor takes.
clock := telemetry.NewFakeClock(0, 0)
m := telemetry.NewMonitor(l4{sm: 2040}, telemetry.MonitorConfig{Clock: clock, Period: time.Minute})
defer m.Close()
start := m.Now()
clock.Advance(10 * time.Millisecond) // the span runs
attrs := m.Window(start, m.Now()).Attrs()
for _, k := range slices.Sorted(maps.Keys(attrs)) {
fmt.Printf("%s=%v\n", k, attrs[k])
}
}
Output: gpu.clocks_event_reasons=sw_power_cap gpu.clocks_event_reasons_mask=0x4 gpu.sm_clock_mhz.max=2040 gpu.sm_clock_mhz.mean=2040 gpu.sm_clock_mhz.min=2040 gpu.telemetry.coverage=1 gpu.telemetry.period_ms=60000 gpu.telemetry.samples=1 gpu.temperature_c.max=58 gpu.temperature_c.mean=58 gpu.temperature_c.min=58
type MonitorConfig ¶
type MonitorConfig struct {
// Period is the sampling period. Zero means DefaultMonitorPeriod;
// a period below MinMonitorPeriod is raised to it.
Period time.Duration
// Capacity is the number of samples retained. Zero means
// DefaultMonitorCapacity. When the ring is full the oldest sample is
// overwritten and counted in MonitorStats.Overwritten.
Capacity int
// Clock stamps the samples. Nil means RealClock. Window bounds must
// be in the same clock domain; see Monitor.Now.
Clock Clock
}
MonitorConfig configures a Monitor. The zero value is usable.
type MonitorDevice ¶
type MonitorDevice interface {
Temperature(nvml.TemperatureSensors) (uint32, error)
ClockInfo(nvml.ClockType) (uint32, error)
PowerUsage() (uint32, error)
UtilizationRates() (nvml.Utilization, error)
MemoryInfoV2() (nvml.MemoryV2, error)
CurrentClocksEventReasons() (uint64, error)
}
MonitorDevice is the set of NVML device queries a Monitor makes. nvml.Device implements it; tests substitute a fake.
type MonitorStats ¶
type MonitorStats struct {
Period time.Duration
// Samples is the number of samples taken.
Samples uint64
// Missed is the number of periods with no sample because the
// previous one ran late, measured from the gaps between query starts.
Missed uint64
// Overwritten is the number of samples evicted from the full ring.
Overwritten uint64
}
MonitorStats counts a Monitor's samples and losses.
type MovementContext ¶
type MovementContext struct {
Version int `json:"version"`
RunID string `json:"run_id"`
Producer string `json:"producer"`
ProducerVersion string `json:"producer_version"`
ProducerSchema string `json:"producer_schema"`
SourceClass string `json:"source_class"` // native, managed, imported, synthetic, modeled
LossByFamily map[string]tracecontract.Loss `json:"loss_by_family"`
Transfers []MovementTransfer `json:"transfers"`
}
MovementContext is a version 1 caller-supplied movement interchange. It is not a NIXL, cuFile, NCCL or fabric exporter mapping. LossByFamily reports producer loss per transfer family; a missing family is unassessed loss.
type MovementEndpoint ¶
type MovementPath ¶
type MovementPath struct {
Mechanism string `json:"mechanism"`
Basis string `json:"basis,omitempty"`
Evidence string `json:"evidence,omitempty"`
}
MovementPath is the supplied transfer mechanism and the digest of the raw artifact documenting it. Mechanism is unknown, pcie, nvlink, nvswitch, host_staged, gds_direct, gds_fallback or network_rdma. Basis is producer_reported or independent_artifact. A declared path is a claim to be checked against topology and artifacts, not an observed route; a consumer may support topology checks for only some mechanisms.
type MovementTransfer ¶
type MovementTransfer struct {
ID string `json:"id"`
Family string `json:"family"`
RawSHA256 string `json:"raw_sha256"`
RequestID string `json:"request_id,omitempty"`
Attempt string `json:"attempt,omitempty"`
OpID obsworkload.OpID `json:"op_id,omitempty"`
Source MovementEndpoint `json:"source"`
Destination MovementEndpoint `json:"destination"`
Direction string `json:"direction"` // host_to_device, device_to_host, device_to_device, peer_to_peer, storage_to_device, device_to_storage, network_send, network_receive, unknown
Bytes *uint64 `json:"bytes,omitempty"`
Unit string `json:"unit,omitempty"`
State string `json:"state"` // enqueued, in_progress, completed, failed, cancelled, unknown
EnqueueNanos *int64 `json:"enqueue_nanos,omitempty"`
StartNanos *int64 `json:"start_nanos,omitempty"`
ProgressNanos *int64 `json:"progress_nanos,omitempty"`
ProgressBytes *uint64 `json:"progress_bytes,omitempty"`
CompleteNanos *int64 `json:"complete_nanos,omitempty"`
ClockDomain string `json:"clock_domain,omitempty"`
ClockEpoch string `json:"clock_epoch,omitempty"`
UncertaintyNS *int64 `json:"uncertainty_ns,omitempty"`
TopologyEpoch string `json:"topology_epoch,omitempty"`
Path MovementPath `json:"path"`
}
MovementTransfer is one caller-supplied data movement record. ID is the supplied transfer identity; RequestID, Attempt and OpID are retained only when supplied and are never synthesized. Bytes is exact with Unit "bytes"; nil means unreported, not zero. EnqueueNanos is submission or async API return, StartNanos and ProgressNanos are producer-reported, and only a completed State with CompleteNanos records completion. All times use the transfer's clock domain and epoch. RawSHA256 identifies the producer record; Family names its loss family in the enclosing context.
type NCUReport ¶
Report preserves the admitted envelope and all exported rows.
func ImportNCU ¶
Import validates a supported envelope and classifies its rows. Unsupported values and unsuccessful joins remain present with explicit Unread reasons. Candidate order never resolves an ambiguous join.
Example ¶
package main
import (
"crypto/sha256"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
// exampleEnvelope is a synthetic exporter control, not a vendor report.
func exampleEnvelope() telemetry.Envelope {
csv := "ID,Process ID,Process Name,Host Name,Kernel Name,Context,Stream,Block Size,Grid Size,Device,CC,Section Name,Metric Name,Metric Unit,Metric Value,Rule Name,Rule Type,Rule Description,Estimated Speedup Type,Estimated Speedup\n" +
"0,1,example,host,kernel,1,1,\"(1, 1, 1)\",\"(1, 1, 1)\",0,9.0,Timing,gpu__time_duration.sum,ns,42,\n"
return telemetry.Envelope{SchemaVersion: 1, ToolVersion: telemetry.ToolVersion, Format: telemetry.NCUFormat, SourcePath: "synthetic example", ReportDigest: fmt.Sprintf("%x", sha256.Sum256([]byte("synthetic example"))), CSVDigest: fmt.Sprintf("%x", sha256.Sum256([]byte(csv))), CSV: csv}
}
func main() {
r, _ := telemetry.ImportNCU(exampleEnvelope(), nil)
m := r.Rows[0].Metric
fmt.Println(m.Name, m.RawValue, m.Unit, m.Value.Record().Number)
}
Output: gpu__time_duration.sum 42 ns <nil>
type NIXLAgent ¶
NIXLAgent identifies one expected application-supplied producer incarnation. Build is an exact source/build identity, not merely a major version. Mode is the selected sink mode. These identities are assertions by the caller, not discovery or authentication of a running producer.
type NIXLAgentInventory ¶
type NIXLAgentInventory struct {
Sink, Scrape string
HasLastObservation bool
LastObservationNanos int64
Producer NIXLAgent
Observed *NIXLAgent
Status, Detail string
EvidenceSHA256 string
BeforeSHA256, AfterSHA256 string
Windows []WorkloadDelta
StagingDrops string
RetentionLoss string
BufferBehavior string
}
NIXLAgentInventory is the detached result for one expected producer. Status is ready, missing, restarted, producer_changed, sink_failed, sink_unknown, scrape_failed, scrape_unknown, stale, or window_unavailable. A ready result establishes only the supplied inventory/window statement. StagingDrops is an exact interval count or empty when unavailable. It never counts sink failures or retention losses. RetentionLoss is always unknown; BufferBehavior describes only the pinned buffer mode's source contract.
type NIXLAgentObservation ¶
type NIXLAgentObservation struct {
Producer NIXLAgent
Sink, Scrape string
Detail string
EvidenceSHA256 string
HasLastObservation bool
LastObservationNanos int64
Before, After WorkloadExport
}
NIXLAgentObservation records supplied initialization and scrape evidence. Sink and Scrape are "ready", "failed" or "unknown". Detail can describe a port-bind failure. EvidenceSHA256 names the original status artifact. LastObservationNanos uses the summary's declared clock and epoch, not wall time. Before/After are the supplied aggregate endpoints for this incarnation. Their RawSHA256 values bind retained bytes; this API does not parse the bytes or authenticate the caller's normalization into WorkloadMetric values.
type NIXLInventory ¶
type NIXLInventory struct {
Options NIXLInventoryOptions
Expected, Observed, Ready int
InventoryComplete bool
Agents []NIXLAgentInventory
}
NIXLInventory compares an expected population with supplied observations. InventoryComplete does not mean complete telemetry, no loss, successful transfers, completed requests or authentic producer qualification.
func SummarizeNIXLInventory ¶
func SummarizeNIXLInventory(expected []NIXLAgent, observed []NIXLAgentObservation, o NIXLInventoryOptions) (NIXLInventory, error)
SummarizeNIXLInventory compares every expected agent/rank and incarnation against supplied sink/scrape status, freshness and actual CounterWorkloadWindow results. A zero staging-drop counter cannot hide a missing or failed sink. The order of Agents follows expected. Unexpected or duplicate observations are refused, rather than silently assigned to an expected producer.
This function opens no sink, port, endpoint or artifact and discovers no process. A rank's supplied windows must name provider nixl, its exact Build, Rank and RunID; every metric must carry the matching agent_name label. Missing/reset/incompatible window data withholds that producer's readiness.
Example ¶
package main
import (
"crypto/sha256"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
expected := []telemetry.NIXLAgent{
{Agent: "prefill", Rank: 0, RestartEpoch: "start-1", Build: telemetry.NIXLTelemetryBuild, Mode: "prometheus"},
{Agent: "decode", Rank: 1, RestartEpoch: "start-1", Build: telemetry.NIXLTelemetryBuild, Mode: "prometheus"},
}
// Constructed canonical snapshots illustrate supplied evidence. An actual
// importer must retain the original bytes and independently map their fields.
snapshot := func(a telemetry.NIXLAgent, nanos int64) telemetry.WorkloadExport {
rank := a.Rank
source := telemetry.WorkloadSource{Provider: "nixl", Version: a.Build, RunID: "example", Rank: &rank, ClockDomain: "mono", ClockEpochID: "boot-1"}
raw := []byte("agent_telemetry_events_dropped_total 0")
return telemetry.WorkloadExport{Source: source, Raw: raw, RawSHA256: fmt.Sprintf("%x", sha256.Sum256(raw)), Metrics: []telemetry.WorkloadMetric{{Source: source, Name: "agent_telemetry_events_dropped_total", Semantic: "telemetry_staging_drops", Unit: "events", Kind: "counter", Temporality: "cumulative", Labels: map[string]string{"agent_name": a.Agent}, RawValue: "0", HasTime: true, TimeNanos: nanos}}}
}
statusRaw := []byte("supplied sink/scrape status artifact")
evidence := fmt.Sprintf("%x", sha256.Sum256(statusRaw))
observed := []telemetry.NIXLAgentObservation{
{Producer: expected[0], Sink: "ready", Scrape: "ready", EvidenceSHA256: evidence, HasLastObservation: true, LastObservationNanos: 20, Before: snapshot(expected[0], 10), After: snapshot(expected[0], 20)},
{Producer: expected[1], Sink: "failed", Scrape: "failed", EvidenceSHA256: evidence, Detail: "bind: address already in use"},
}
inventory, err := telemetry.SummarizeNIXLInventory(expected, observed, telemetry.NIXLInventoryOptions{RunID: "example", StartNanos: 10, EndNanos: 20, MaxAgeNanos: 2, ClockDomain: "mono", ClockEpochID: "boot-1"})
if err != nil {
panic(err)
}
fmt.Println(inventory.Ready, inventory.Expected, inventory.InventoryComplete)
fmt.Println(inventory.Agents[0].StagingDrops, inventory.Agents[0].RetentionLoss)
fmt.Println(inventory.Agents[1].Status)
}
Output: 1 2 false 0 unknown sink_failed
type NIXLInventoryOptions ¶
type NIXLInventoryOptions struct {
RunID string
StartNanos, EndNanos int64
ClockDomain, ClockEpochID string
MaxAgeNanos int64
Limits WorkloadLimits
}
NIXLInventoryOptions bounds the supplied inventory and all export bodies and metric populations in aggregate. Limits uses WorkloadLimits defaults/caps; MaxMetrics also bounds each inventory's cardinality. MaxAgeNanos must be positive. All observations use ClockDomain/ClockEpochID. No clock mapping or calibration is inferred.
type NSysLimits ¶
type NSysLimits struct{ Bytes, Rows int }
Limits bounds total returned row bytes and row count across all tables. Zero fields select 16 MiB and 65536 rows; maxima are 64 MiB and 262144.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
l := telemetry.NSysLimits{Bytes: 1 << 20, Rows: 100}
fmt.Println(l.Rows)
}
Output: 100
type NSysReader ¶
Reader supplies bounded, read-only SQLite table access. It must return ErrUnavailable only for a missing table, not a query/tool failure. It must honor ctx, bound subprocess lifetime/output, and return at most limit+1 rows so a truncated table cannot be mistaken for a complete population. All calls must refer to one stable, read-only database snapshot.
Example ¶
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
// metadataFixture is a synthetic read-only database boundary. A real adapter
// belongs outside this package and must verify its stable database identity,
// bind process/cancellation/output limits, and project exact SQLite columns.
type metadataFixture struct{}
func (metadataFixture) ReadTable(ctx context.Context, name string, limit int) (telemetry.Table, error) {
if name != "META_DATA_EXPORT" {
return telemetry.Table{}, telemetry.ErrUnavailable
}
return telemetry.Table{DatabaseSHA256: strings.Repeat("b", 64), Columns: []telemetry.Column{{Name: "name", Type: "TEXT"}, {Name: "value", Type: "TEXT", Nullable: true}}, Rows: []json.RawMessage{json.RawMessage(`{"name":"EXPORT_SCHEMA_VERSION","value":"3.11.0"}`)}}, nil
}
func main() {
var r telemetry.NSysReader = metadataFixture{}
_, err := r.ReadTable(context.Background(), "OSRT_API", 1)
fmt.Println(errors.Is(err, telemetry.ErrUnavailable))
}
Output: true
type NSysReport ¶
type NSysReport struct {
Source NSysSource
SchemaVersion string
SelectedSchemaSHA256 string
Basis string
SessionStartUTCNS *int64
Providers []Provider
Events []Event
Joins []Join
Unjoined []Unjoined
Metadata []json.RawMessage
}
Report is imported evidence with basis external:nsys. It is never a local measurement or a certificate of whole-capture completion. SessionStartUTCNS retains a documented capture metadata value; it does not establish that exported timestamps were normalized to that epoch.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
r := telemetry.NSysReport{Basis: "external:nsys"}
fmt.Println(r.Basis)
}
Output: external:nsys
func ImportNSys ¶
func ImportNSys(ctx context.Context, reader NSysReader, source NSysSource, limits NSysLimits) (*NSysReport, error)
Import reads the supported tables, checks their pinned column schemas and required row types, resolves string IDs and makes only unique same-process correlations within this report. Missing tables remain explicit providers.
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
// metadataFixture is a synthetic read-only database boundary. A real adapter
// belongs outside this package and must verify its stable database identity,
// bind process/cancellation/output limits, and project exact SQLite columns.
type metadataFixture struct{}
func (metadataFixture) ReadTable(ctx context.Context, name string, limit int) (telemetry.Table, error) {
if name != "META_DATA_EXPORT" {
return telemetry.Table{}, telemetry.ErrUnavailable
}
return telemetry.Table{DatabaseSHA256: strings.Repeat("b", 64), Columns: []telemetry.Column{{Name: "name", Type: "TEXT"}, {Name: "value", Type: "TEXT", Nullable: true}}, Rows: []json.RawMessage{json.RawMessage(`{"name":"EXPORT_SCHEMA_VERSION","value":"3.11.0"}`)}}, nil
}
func Example_nsys() {
source := telemetry.NSysSource{ToolVersion: "2024.2", ToolBuild: "2024.2-fixture", ReportPath: "synthetic.nsys-rep", ReportSHA256: strings.Repeat("a", 64), DatabaseSHA256: strings.Repeat("b", 64), Clock: "unestablished"}
r, err := telemetry.ImportNSys(context.Background(), metadataFixture{}, source, telemetry.NSysLimits{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(r.SchemaVersion, r.Basis, len(r.Events))
}
func main() {
Example_nsys()
}
Output: 3.11.0 external:nsys 0
type NSysSource ¶
type NSysSource struct {
ToolVersion string
ToolBuild string
ReportPath string
ReportSHA256 string
DatabaseSHA256 string
Clock string
ShiftNS int64
}
Source preserves caller-declared export identities and clock choices. ToolVersion is the named supported release, not an inferred database version. ToolBuild identifies the actual exporter build. Clock is report-relative, unix-epoch or unestablished; ShiftNS preserves the explicit --ts-shift value. SHA256 values identify the original report and the imported database. They are not proof that a caller's declared exporter or clock choice is correct.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
s := telemetry.NSysSource{Clock: "unestablished", ShiftNS: 17}
fmt.Println(s.Clock, s.ShiftNS)
}
Output: unestablished 17
type NVLinkConfig ¶
type NVLinkConfig struct {
NodeID, SourceID, NVMLVersion, TopologyEpoch string
Links []uint32
Peers []NVLinkPeer
ValidFromNanos, ValidUntilNanos int64
}
NVLinkConfig explicitly selects links and supplies source and topology provenance. ValidUntilNanos is exclusive; the reader cannot extend validity. NVMLVersion must be supplied from the caller's initialized NVML library.
type NVLinkCounterConfig ¶
type NVLinkCounterConfig struct {
Topology NVLinkConfig
Counters []nvml.NvLinkErrorCounter
}
NVLinkCounterConfig selects documented raw counters and existing topology configuration. Counters must be distinct enum values 0–4; none are implicit.
type NVLinkCounterObservation ¶
type NVLinkCounterObservation struct {
Link uint32 `json:"link"`
Counter nvml.NvLinkErrorCounter `json:"counter"`
Query NVLinkQuery `json:"query"`
Value *uint64 `json:"value,omitempty"`
}
NVLinkCounterObservation preserves an exact raw API result or unavailable status. Available zero has a nonnil Value; failures never fabricate zero. JSON requires explicit link and counter fields, including when they are zero.
func (*NVLinkCounterObservation) UnmarshalJSON ¶
func (o *NVLinkCounterObservation) UnmarshalJSON(data []byte) error
UnmarshalJSON requires the observed link and counter identities. An omitted identity is not evidence that the API queried link or counter zero.
type NVLinkCounterReader ¶
type NVLinkCounterReader struct {
// contains filtered or unexported fields
}
NVLinkCounterReader reads at most 32 links and five counters per batch. It allocates no native resources and needs no Close. Synchronous NVML calls cannot be interrupted; cancellation is checked between calls. It is not concurrent safe and its zero value is unusable. Existing NVLinkDevice implementations do not need the optional counter interface unless this reader is constructed.
func NewNVLinkCounterReader ¶
func NewNVLinkCounterReader(device NVLinkDevice, clock Clock, config NVLinkCounterConfig) (*NVLinkCounterReader, error)
NewNVLinkCounterReader binds the optional counter API to the same physical device as the existing topology reader. Invalid selections fail before any device calls. No library/version is presumed to support a selected field; unsupported/denied calls remain per-query unavailable records.
Example ¶
device, clock, config := counterFixture() // host fake; no native producer ran
reader, err := telemetry.NewNVLinkCounterReader(device, clock, config)
if err != nil {
panic(err)
}
snapshot, err := reader.Read(context.Background())
if err != nil {
panic(err)
}
fmt.Println(snapshot.API, snapshot.ResetCoverage)
Output: nvmlDeviceGetNvLinkErrorCounter unknown
func (*NVLinkCounterReader) Read ¶
func (r *NVLinkCounterReader) Read(ctx context.Context) (*NVLinkCounterSnapshot, error)
Read preserves raw counts between topology snapshots. UUID, peer, source, clock or topology-epoch changes refuse the trusted batch. Stable unknown endpoints remain unknown; neither a nominal version nor a positive count establishes an active transfer route or a transport cause.
Example ¶
d, c, config := counterFixture()
r, _ := telemetry.NewNVLinkCounterReader(d, c, config)
snapshot, err := r.Read(context.Background())
if err != nil {
panic(err)
}
fmt.Println(snapshot.Before.DeviceUUID, len(snapshot.Observations))
Output: GPU-0 5
type NVLinkCounterSnapshot ¶
type NVLinkCounterSnapshot struct {
Version int `json:"version"`
API string `json:"api"`
ResetCoverage string `json:"reset_coverage"`
Before NVLinkSnapshot `json:"before"`
After NVLinkSnapshot `json:"after"`
Counters []nvml.NvLinkErrorCounter `json:"counters"`
Observations []NVLinkCounterObservation `json:"observations"`
}
NVLinkCounterSnapshot is version 1 raw-counter evidence bracketed by existing topology observations. Versions/API/source IDs are retained, not authenticated. Query intervals are host bounds, not sensor timestamps. ResetCoverage is always unknown: this API does not establish a reset/wrap/saturation epoch.
func ReadNVLinkCounterSnapshot ¶
func ReadNVLinkCounterSnapshot(r io.Reader, maxBytes int64) (*NVLinkCounterSnapshot, error)
ReadNVLinkCounterSnapshot decodes one strict bounded raw report (at most 256 KiB). Unknown/duplicate fields, future versions and inconsistent endpoint identities refuse rather than create a new route from counter values.
Example ¶
d, c, config := counterFixture()
r, _ := telemetry.NewNVLinkCounterReader(d, c, config)
snapshot, _ := r.Read(context.Background())
raw, _ := json.Marshal(snapshot)
decoded, err := telemetry.ReadNVLinkCounterSnapshot(bytes.NewReader(raw), 256<<10)
if err != nil {
panic(err)
}
fmt.Println(decoded.Version, *decoded.Observations[0].Value)
Output: 1 9007199254740993
func (NVLinkCounterSnapshot) Validate ¶
func (s NVLinkCounterSnapshot) Validate() error
Validate checks version 1, selected fields, exact topology/peer identity, presence and ordering. Unknown counter epochs cannot become rate evidence.
Example ¶
d, c, config := counterFixture() r, _ := telemetry.NewNVLinkCounterReader(d, c, config) snapshot, _ := r.Read(context.Background()) fmt.Println(snapshot.Validate())
Output: <nil>
type NVLinkDevice ¶
type NVLinkDevice interface {
UUID() (string, error)
NvLinkState(uint32) (nvml.EnableState, error)
NvLinkRemotePciInfo(uint32) (nvml.PciInfo, error)
NvLinkRemoteDeviceType(uint32, *nvml.IntNvLinkDeviceType) error
NvLinkVersion(uint32) (uint32, error)
}
NVLinkDevice is the selected read-only NVML surface. nvml.Device implements it. The caller owns NVML initialization and the device handle.
type NVLinkErrorCounterDevice ¶
type NVLinkErrorCounterDevice interface {
NvLinkErrorCounter(uint32, nvml.NvLinkErrorCounter) (uint64, error)
}
NVLinkErrorCounterDevice is an optional read-only addition to NVLinkDevice. nvml.Device implements it. The caller owns NVML initialization and the handle; the reader never resets counters or configures/enables utilization collection.
type NVLinkObservation ¶
type NVLinkObservation struct {
Link uint32 `json:"link"`
StateQuery NVLinkQuery `json:"state_query"`
RawState uint32 `json:"raw_state"`
PCIQuery NVLinkQuery `json:"pci_query"`
RemotePCI string `json:"remote_pci,omitempty"`
RawRemotePCI string `json:"raw_remote_pci,omitempty"`
TypeQuery NVLinkQuery `json:"type_query"`
RawRemoteType int32 `json:"raw_remote_type"`
RemoteTypeKnown bool `json:"remote_type_known"`
VersionQuery NVLinkQuery `json:"version_query"`
LinkVersion uint32 `json:"link_version"`
PeerState string `json:"peer_state"`
PeerUUID string `json:"peer_uuid,omitempty"`
}
NVLinkObservation retains raw per-link facts. RemoteTypeKnown distinguishes a recognized enum from future unknown numeric values. PeerState is mapped, unknown, ambiguous, or non_gpu. Version is nominal, never measured traffic. PciSubSystemId is deliberately omitted: NVML says it is indeterminate here.
type NVLinkPeer ¶
NVLinkPeer is a caller-established physical GPU PCI-to-UUID assignment. BusID must be the canonical eight-hex-digit domain form. Several assignments for one PCI address are permitted, but ambiguous addresses never yield UUIDs.
type NVLinkQuery ¶
type NVLinkQuery struct {
State string `json:"state"`
NativeCode string `json:"native_code,omitempty"`
StartNanos int64 `json:"start_nanos"`
EndNanos int64 `json:"end_nanos"`
}
NVLinkQuery identifies availability and the query interval of one native call. State is available, unsupported, denied, or failed. It is not link activity. NativeCode is a bounded canonical decimal NVML failure result, never error text or success code zero. Unsupported (3/13) and denied (4) classifications must match; other known or future failure codes have state failed. Device loss refuses a trusted snapshot, matching the live reader.
type NVLinkReader ¶
type NVLinkReader struct {
// contains filtered or unexported fields
}
NVLinkReader reads only explicitly selected links. It allocates no NVML resources and needs no Close. Calls cannot be interrupted inside NVML; cancellation is checked between calls. It is not safe for concurrent use. Its zero value is not usable.
func NewNVLinkReader ¶
func NewNVLinkReader(d NVLinkDevice, c Clock, config NVLinkConfig) (*NVLinkReader, error)
NewNVLinkReader binds caller-selected link indices to a physical device UUID. Known MIG UUIDs are refused: physical PCI identity cannot identify a MIG instance. It copies configuration and refuses invalid or duplicate indices before calls.
Example ¶
d, c, cfg := linkFixture() reader, _ := telemetry.NewNVLinkReader(d, c, cfg) report, _ := reader.Read(context.Background()) fmt.Println(report.Links[0].PeerUUID)
Output: GPU-1
func (*NVLinkReader) Read ¶
func (r *NVLinkReader) Read(ctx context.Context) (*NVLinkSnapshot, error)
Read queries state, remote PCI, device type and nominal version for each selected link. Unsupported fields remain unavailable without fabricated zero facts. UUID is checked before and after the batch; identity loss returns no trusted report. Query intervals are host bounds, not GPU sensor timestamps.
Example ¶
d, c, cfg := linkFixture() reader, _ := telemetry.NewNVLinkReader(d, c, cfg) report, _ := reader.Read(context.Background()) fmt.Println(report.Links[0].RemotePCI, report.Links[0].LinkVersion)
Output: 00000000:03:00.0 4
type NVLinkSnapshot ¶
type NVLinkSnapshot struct {
Version int `json:"version"`
NodeID string `json:"node_id"`
SourceID string `json:"source_id"`
NVMLVersion string `json:"nvml_version"`
DeviceUUID string `json:"device_uuid"`
TopologyEpoch string `json:"topology_epoch"`
ClockDomain string `json:"clock_domain"`
ClockEpoch string `json:"clock_epoch"`
AtNanos int64 `json:"at_nanos"`
ValidFromNanos int64 `json:"valid_from_nanos"`
ValidUntilNanos int64 `json:"valid_until_nanos"`
PeerAssignments []NVLinkPeer `json:"peer_assignments"`
Links []NVLinkObservation `json:"links"`
}
NVLinkSnapshot is version 1 bounded topology evidence. PeerAssignments are caller provenance, not discovery. Raw unmatched links remain in this report; a health graph cannot represent unknown endpoints as fabricated GPU UUIDs.
func ReadNVLinkSnapshot ¶
func ReadNVLinkSnapshot(r io.Reader, maxBytes int64) (*NVLinkSnapshot, error)
ReadNVLinkSnapshot reads one strict bounded version 1 report. maxBytes must be positive and at most 64 KiB. Unknown fields and duplicate names are refused.
Example ¶
d, c, cfg := linkFixture() reader, _ := telemetry.NewNVLinkReader(d, c, cfg) report, _ := reader.Read(context.Background()) raw, _ := json.Marshal(report) parsed, _ := telemetry.ReadNVLinkSnapshot(strings.NewReader(string(raw)), 8192) fmt.Println(parsed.Version, len(parsed.Links))
Output: 1 1
func (NVLinkSnapshot) Validate ¶
func (s NVLinkSnapshot) Validate() error
Validate checks bounded source, peer assignments, query ordering and presence flags. An active link with unresolved peer identity never becomes a UUID edge.
Example ¶
d, c, cfg := linkFixture() reader, _ := telemetry.NewNVLinkReader(d, c, cfg) report, _ := reader.Read(context.Background()) fmt.Println(report.Validate())
Output: <nil>
type NVMLFabricReader ¶
type NVMLFabricReader struct {
// contains filtered or unexported fields
}
NVMLFabricReader reads the existing version 3 fabric query and common-ancestor relationship for explicitly selected peers. It never discovers peers or modifies fabric/IMEX state. The caller owns NVML and all device handles. The zero value is unusable; reads must not run concurrently.
func NewNVMLFabricReader ¶
func NewNVMLFabricReader(device nvml.Device, peers []nvml.Device, clock Clock, nodeID, epoch, scope string, validForNanos int64) (*NVMLFabricReader, error)
NewNVMLFabricReader verifies the selected device and at most 32 peer UUIDs. validForNanos bounds the snapshot's nominal topology validity; it is a caller policy, not a native guarantee. scope follows NewNVMLHealthReader conventions.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
_, err := telemetry.NewNVMLFabricReader(0, nil, telemetry.RealClock{}, "node", "epoch", telemetry.MIGScopeUnknown, 1000000000)
fmt.Println(err)
}
Output: fabric reader requires a device
func (*NVMLFabricReader) Read ¶
func (r *NVMLFabricReader) Read(ctx context.Context) (*HealthSnapshot, error)
Read returns raw fabric fields, a separately labeled vendor summary, and directed reported common-ancestor edges. Query success never establishes sensor freshness, measured traffic, full fabric membership or IMEX health.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var reader telemetry.NVMLFabricReader
_, err := reader.Read(context.Background())
fmt.Println(err)
}
Output: invalid fabric reader
type NVMLHealthReader ¶
type NVMLHealthReader struct {
// contains filtered or unexported fields
}
NVMLHealthReader reads selected, existing NVML health APIs for one device. It never enumerates other devices, registers events, changes link settings or invokes repair/reset. The caller owns NVML initialization and the handle. It is not safe for concurrent use; the zero value is not usable.
func NewNVMLHealthReader ¶
func NewNVMLHealthReader(device nvml.Device, clock Clock, nodeID, topologyEpoch, scope string, links []uint32) (*NVMLHealthReader, error)
NewNVMLHealthReader binds a device handle to its queried UUID. scope must be a MIGScope constant: a caller without independently established scope must use MIGScopeUnknown. links explicitly selects at most 32 link indices. The reader rechecks UUID before every batch and refuses identity changes.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
_, err := telemetry.NewNVMLHealthReader(0, telemetry.NewFakeClock(1, 1), "node", "epoch", telemetry.MIGScopeUnknown, nil)
fmt.Println(err != nil)
}
Output: true
func (*NVMLHealthReader) Read ¶
func (r *NVMLHealthReader) Read(ctx context.Context) (*HealthSnapshot, error)
Read returns a bounded read-only health bundle with one query interval per field. ECC counters are volatile (driver-lifetime), not lifetime totals. retired_pages_pending is 1 if a retired page awaits a GPU reset or reboot. Link state is a boolean, not traffic or a peer-identity observation. Sensor timestamps and integration intervals remain unknown. Field failures retain typed unavailable reasons and native error text; sanitize diagnostic text before external publication. No measurements are invented for missing APIs. Cancellation is checked between NVML calls and cannot interrupt a native call.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var reader telemetry.NVMLHealthReader
_, err := reader.Read(context.Background())
fmt.Println(err != nil)
}
Output: true
type NVMLProcessDevice ¶
type NVMLProcessDevice struct {
Device DeviceMetadata
Query NVMLProcessQuery
}
NVMLProcessDevice is an opened device: its metadata and its query.
type NVMLProcessFact ¶
type NVMLProcessFact struct {
PID uint32
Device DeviceMetadata
UsedMemoryBytes uint64
HasUsedMemory bool
GPUInstanceID uint32
HasGPUInstanceID bool
ComputeInstanceID uint32
HasComputeInstanceID bool
ObservationSource string
Snapshot EntitySnapshot
}
NVMLProcessFact preserves an NVML process observation with explicit unknown memory and MIG identifiers. A PID is not a verified process generation or an MPS server/client mapping. ObservationSource names the actual queried API.
func AdaptNVMLProcesses ¶
func AdaptNVMLProcesses(device DeviceMetadata, processes []nvml.ProcessInfo, source string, snapshot EntitySnapshot) ([]NVMLProcessFact, error)
AdaptNVMLProcesses preserves bounded nvml.ProcessInfo v3 observations. It accepts nvml_compute_v3, nvml_graphics_v3 or nvml_mps_compute_v3 as the observation source. It does not perform native calls or infer process birth, exec, allocation recipient or device-wide consumption from these facts.
Example ¶
s := EntitySnapshot{SourceRevision: "synthetic-v3", ClockDomain: "monotonic", ClockEpoch: "boot", EndNanos: 1}
f, err := AdaptNVMLProcesses(DeviceMetadata{UUID: "GPU-a"}, []nvml.ProcessInfo{{Pid: 12, UsedGpuMemory: ^uint64(0), GpuInstanceId: ^uint32(0), ComputeInstanceId: ^uint32(0)}}, "nvml_compute_v3", s)
if err != nil {
panic(err)
}
fmt.Println(f[0].PID, f[0].HasUsedMemory)
Output: 12 false
func QueryNVMLProcesses ¶
func QueryNVMLProcesses(ctx context.Context, sel NVMLProcessSelection, devices []NVMLProcessDevice) ([]NVMLProcessFact, error)
QueryNVMLProcesses makes one bounded query per selected source on each device and returns the observations, in device and then source order. devices must be the selected devices in selection order.
The selection and devices are validated before any query. Every query uses one buffer of MaxPerCall entries, allocated once. A failed, unsupported or permission-denied query, a list that does not fit, or more than MaxRecords records in all fails the whole call; there is no partial or truncated result, and a failure is never an empty success. Facts keep their device, API and GPU and compute instance; the same PID may appear in several facts. A fact observes that a context existed during the query. It does not establish process identity, exec, allocation or MPS client ownership.
A canceled ctx stops further queries but cannot interrupt one in progress.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"github.com/tmc/lib/nvidia/nvml"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
// unsupportedQuery stands in for a device whose driver does not support the
// running-process queries. It reports no device data.
type unsupportedQuery struct{}
func (unsupportedQuery) ComputeRunningProcessesInto([]nvml.ProcessInfo) (int, error) {
return 0, nvml.ErrNotSupported
}
func (unsupportedQuery) GraphicsRunningProcessesInto([]nvml.ProcessInfo) (int, error) {
return 0, nvml.ErrNotSupported
}
func (unsupportedQuery) MPSComputeRunningProcessesInto([]nvml.ProcessInfo) (int, error) {
return 0, nvml.ErrNotSupported
}
func main() {
const uuid = "GPU-11111111-2222-3333-4444-555555555555"
sel := telemetry.NVMLProcessSelection{
UUIDs: []string{uuid},
Sources: []string{"nvml_compute_v3"},
MaxPerCall: 64,
MaxRecords: 65537,
BootID: "boot-1",
PIDNamespace: "pid:[4026531836]",
Snapshot: telemetry.EntitySnapshot{
SourceRevision: "fixture-nvml-1",
NodeID: "node-1",
ClockDomain: "synthetic_unix_utc",
ClockEpoch: "fixture-epoch-1",
StartNanos: 100,
EndNanos: 200,
},
}
devices := []telemetry.NVMLProcessDevice{{Device: telemetry.DeviceMetadata{UUID: uuid}, Query: unsupportedQuery{}}}
// A cap above 65536 is refused before any query.
_, err := telemetry.QueryNVMLProcesses(context.Background(), sel, devices)
fmt.Println(err)
// An unsupported query is a failure, not an empty list.
sel.MaxRecords = 64
facts, err := telemetry.QueryNVMLProcesses(context.Background(), sel, devices)
fmt.Println(len(facts), errors.Is(err, nvml.ErrNotSupported), nvml.IsUnsupported(err))
}
Output: nvml processes: record caps must be in [1, 65536] 0 true true
type NVMLProcessQuery ¶
type NVMLProcessQuery interface {
ComputeRunningProcessesInto(buf []nvml.ProcessInfo) (int, error)
GraphicsRunningProcessesInto(buf []nvml.ProcessInfo) (int, error)
MPSComputeRunningProcessesInto(buf []nvml.ProcessInfo) (int, error)
}
NVMLProcessQuery is the bounded running-process query of one device. Each method makes one query with capacity len(buf), stores the entries in buf and returns their count, or refuses a list that does not fit. nvml.Device implements it.
type NVMLProcessSelection ¶
type NVMLProcessSelection struct {
UUIDs []string
Sources []string
MaxPerCall int
MaxRecords int
BootID string
PIDNamespace string
Snapshot EntitySnapshot
}
NVMLProcessSelection selects live NVML process observations.
UUIDs lists the devices to query, in order; the caller opens each one by UUID and verifies the UUID it reports. Sources lists the queried APIs: nvml_compute_v3, nvml_graphics_v3 or nvml_mps_compute_v3. Neither list may be empty or repeat an entry. MaxPerCall is the capacity of each query and MaxRecords bounds the records of all queries; both must be in [1, 65536]. Snapshot supplies the observation provenance, and BootID, Snapshot.NodeID and PIDNamespace identify the host the queries observe, which must be the host whose proc files are read.
The caps are not the effective limits. QueryNVMLProcesses accepts at most 4096 records from each query, and ReadNVMLAttributionSnapshot reads at most 4096 distinct PIDs. Caps up to 65536 remain valid configuration, but a real result beyond 4096 records in one query, or 4096 distinct PIDs in all, fails the call rather than being truncated.
func (NVMLProcessSelection) Validate ¶
func (s NVMLProcessSelection) Validate(src SlurmAttributionSource) error
Validate reports whether s can select the processes read by src. src must be valid and configure no PIDs, and the boot, node and PID namespace identities of s and src must agree. Validate makes no native call, so a caller can validate before initializing NVML.
type NVMLSampler ¶
type NVMLSampler struct {
// contains filtered or unexported fields
}
NVMLSampler acquires live hardware telemetry from NVIDIA GPUs through NVML.
func NewNVMLSampler ¶
func NewNVMLSampler(clock Clock, devices ...nvml.Device) (*NVMLSampler, error)
NewNVMLSampler creates a sampler for the given devices. If devices is empty, it queries all available NVML devices.
func (*NVMLSampler) Devices ¶
func (s *NVMLSampler) Devices() []DeviceMetadata
Devices returns metadata for all sampled devices.
func (*NVMLSampler) NewCollectorDaemon ¶
func (s *NVMLSampler) NewCollectorDaemon(intervals CollectorIntervals) (*CollectorDaemon, error)
NewCollectorDaemon prepares an extended collector for the sampler's GPUs. The daemon owns its event sets and GPM buffers for one Run.
type NVMLXIDReader ¶
type NVMLXIDReader struct {
// contains filtered or unexported fields
}
NVMLXIDReader owns an event set registered solely for a queried device UUID. It reports native XID codes without executing catalog recommendations. Calls must be serialized. Close errors retain event-set ownership for an explicit caller retry. The zero value is not usable.
func NewNVMLXIDReader ¶
func NewNVMLXIDReader(device nvml.Device, clock Clock) (*NVMLXIDReader, error)
NewNVMLXIDReader registers critical XID events on one independently queried UUID. It does not claim per-MIG-instance reporting: raw native instance IDs remain in observation Scope. The caller owns NVML initialization. If registration and cleanup both fail, a nonnil reader is returned with the error so the caller can retain and explicitly close the event set.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
_, err := telemetry.NewNVMLXIDReader(0, telemetry.NewFakeClock(1, 1))
fmt.Println(err != nil)
}
Output: true
func (*NVMLXIDReader) Close ¶
func (r *NVMLXIDReader) Close() error
Close releases only this reader's event set. A failure leaves it owned and usable for an explicit close retry; no automatic retry is performed.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var reader *telemetry.NVMLXIDReader
fmt.Println(reader.Close())
}
Output: <nil>
func (*NVMLXIDReader) Poll ¶
func (r *NVMLXIDReader) Poll(ctx context.Context, maxEvents int) ([]HealthObservation, error)
Poll performs at most maxEvents zero-timeout native waits. A timeout means no event was observed, not that the GPU is healthy. Events have query bounds only; NVML does not provide a sensor timestamp here. Saturation returns the bounded observations plus an error rather than claiming a complete drain. An identity contradiction discards the batch; other failures retain its partial observations and return an error. Callers must record that loss.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var reader telemetry.NVMLXIDReader
_, err := reader.Poll(context.Background(), 4)
fmt.Println(err != nil)
}
Output: true
type Node ¶
type Node struct {
Path string `json:"path"`
Exists bool `json:"exists"`
CharDevice bool `json:"char_device"`
Mode fs.FileMode `json:"mode"`
Major uint32 `json:"major,omitempty"`
Minor uint32 `json:"minor,omitempty"`
OpenOK bool `json:"open_ok"`
Errno int `json:"errno,omitempty"` // errno of stat or open, when known
Error string `json:"error,omitempty"`
}
A Node is what opening one device node showed.
func ProbeNodes ¶
ProbeNodes stats and opens each path read-write and closes it again. root, if not empty, is prefixed to every path, for tests.
type Number ¶
type Number struct {
Float *float64 `json:"float,omitempty"`
Int *int64 `json:"int,omitempty"`
Uint *uint64 `json:"uint,omitempty"`
}
Number preserves one exact scalar. Its zero value has no value; an available V3 reading requires exactly one nonnil arm. Float must be finite.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
n := int64(-9223372036854775808)
b, _ := json.Marshal(telemetry.Number{Int: &n})
fmt.Println(string(b))
}
Output: {"int":-9223372036854775808}
type OTLPClockMetadata ¶
type OTLPClockMetadata struct {
ClockDomain string `json:"clock_domain"`
HasClockCalibration bool `json:"has_clock_calibration"`
ClockCalibrationBoundsNanos int64 `json:"clock_calibration_bounds_nanos"`
}
OTLPClockMetadata preserves declared clock facts, including known zero bounds.
type OTLPFormat ¶
type OTLPFormat string
OTLPFormat is an OTLP/HTTP request and response media type.
const ( FormatJSON OTLPFormat = "application/json" FormatProtobuf OTLPFormat = "application/x-protobuf" )
type OTLPHistogramReadResult ¶
OTLPHistogramReadResult contains owned canonical readings and the digest of the complete accepted current entity. TransportSHA256 is not producer lineage and never populates Observation.RawSHA256 or a point attribute.
func ReadOTLPHistogramMetrics ¶
func ReadOTLPHistogramMetrics(ctx context.Context, r io.Reader, o OTLPReadOptions) (OTLPHistogramReadResult, error)
ReadOTLPHistogramMetrics reads one bounded, strict OTLP/HTTP JSON histogram request with exactly one resource and instrumentation scope. It accepts only the reversible private attribute mapping; no vendor or native origin is inferred. Mapped V5 points allow at most 32 ordinary attributes and the exact 13 source-time attributes. Other profiles retain the total limit of 32. The reader must unblock cooperatively when ctx is canceled.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
count := uint64(0)
scope := ""
reading := telemetry.Reading{Name: "latency", Unit: telemetry.UnitSeconds, DeviceUUID: "GPU-example", Evidence: telemetry.EvidenceMeasured, TimestampUnix: 1, Observation: &telemetry.Observation{SourceClass: "imported", ClockEpoch: "unix", Kind: "histogram", OTLPScopeName: &scope, OTLPClock: &telemetry.OTLPClockMetadata{}, Observer: telemetry.Observer{SamplingCoverage: &telemetry.SamplingCoverage{Status: "unknown"}}, Histogram: &telemetry.Histogram{Count: &count, Temporality: "delta"}}}
bindings := []telemetry.HistogramBinding{{Name: "latency", Unit: telemetry.UnitSeconds}}
var wire bytes.Buffer
if err := telemetry.WriteOTLPMetrics(&wire, []telemetry.Reading{reading}, telemetry.ExportOptions{HistogramBindings: bindings}); err != nil {
panic(err)
}
result, err := telemetry.ReadOTLPHistogramMetrics(context.Background(), &wire, telemetry.OTLPReadOptions{HistogramBindings: bindings})
if err != nil {
panic(err)
}
fmt.Println(result.Readings[0].Name, *result.Readings[0].Observation.Histogram.Count)
}
Output: latency 0
type OTLPReadOptions ¶
type OTLPReadOptions struct {
HistogramBindings []HistogramBinding
MaxBytes int64
MaxMetrics int
MaxReadings int
MaxExplicitBounds int
}
OTLPReadOptions bounds one restricted OTLP histogram request. Zero selects defaults: 1 MiB, 4096 metrics, 4096 points and 256 explicit bounds. Maxima are 64 MiB, 65536 metrics, 65536 points and 4096 explicit bounds, independently.
type OTLPSourceTime ¶
type OTLPSourceTime struct {
SourceClass string `json:"source_class"`
SourceClockEpoch string `json:"source_clock_epoch"`
SourceMonotonicEndNanos int64 `json:"source_monotonic_end_nanos"`
SourceIntervalPresent bool `json:"source_interval_present"`
SourceIntervalClock string `json:"source_interval_clock"`
SourceIntervalStartNanos int64 `json:"source_interval_start_nanos"`
SourceIntervalEndNanos int64 `json:"source_interval_end_nanos"`
MappingDomain string `json:"mapping_domain"`
MappingEpoch string `json:"mapping_epoch"`
MappingValidFromNanos int64 `json:"mapping_valid_from_nanos"`
MappingValidUntilNanos int64 `json:"mapping_valid_until_nanos"`
MappingUnixOffsetNanos int64 `json:"mapping_unix_offset_nanos"`
MappingProvenance string `json:"mapping_provenance"`
}
OTLPSourceTime preserves the complete caller-asserted source-to-Unix transform. It establishes internal consistency, not calibration or source authenticity.
type Observation ¶
type Observation struct {
// OTLP fields are V5-only assertions, not verified source facts.
OTLPScopeName *string `json:"otlp_scope_name,omitempty"`
OTLPClock *OTLPClockMetadata `json:"otlp_clock_metadata,omitempty"`
OTLPSourceTime *OTLPSourceTime `json:"otlp_source_time,omitempty"`
Family string `json:"family"`
SourceClass string `json:"source_class"`
Producer string `json:"producer"`
ProducerVersion string `json:"producer_version"`
ProducerSchema string `json:"producer_schema"`
RawSHA256 string `json:"raw_sha256"`
Transform string `json:"transform"`
TransformSHA256 string `json:"transform_sha256"`
Assignment *EntityAssignment `json:"assignment,omitempty"`
Workload *obsworkload.WorkloadIdentity `json:"workload,omitempty"`
OpID obsworkload.OpID `json:"op_id,omitempty"`
Host *obsworkload.HostSubmission `json:"host,omitempty"`
Device *obsworkload.DeviceActivity `json:"device,omitempty"`
Interval *tracecontract.Interval `json:"interval,omitempty"`
ClockEpoch string `json:"clock_epoch"`
UncertaintyNS *int64 `json:"uncertainty_ns,omitempty"`
Observer Observer `json:"observer"`
Kind string `json:"kind"`
CounterEpoch string `json:"counter_epoch,omitempty"`
CounterReset bool `json:"counter_reset,omitempty"`
Histogram *Histogram `json:"histogram,omitempty"`
Denominator *Number `json:"denominator,omitempty"`
DenominatorUnit string `json:"denominator_unit,omitempty"`
Scope string `json:"scope,omitempty"`
HasReturn bool `json:"has_return,omitempty"`
TID uint64 `json:"tid,omitempty"`
}
Observation links a V3 reading to existing subject, workload and trace contracts. SourceClass is native, managed, imported, synthetic or modeled; a label alone never establishes authenticity. Missing fields stay unknown. Kind is gauge, counter, histogram, host_call, kernel, a supplied closed event, or a scheduler state (sched_running, sched_runnable, sched_blocked).
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
o := telemetry.Observation{Family: "nvml", SourceClass: "synthetic"}
fmt.Println(o.Family, o.SourceClass)
}
Output: nvml synthetic
type Observer ¶
type Observer struct {
ID string `json:"id"`
Version string `json:"version"`
Mode string `json:"mode"`
Pass string `json:"pass"`
Population string `json:"population"`
Filter string `json:"filter"`
Replay string `json:"replay"`
SamplingCoverage *SamplingCoverage `json:"sampling_coverage,omitempty"`
}
Observer identifies an observation population and mode. Empty fields remain unknown and cannot satisfy consumer admission. Reading JSON does not verify that a physical observer ran.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
o := telemetry.Observer{ID: "capture-1", Mode: "activity", Pass: "single"}
fmt.Println(o.ID, o.Mode, o.Pass)
}
Output: capture-1 activity single
type OperatorBinding ¶
type OperatorBinding struct {
Process obsworkload.ProcessGenID `json:"process"`
OpID obsworkload.OpID `json:"op_id"`
Context obsworkload.ContextStreamID `json:"context"`
GraphReplay obsworkload.GraphReplayGeneration `json:"graph_replay"`
GraphNodeID uint64 `json:"graph_node_id,omitempty"`
Code *obsevidence.EvidenceIdentity `json:"code,omitempty"`
ModuleID string `json:"module_id,omitempty"`
ModuleGeneration uint64 `json:"module_generation,omitempty"`
Pass string `json:"pass,omitempty"`
Replay string `json:"replay,omitempty"`
CompilerBuild string `json:"compiler_build,omitempty"`
CompilerOptions []string `json:"compiler_options,omitempty"`
}
OperatorBinding retains caller-supplied execution and compiler identities. Zero/absent code, module and pass fields remain unknown. These declarations do not prove that a compiler or device produced the referenced bytes.
type OperatorCPUContext ¶
type OperatorCPUContext struct {
Version int `json:"version"`
RunID string `json:"run_id"`
TraceSource WorkloadSource `json:"trace_source"`
Trace OperatorReference `json:"trace"`
Artifacts map[string][]byte `json:"artifacts"`
CodeFacts []OperatorReference `json:"code_facts,omitempty"`
Evidence []OperatorReference `json:"evidence,omitempty"`
}
OperatorCPUContext retains an imported CPU annotation trace and optional separately hashed code facts and evidence. References identify retained bytes, not native operations or contributing members. The zero value is invalid. Artifacts must contain exactly the referenced raw payloads.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var c telemetry.OperatorCPUContext
err := telemetry.WriteOperatorCPUContext(&bytes.Buffer{}, c, telemetry.WorkloadLimits{})
fmt.Println(err != nil)
}
Output: true
type OperatorContext ¶
type OperatorContext struct {
Version int `json:"version"`
RunID string `json:"run_id"`
Producer string `json:"producer"`
ProducerVersion string `json:"producer_version"`
ProducerSchema string `json:"producer_schema"`
SourceClass string `json:"source_class"`
Batch obsworkload.ActivityBatch `json:"batch"`
Receipt tracecontract.Receipt `json:"receipt"`
Annotations []obsworkload.HostSubmission `json:"annotations"`
Artifacts map[string][]byte `json:"artifacts"`
Groups []OperatorGroup `json:"groups"`
ActivityFamily string `json:"activity_family,omitempty"`
CorrelationFamily string `json:"correlation_family,omitempty"`
MetadataFamily string `json:"metadata_family,omitempty"`
}
OperatorContext is version1 application interchange, not a framework export. Artifacts closes metadata references with byte-exact raw payloads keyed by SHA256. Batch contains metadata only; its Records must be empty. Family names select existing Receipt loss entries; empty names retain unknown coverage. The zero value is not a valid interchange.
type OperatorGroup ¶
type OperatorGroup struct {
ID string `json:"id"`
Iteration string `json:"iteration,omitempty"`
Binding OperatorBinding `json:"binding"`
Members []OperatorMember `json:"members"`
InventorySource *OperatorReference `json:"inventory_source,omitempty"`
Inventory *OperatorInventory `json:"-"`
InventoryReason string `json:"-"`
}
OperatorGroup supplies contributing members for one annotated submission. Inventory is populated only by ReadOperatorContext from InventorySource. Its metadata is never inferred from names, kernel geometry or launch order.
type OperatorInventory ¶
type OperatorInventory struct {
Version int `json:"version"`
RunID string `json:"run_id"`
Binding OperatorBinding `json:"binding"`
Members []OperatorMember `json:"members"`
}
OperatorInventory is an application-owned, separately retained expectation. Version1 binds one group to its expected producer-native member IDs. Agreement establishes completeness relative to these bytes, not producer authenticity.
type OperatorMember ¶
type OperatorMember struct {
ID string `json:"id"`
Name string `json:"name"`
Schema string `json:"schema,omitempty"`
Shapes [][]int64 `json:"shapes,omitempty"`
Source OperatorReference `json:"source"`
}
OperatorMember is a supplied framework/compiler record. ID is native to its producer and scoped by Source.SHA256; Name is display text. Shapes preserve supplied dimensions (-1 means unknown), without computing tensor extents.
type OperatorReference ¶
type OracleFieldComparison ¶
type OracleFieldComparison struct {
Metric string `json:"metric"`
Unit string `json:"unit"`
NVTelemetryAvailable bool `json:"nvtelemetry_available"`
NVTelemetryBefore float64 `json:"nvtelemetry_before"`
NVTelemetryAfter float64 `json:"nvtelemetry_after"`
SMIOracleAvailable bool `json:"smi_oracle_available"`
SMIOracleValue float64 `json:"smi_oracle_value"`
DCGMOracleAvailable bool `json:"dcgm_oracle_available"`
DCGMOracleValue float64 `json:"dcgm_oracle_value"`
Tolerance float64 `json:"tolerance"`
DeltaSMI float64 `json:"delta_smi"`
DeltaDCGM float64 `json:"delta_dcgm"`
Passed bool `json:"passed"`
Detail string `json:"detail"`
}
OracleFieldComparison records the comparison of a single nvtelemetry metric against nvidia-smi and dcgmi dmon on the same sample window.
func CompareOracleSamples ¶
func CompareOracleSamples(nvtBefore, nvtAfter []Reading, smi, dcgmSample *OracleSample) ([]OracleFieldComparison, error)
CompareOracleSamples compares nvtelemetry readings acquired immediately before and after the oracle polling window against nvidia-smi and (when available) dcgmi dmon, returning per-field comparison rows and failing with ErrOracleDivergence if any field diverges beyond tolerance or has a unit error.
type OracleFieldValue ¶
OracleFieldValue holds a parsed oracle reading and its availability status.
type OracleSample ¶
type OracleSample struct {
Source string
Metrics map[string]OracleFieldValue
}
OracleSample holds the 12 GPU telemetry fields covering all 10 field categories mapped by nvtelemetry from either nvidia-smi or dcgmi dmon.
func ParseDCGMDmonOutput ¶
func ParseDCGMDmonOutput(out string) (*OracleSample, error)
ParseDCGMDmonOutput parses the tabular output of `dcgmi dmon -e 150,100,101,155,156,201,200,203,204,310,311,112 -c 1` and converts DCGM units (e.g. power in Watts -> power_milliwatts in mW) into nvtelemetry's canonical units.
func ParseNvidiaSMIQueryCSV ¶
func ParseNvidiaSMIQueryCSV(csvText string) (*OracleSample, error)
ParseNvidiaSMIQueryCSV parses a single CSV row from nvidia-smi --query-gpu (matching nvidiaSMIQueryColumns) and converts units into nvtelemetry's canonical units (e.g., power.draw in Watts -> power_milliwatts in mW).
func QueryDCGMDmonOracle ¶
func QueryDCGMDmonOracle(ctx context.Context, gpuIndex int) (*OracleSample, error)
QueryDCGMDmonOracle runs `dcgmi dmon -i <gpuIndex> -e 150,100,101,155,156,201,200,203,204,310,311,112 -c 1` if `dcgmi` is installed and reachable. Returns (nil, nil) when dcgmi is not installed or nv-hostengine is not running on the host.
func QueryNvidiaSMIOracle ¶
func QueryNvidiaSMIOracle(ctx context.Context, gpuIndex int) (*OracleSample, error)
QueryNvidiaSMIOracle runs nvidia-smi --query-gpu and nvidia-smi -q for gpuIndex and returns the parsed canonical OracleSample (converting W -> mW, KB/s -> B/s, J -> mJ).
type PCI ¶
type PCI struct {
Bus Value `xml:"pci_bus"`
Device Value `xml:"pci_device"`
Domain Value `xml:"pci_domain"`
DeviceID Value `xml:"pci_device_id"`
BusID Value `xml:"pci_bus_id"`
SubSystemID Value `xml:"pci_sub_system_id"`
MaxLinkGen Value `xml:"pci_gpu_link_info>pcie_gen>max_link_gen"`
CurrentLinkGen Value `xml:"pci_gpu_link_info>pcie_gen>current_link_gen"`
MaxLinkWidth Value `xml:"pci_gpu_link_info>link_widths>max_link_width"`
CurrentLinkWidth Value `xml:"pci_gpu_link_info>link_widths>current_link_width"`
ReplayCounter Value `xml:"replay_counter"`
ReplayRolloverCounter Value `xml:"replay_rollover_counter"`
TxUtil Value `xml:"tx_util"`
RxUtil Value `xml:"rx_util"`
}
PCI describes a GPU's PCI identity and link.
type PhaseMarker ¶
type PhaseMarker struct {
Name string `json:"name"`
StartMonotonicNanos int64 `json:"start_monotonic_nanos"`
EndMonotonicNanos int64 `json:"end_monotonic_nanos"`
}
PhaseMarker marks the boundary of an execution phase.
func (PhaseMarker) Contains ¶
func (p PhaseMarker) Contains(monoNanos int64) bool
Contains reports whether a monotonic timestamp falls within the half-open phase interval [start, end).
func (PhaseMarker) Duration ¶
func (p PhaseMarker) Duration() time.Duration
Duration returns the total duration of the phase.
type Platform ¶
type Platform struct {
ChassisSerialNumber Value `xml:"chassis_serial_number"`
SlotNumber Value `xml:"slot_number"`
TrayIndex Value `xml:"tray_index"`
HostID Value `xml:"host_id"`
PeerType Value `xml:"peer_type"`
ModuleID Value `xml:"module_id"`
GPUFabricGUID Value `xml:"gpu_fabric_guid"`
}
Platform is the rack position of a GPU in a multi-node system such as GB200 NVL72. Single-node systems report N/A.
type PluginDeviceBinding ¶
type PluginDeviceBinding struct {
ResourceName, DeviceID string
Proof EntityAssignment
}
PluginDeviceBinding maps an opaque device-plugin ID to an explicitly supplied device proof. Proof must identify the node and supplying plugin revision. Authentication is the caller's responsibility; parsing never creates trust.
type PodEntityMetadata ¶
type PodEntityMetadata struct {
Namespace, PodName, ContainerName, NodeName string
Owner EntityOwner
Running bool
Snapshot EntitySnapshot
}
PodEntityMetadata preserves core/v1 Pod identity and container status. A container name alone does not establish an execution identity.
func ReadKubernetesPodsJSON ¶
func ReadKubernetesPodsJSON(r io.Reader, snapshot EntitySnapshot) ([]PodEntityMetadata, error)
ReadKubernetesPodsJSON reads a caller-supplied core/v1 Pod or PodList. Credentials, freshness and authority are supplied by the caller. Unknown fields are ignored; omitted UID, container ID and running status stay unknown.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
s := telemetry.EntitySnapshot{SourceRevision: "v1.32.0", ClockDomain: "mono", ClockEpoch: "boot", StartNanos: 0, EndNanos: 10}
pods, err := telemetry.ReadKubernetesPodsJSON(strings.NewReader(`{"apiVersion":"v1","kind":"Pod","metadata":{"name":"worker","namespace":"default","uid":"pod-uid"},"spec":{"nodeName":"node"},"status":{"containerStatuses":[{"name":"worker","containerID":"containerd://abc","state":{"running":{}}}]}}`), s)
fmt.Println(len(pods), pods[0].Owner.PodUID, err)
}
Output: 1 pod-uid <nil>
type PodResourceAllocation ¶
type PodResourceAllocation struct {
Namespace string
PodName string
ContainerName string
ResourceName string
DeviceIDs []string
Snapshot EntitySnapshot
}
PodResourceAllocation preserves PodResources v1 List response fields. The API has pod names, not pod UIDs, and device-plugin IDs are opaque. Consequently this reader never turns a display name into an exact identity.
func ReadKubeletPodResources ¶
func ReadKubeletPodResources(ctx context.Context, socket string, snapshot EntitySnapshot) ([]PodResourceAllocation, error)
ReadKubeletPodResources lists current allocations on a local kubelet socket. An empty socket uses the standard kubelet path.
func ReadPodResourcesJSON ¶
func ReadPodResourcesJSON(r io.Reader, snapshot EntitySnapshot) ([]PodResourceAllocation, error)
ReadPodResourcesJSON reads an external protobuf-JSON rendering of Kubernetes v1 ListPodResourcesResponse using its lowerCamelCase field names. It accepts unconsumed CPU, memory and topology fields but does not interpret them. It does not read the gRPC socket or establish a pod UID or physical GPU UUID.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
s := telemetry.EntitySnapshot{SourceRevision: "kubernetes-v1.32.0", NodeID: "node-a", ClockDomain: "monotonic", ClockEpoch: "boot-a", StartNanos: 10, EndNanos: 20}
r := strings.NewReader(`{"podResources":[{"namespace":"default","name":"worker","containers":[{"name":"app","devices":[{"resourceName":"nvidia.com/gpu","deviceIds":["GPU-a"]}]}]}]}`)
allocations, err := telemetry.ReadPodResourcesJSON(r, s)
if err != nil {
panic(err)
}
fmt.Println(allocations[0].PodName, allocations[0].DeviceIDs[0])
}
Output: worker GPU-a
type Power ¶
type Power struct {
State Value
Management Value // power_readings only
PowerDraw Value
AverageDraw Value
InstantDraw Value
// Limit is the enforced limit: enforced_power_limit or
// current_power_limit.
Limit Value
// RequestedLimit is the limit set by software: power_limit or
// requested_power_limit.
RequestedLimit Value
DefaultLimit Value
MinLimit Value
MaxLimit Value
}
Power holds power readings and limits in watts.
Reports name these differently by driver: power_readings has power_limit and enforced_power_limit, while gpu_power_readings has requested_power_limit and current_power_limit, and in newer reports average_power_draw and instant_power_draw instead of power_draw.
func (Power) Draw ¶
Draw returns the first available of p.PowerDraw, p.AverageDraw, and p.InstantDraw, or p.PowerDraw if none is available.
func (*Power) UnmarshalXML ¶
UnmarshalXML decodes any of the power reading elements.
type ProcEntityFacts ¶
type ProcEntityFacts struct {
Process EntityProcess
StartTimeTicks uint64
Cgroups []string
// SelfReported contains only untrusted environment observations. It is
// independent of cgroup, scheduler and execution identity. The zero state
// means no environment observation was made.
SelfReported ProcEnvironFacts
}
ProcEntityFacts preserves Linux proc observations. Cgroups are raw membership paths, not proof of container or pod UID. StartTimeTicks is proc stat field 22 in clock ticks since boot; it is not a nanosecond or an exec generation.
func ReadProcEntity ¶
func ReadProcEntity(stat, status, cgroup io.Reader, bootID, nodeID, pidNamespace string) (ProcEntityFacts, error)
ReadProcEntity reads supplied /proc/PID/stat, status and cgroup snapshots. bootID, nodeID and pidNamespace must be supplied from the same host snapshot. It performs no filesystem access and cannot prove these reads were atomic. The returned process generation is the boot-scoped start time tick count. A zombie or dead process returns ErrProcEntityNotLive. Other states describe only the supplied snapshot, not whether the process remains alive.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
stat := strings.NewReader("12 (worker ) task) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 400")
facts, err := telemetry.ReadProcEntity(stat, strings.NewReader("NSpid:\t12\t2\n"), strings.NewReader("0::/tenant/worker\n"), "boot-a", "node-a", "pid:[100]")
if err != nil {
panic(err)
}
fmt.Println(facts.Process.Process.PID, facts.StartTimeTicks, facts.Process.HasExecGeneration)
}
Output: 12 400 false
Example (NonLive) ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
stat := "12 (worker) Z" + strings.Repeat(" 0", 18) + " 100\n"
_, err := telemetry.ReadProcEntity(strings.NewReader(stat), strings.NewReader(""), strings.NewReader(""), "boot", "node", "pidns")
fmt.Println(errors.Is(err, telemetry.ErrProcEntityNotLive))
}
Output: true
type ProcEnvironFacts ¶
type ProcEnvironFacts struct {
State ProcEnvironState
SlurmJobID string
}
ProcEnvironFacts contains only the supported self-reported environment value. SlurmJobID is nonempty only when State is ProcEnvironSelfReported. It is not a validated job identity, cgroup fact, scheduler proof or allocation authority. The zero value means no observation was made. No other environment value is retained, and these facts must not become metric labels or assigned owners.
func ReadProcEnviron ¶
func ReadProcEnviron(r io.Reader) (ProcEnvironFacts, error)
ReadProcEnviron reads at most 64 KiB of NUL-separated environment pairs. Only SLURM_JOB_ID is retained, as a self-reported UTF-8 string of at most 256 bytes. Unknown pairs are ignored. Every pair must contain a nonempty name, and duplicate SLURM_JOB_ID entries refuse even if their values agree. Empty input or a missing/empty supported value is absent. Invalid, partial and error-bearing reads return their state and an error, with no value. Reading this file cannot prove an atomic process snapshot or job ownership.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
facts, err := telemetry.ReadProcEnviron(strings.NewReader("SLURM_JOB_ID=999\x00TOKEN=not-retained\x00"))
fmt.Println(facts.State, facts.SlurmJobID, err)
}
Output: self_reported 999 <nil>
type ProcEnvironState ¶
type ProcEnvironState string
ProcEnvironState describes an untrusted environment observation.
const ( // ProcEnvironUnknown means no environment observation was made. ProcEnvironUnknown ProcEnvironState = "" // ProcEnvironAbsent means the file or supported value was absent. ProcEnvironAbsent ProcEnvironState = "absent" // ProcEnvironSelfReported means a bounded SLURM_JOB_ID value was observed. ProcEnvironSelfReported ProcEnvironState = "self_reported" // ProcEnvironInvalid means the complete input was malformed or too large. ProcEnvironInvalid ProcEnvironState = "invalid" // ProcEnvironPartial means the last environment pair was not terminated. ProcEnvironPartial ProcEnvironState = "partial" // ProcEnvironPermissionDenied means access to the observation was denied. ProcEnvironPermissionDenied ProcEnvironState = "permission_denied" // ProcEnvironReadError means I/O failed; no supported value is retained. ProcEnvironReadError ProcEnvironState = "read_error" )
type Process ¶
type Process struct {
GPUInstanceID Value `xml:"gpu_instance_id"`
ComputeInstanceID Value `xml:"compute_instance_id"`
PID Value `xml:"pid"`
Type Value `xml:"type"`
Name string `xml:"process_name"`
UsedMemory Value `xml:"used_memory"`
}
A Process is one process using a GPU.
type Provider ¶
Provider records whether a supported table exists. Available with zero Rows means an empty exported table, not an observed absence of activity.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
p := telemetry.Provider{Table: "OSRT_API", Reason: "table absent from export"}
fmt.Println(p.Available, p.Reason)
}
Output: false table absent from export
type RawLaunch ¶
type RawLaunch struct {
ID string // the export's launch ID, as written
Process string // "Process ID"
Kernel string // "Kernel Name", as exported (possibly demangled or truncated)
Context string
Stream string
Block string // "Block Size", such as "(128, 1, 1)"
Grid string // "Grid Size"
Device string
CC string
// Raw holds every metric value as written, indexed like RawTable.Metrics.
Raw []string
}
A RawLaunch is one row of a raw-page export.
type RawTable ¶
type RawTable struct {
Preamble []string // lines before the header, such as ==PROF== notices
Metrics []string // metric column names in CSV order
Units []string // unit of each metric column; "" when the export gives none
Launches []RawLaunch // in CSV order
}
A RawTable is one ncu --csv --page raw export: one row per profiled launch, one column per metric, and a units row.
Unlike [Read] and [Import], ReadRaw accepts any Nsight Compute version and any metric set. It retains what the CSV says and joins nothing: a kernel name in a row is a display string, not an identity.
func ReadRaw ¶
ReadRaw reads a raw-page CSV export of at most maxBytes bytes, as written by ncu --csv --page raw --log-file, including the ==PROF== lines ncu puts before the header. It refuses an export containing an ==ERROR== line (such as ERR_NVGPUCTRPERM, profiling not permitted), a header without ID and Kernel Name, a duplicate column, rows of the wrong length, and duplicate launch IDs, so a failed profile is never read as an empty one.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
export := `==PROF== Connected to process 1382
"ID","Kernel Name","Block Size","Grid Size","gpu__time_duration.sum","dram__bytes_read.sum"
"","","","","ns","byte"
"0","copy_kernel","(256, 1, 1)","(132, 1, 1)","16,608","8,617,984"
`
t, err := telemetry.ReadRaw(strings.NewReader(export), telemetry.MaxNCUBytes)
if err != nil {
panic(err)
}
for i := range t.Launches {
l := &t.Launches[i]
ns, _, _ := t.Value(l, "gpu__time_duration.sum")
bytes, _, _ := t.Value(l, "dram__bytes_read.sum")
fmt.Printf("%s: %.0f ns, %.1f GB/s\n", l.Kernel, ns, bytes/ns)
}
}
Output: copy_kernel: 16608 ns, 518.9 GB/s
type Reading ¶
type Reading struct {
// Number preserves the exact V3 scalar, including measured zero. Exactly one
// numeric arm is present. Legacy streams continue using Value and IntValue.
Number *Number `json:"number,omitempty"`
Observation *Observation `json:"observation,omitempty"`
Source *ReadingSource `json:"source,omitempty"`
Name string `json:"name"`
Unit string `json:"unit"`
Backend string `json:"backend"`
DeviceUUID string `json:"device_uuid"`
Evidence string `json:"evidence"`
Value float64 `json:"value,omitempty"`
IntValue uint64 `json:"int_value,omitempty"`
IsInt bool `json:"is_int,omitempty"`
TimestampMonotonic int64 `json:"timestamp_monotonic"`
TimestampUnix int64 `json:"timestamp_unix"`
SourceTimestamp int64 `json:"source_timestamp,omitempty"`
HasSourceTimestamp bool `json:"has_source_timestamp,omitempty"`
SourceTimestampDomain string `json:"source_timestamp_domain,omitempty"`
WallClockUncertaintyNanos int64 `json:"wall_clock_uncertainty_nanos,omitempty"`
HasWallClockUncertainty bool `json:"has_wall_clock_uncertainty,omitempty"`
QueryStartNanos int64 `json:"query_start_nanos,omitempty"`
QueryEndNanos int64 `json:"query_end_nanos,omitempty"`
HasQueryBounds bool `json:"has_query_bounds,omitempty"`
RefreshCadenceNanos int64 `json:"refresh_cadence_nanos,omitempty"`
IntegrationIntervalNanos int64 `json:"integration_interval_nanos,omitempty"`
IsWarmup bool `json:"is_warmup,omitempty"`
}
Reading represents a single hardware telemetry measurement or recorded unavailable status.
func NVLinkCounterReadings ¶
NVLinkCounterReadings converts a bounded raw report into existing canonical V3+ exact integer readings. sourceClass is the caller's native, imported or synthetic assertion, never an authenticity check. Scope retains endpoint, topology, selected API and raw error status; query times are not sensor times. The caller supplies independently held observer/assignment/workload and transformation artifact links if needed. CounterEpoch stays empty because reset coverage is unknown; DiagnoseTelemetry must withhold epoch-dependent findings. No gauge relabeling, rates or throughput estimates are performed.
Example ¶
d, c, config := counterFixture()
r, _ := telemetry.NewNVLinkCounterReader(d, c, config)
snapshot, _ := r.Read(context.Background())
raw, _ := json.Marshal(snapshot)
readings, err := telemetry.NVLinkCounterReadings(raw, "synthetic")
if err != nil {
panic(err)
}
fmt.Println(readings[0].Name, *readings[0].Number.Uint, readings[0].Unit)
fmt.Println(readings[0].Observation.CounterEpoch == "")
Output: nvlink_dl_replay_errors 9007199254740993 count true
func (Reading) IsAvailable ¶
IsAvailable reports whether the reading represents an active valid measurement.
type ReadingSource ¶
type ReadingSource struct {
Native *DCGMReadingSource `json:"native,omitempty"`
Mapping ManagedField `json:"mapping"`
MappingDigest string `json:"mapping_digest"`
Schema string `json:"schema"`
SourceID string `json:"source_id"`
Producer string `json:"producer"`
ProducerVersion string `json:"producer_version"`
NativeOrigin string `json:"native_origin"`
FieldID string `json:"field_id"`
RawValue string `json:"raw_value"`
Labels map[string]string `json:"labels,omitempty"`
ExpositionTimestampUnix int64 `json:"exposition_timestamp_unix,omitempty"`
HasExpositionTimestamp bool `json:"has_exposition_timestamp,omitempty"`
RawTimestamp string `json:"raw_timestamp,omitempty"`
TimestampUnit string `json:"timestamp_unit,omitempty"`
CounterReset bool `json:"counter_reset,omitempty"`
}
ReadingSource records import lineage. Exposition timestamps are producer publication timestamps, never proof of sensor acquisition time.
type RealClock ¶
type RealClock struct{}
RealClock uses host system time with decoupled monotonic and wall-clock sources.
func (RealClock) MonotonicDomain ¶
MonotonicDomain returns the monotonic domain of RealClock.
func (RealClock) MonotonicEpochID ¶
MonotonicEpochID returns the unique process-local epoch ID.
func (RealClock) NowMonotonic ¶
NowMonotonic returns monotonic time in nanoseconds elapsed since process start. It uses Go runtime monotonic clocking and never steps with NTP adjustments.
func (RealClock) Provenance ¶
Provenance returns the synchronization authority.
func (RealClock) WallDomain ¶
WallDomain returns the wall clock domain.
type Record ¶
type Record struct {
Kind Kind
Source XIDLogSource
Product Architecture
Driver string
Raw, Message, Problem string
Partial bool
Header *Kmsg
PCI, UUID string
Code uint64
PID *uint64
ProcessName string
Catalog Entry
Applicability Applicability
Recovery *RecoveryTransition
}
Record retains raw input and caller provenance even when input is unknown. PID and Recovery are nil when absent or unsupported. Catalog is a raw entry plus separate applicability, not a health or recovery policy.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var r telemetry.Record
fmt.Println(r.Recovery == nil)
}
Output: true
func ParseKmsg ¶
func ParseKmsg(raw string, o XIDLogOptions) (Record, error)
ParseKmsg parses exactly one Linux kmsg record including its metadata lines. Unknown header extension fields and flags are retained. A c flag is a fragment and is never joined with another event or treated as a complete XID.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func inputs() telemetry.XIDLogOptions {
return telemetry.XIDLogOptions{Source: telemetry.XIDLogSource{BootID: "supplied-boot", InputID: "constructed example"}, Product: "L4", Driver: "580"}
}
func main() {
v, _ := telemetry.ParseKmsg("6,10,123,-;unrelated\n", inputs())
fmt.Println(v.Header.Sequence, v.Header.MonotonicMicroseconds)
}
Output: 10 123
func ParseText ¶
func ParseText(raw string, o XIDLogOptions) (Record, error)
ParseText parses one supplied complete text line. Prefix text remains raw; dmesg or journal prefix timestamps are not interpreted as wall-clock time.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func inputs() telemetry.XIDLogOptions {
return telemetry.XIDLogOptions{Source: telemetry.XIDLogSource{BootID: "supplied-boot", InputID: "constructed example"}, Product: "L4", Driver: "580"}
}
func main() {
v, _ := telemetry.ParseText("NVRM: Xid (PCI:0000:65:00): 9999, future", inputs())
fmt.Println(v.Kind, v.Applicability == telemetry.UnknownID)
}
Output: xid true
type RecoveryText ¶
type RecoveryText uint8
RecoveryText identifies documented text, independently of the numeric token. These values are not NVML enums and do not authorize recovery operations.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
state, known := telemetry.RecognizeRecoveryText("None")
fmt.Println(known, state == telemetry.RecoveryNone)
}
Output: true true
const ( UnknownRecoveryText RecoveryText = iota RecoveryNone RecoveryDrainP2P RecoveryDrainAndReset RecoveryGPUReset RecoveryNodeReboot )
func RecognizeRecoveryText ¶
func RecognizeRecoveryText(text string) (RecoveryText, bool)
RecognizeRecoveryText recognizes only the five pinned workbook spellings. Unknown future text is not interpreted as None or an instruction to reset.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
state, known := telemetry.RecognizeRecoveryText("Future action")
fmt.Println(state == telemetry.UnknownRecoveryText, known)
}
Output: true false
type RecoveryToken ¶
type RecoveryToken struct {
Hex string
Value uint32
Text string
State RecoveryText
Recognized bool
}
RecoveryToken retains the original hexadecimal and text tokens and the parsed uint32 value. Recognized refers to Text only: numeric/text equivalence is not inferred from an NVML enum or generalized from a workbook example.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
transition, _ := telemetry.ParseRecoveryTransition("Xid 154 GPU recovery action changed from 0x0 (None) to 0xcd (Future action)")
token := transition.To
fmt.Println(token.Hex, token.Value, token.Recognized)
}
Output: 0xcd 205 false
type RecoveryTransition ¶
type RecoveryTransition struct {
XID uint64
PCI string
Message string
From RecoveryToken
To RecoveryToken
}
RecoveryTransition preserves one complete XID154 transition. PCI is empty for the workbook's bare message form; otherwise its original token is kept. Message has no inferred driver/product identity or causal preceding event.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
transition, _ := telemetry.ParseRecoveryTransition("Xid 154 GPU recovery action changed from 0x0 (None) to 0x2 (Node Reboot Required)")
fmt.Println(transition.XID, transition.PCI == "", transition.To.Text)
}
Output: 154 true Node Reboot Required
func ParseRecoveryTransition ¶
func ParseRecoveryTransition(message string) (RecoveryTransition, error)
ParseRecoveryTransition parses the documented bare "Xid 154 ..." or NVRM "Xid (PCI:...): 154, ..." message. Transport timestamps and unrelated log prefixes are not guessed. Missing, truncated, multiline or multiple events are refused. Numeric and text tokens remain separate observations; parsing is not a health classification, causal inference or remediation policy.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
event, err := telemetry.ParseRecoveryTransition("NVRM: Xid (PCI:0008:01:00): 154, GPU recovery action changed from 0x0 (None) to 0x1 (GPU Reset Required)")
fmt.Println(event.PCI, event.From.Hex, event.To.Text, err)
}
Output: 0008:01:00 0x0 GPU Reset Required <nil>
type RefreshConfig ¶
RefreshConfig bounds a periodic source refresher. All fields must be positive. Interval separates Run cycles, Timeout bounds one read or fetch, and MaxAge is how long the last successful cycle is served before results are withheld as stale.
type RefreshStatus ¶
type RefreshStatus struct {
Cycles int64 `json:"cycles"`
Failures int64 `json:"failures"`
HasAttempt bool `json:"has_attempt"`
LastAttempt int64 `json:"last_attempt_nanos"`
HasSuccess bool `json:"has_success"`
LastSuccess int64 `json:"last_success_nanos"`
LastError string `json:"last_error,omitempty"`
Records int `json:"records"`
Withheld int `json:"withheld"`
Closed bool `json:"closed"`
}
RefreshStatus reports a refresher's cycles. Times are the refresher clock's monotonic nanoseconds and are meaningful only when the matching Has field is true. Records and Withheld describe the last successful cycle.
type RemappedRows ¶
type RemappedRows struct {
Correctable Value `xml:"remapped_row_corr"`
Uncorrectable Value `xml:"remapped_row_unc"`
Pending Value `xml:"remapped_row_pending"`
Failure Value `xml:"remapped_row_failure"`
HistogramMax Value `xml:"row_remapper_histogram>row_remapper_histogram_max"`
HistogramHigh Value `xml:"row_remapper_histogram>row_remapper_histogram_high"`
HistogramPartial Value `xml:"row_remapper_histogram>row_remapper_histogram_partial"`
HistogramLow Value `xml:"row_remapper_histogram>row_remapper_histogram_low"`
HistogramNone Value `xml:"row_remapper_histogram>row_remapper_histogram_none"`
}
RemappedRows reports row remapping, used from Ampere on. Every field is unavailable when the report has "N/A" in place of the element's children.
type Result ¶
type Result struct {
Status string
Entity *Entity
WarningsAvailable, InfoAvailable bool
Warnings []Warning
Info []string
Unknown map[string]json.RawMessage
}
Result preserves a literal status and optional entity identity. The producer omits identity for FE_NONE, including ordinary results and summary rows. Warnings/info availability is independent of whether the corresponding list is empty. Status Fail may include DCGM WARN.
type Retention ¶
type Retention struct {
// contains filtered or unexported fields
}
Retention stores strictly validated complete streams. Its methods serialize access. An operating-system file lock refuses live writers and recoverers. A crashed writer requires explicit recovery. The owner marker is never removed; its inode is the lock identity, and the active lease is a hard link to it. Version 1 directories require manual migration after all old writers have stopped. The zero value is closed.
func OpenRetention ¶
func OpenRetention(path string, cfg RetentionConfig) (*Retention, error)
OpenRetention opens or initializes a private task directory. It rejects foreign files, symbolic links, corrupt streams and another writer's lease. Changing budgets is checked before deleting any retained data (configuration rollback). The operating system must support the package's nonblocking file locks.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
_, err := telemetry.OpenRetention("unused", telemetry.RetentionConfig{})
fmt.Println(err)
}
Output: invalid retention configuration
func (*Retention) Close ¶
Close removes this writer's lease link, then closes the root before releasing its file lock. A cleanup failure retains admission for a retry; it never removes a substituted lease or owner marker. Streams are preserved.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var retained telemetry.Retention
fmt.Println(retained.Close())
}
Output: <nil>
func (*Retention) NextStreamID ¶
NextStreamID returns the next monotonically increasing stream ID for this retention directory.
func (*Retention) Status ¶
func (r *Retention) Status() RetentionStatus
Status validates the bounded managed state under the writer lock. Corruption returns Ready=false and StateError=state_unavailable, with zero counts whose availability must not be inferred. A closed or zero Retention reports closed. It neither prunes nor probes writes and makes no free-disk-space claim.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var retained telemetry.Retention
status := retained.Status()
fmt.Println(status.Closed, status.Ready, status.CountsAvailable)
}
Output: true false false
func (*Retention) Store ¶
Store validates and writes a bounded complete stream, removes the oldest owned streams to make room, then publishes it. A pending write needs at most MaxStreamBytes extra disk headroom. A failed publication can follow pruning; callers must retain the input until Store succeeds. IDs are increasing thirteen-digit integers; replaying an existing or older ID is refused.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var retained telemetry.Retention
fmt.Println(retained.Store(1, nil))
}
Output: retention is closed
type RetentionConfig ¶
type RetentionConfig struct {
Owner string `json:"owner"`
MaxFiles int `json:"max_files"`
MaxBytes int64 `json:"max_bytes"`
MaxStreamBytes int64 `json:"max_stream_bytes"`
}
RetentionConfig bounds complete streams in an exclusively task-owned directory. Owner is a stable, non-secret task identifier. The directory must be private to the calling user and must not be writable by other users.
type RetentionRecoveryManifest ¶
type RetentionRecoveryManifest struct {
SchemaVersion int `json:"schema_version"`
MarkerVersion int `json:"marker_version"`
Owner string `json:"owner"`
RecoveredLease bool `json:"recovered_lease"`
PendingStream bool `json:"pending_stream"`
RetainedFiles int `json:"retained_files"`
RetainedBytes int64 `json:"retained_bytes"`
NextStreamID uint64 `json:"next_stream_id"`
}
RetentionRecoveryManifest records the versioned recovery state of an owned retention directory.
func ReadRetentionRecoveryManifest ¶
func ReadRetentionRecoveryManifest(r io.Reader) (RetentionRecoveryManifest, error)
ReadRetentionRecoveryManifest strictly decodes and validates a JSON recovery manifest.
func RecoverRetentionManifest ¶
func RecoverRetentionManifest(path, owner string) (RetentionRecoveryManifest, error)
RecoverRetentionManifest recovers an owned retention directory under the exclusive owner marker lock and returns a versioned recovery manifest describing the recovered state.
type RetentionStatus ¶
type RetentionStatus struct {
CountsAvailable bool `json:"counts_available"`
Files int `json:"files"`
Bytes int64 `json:"bytes"`
MaxFiles int `json:"max_files"`
MaxBytes int64 `json:"max_bytes"`
MaxStreamBytes int64 `json:"max_stream_bytes"`
Closed bool `json:"closed"`
Ready bool `json:"ready"`
AtCapacity bool `json:"at_capacity"`
StateError string `json:"state_error,omitempty"`
LastOperationError string `json:"last_operation_error,omitempty"`
Stores uint64 `json:"stores"`
StoreFailures uint64 `json:"store_failures"`
PrunedFiles uint64 `json:"pruned_files"`
PrunedBytes uint64 `json:"pruned_bytes"`
QueryDuration time.Duration `json:"query_duration_nanos"`
}
RetentionStatus describes the managed streams and observations since open. Limits exclude the marker, lease, and a pending file; Store may require an additional MaxStreamBytes of disk space. AtCapacity indicates pruning pressure, not disk exhaustion. Readiness is a bounded validation, not a write probe. Error fields contain fixed categories, never paths or stream contents.
type RetiredPages ¶
type RetiredPages struct {
SingleBitCount Value `xml:"multiple_single_bit_retirement>retired_count"`
DoubleBitCount Value `xml:"double_bit_retirement>retired_count"`
PendingBlacklist Value `xml:"pending_blacklist"`
PendingRetirement Value `xml:"pending_retirement"`
}
RetiredPages reports dynamic page retirement, used before Ampere.
type Row ¶
type Row struct {
Launch LaunchKey `json:"launch"`
Entry string `json:"entry"`
Block [3]uint64 `json:"block"`
Grid [3]uint64 `json:"grid"`
Target string `json:"target"`
Section string `json:"section"`
Raw []string `json:"raw"`
Metric *Metric `json:"metric,omitempty"`
ModuleID string `json:"module_id,omitempty"`
Generation uint64 `json:"generation,omitempty"`
JoinReason string `json:"join_reason,omitempty"`
}
Row retains every CSV field, including unsupported rule diagnostics. ModuleID and Generation are set only after a unique verified join.
type SMIGPU ¶
type SMIGPU struct {
// ID is the PCI bus ID from the id attribute, such as "00000000:01:00.0".
ID string `xml:"id,attr"`
ProductName string `xml:"product_name"`
ProductBrand string `xml:"product_brand"`
ProductArchitecture string `xml:"product_architecture"`
UUID string `xml:"uuid"`
VBIOSVersion string `xml:"vbios_version"`
Serial Value `xml:"serial"`
MinorNumber Value `xml:"minor_number"`
BoardID Value `xml:"board_id"`
BoardPartNumber Value `xml:"board_part_number"`
GPUPartNumber Value `xml:"gpu_part_number"`
ModuleID Value `xml:"gpu_module_id"`
GSPFirmwareVersion Value `xml:"gsp_firmware_version"`
DisplayMode Value `xml:"display_mode"`
DisplayActive Value `xml:"display_active"`
PersistenceMode Value `xml:"persistence_mode"`
AddressingMode Value `xml:"addressing_mode"`
ComputeMode Value `xml:"compute_mode"`
PerformanceState Value `xml:"performance_state"`
FanSpeed Value `xml:"fan_speed"`
VirtualizationMode Value `xml:"gpu_virtualization_mode>virtualization_mode"`
MIGMode Value `xml:"mig_mode>current_mig"`
PendingMIGMode Value `xml:"mig_mode>pending_mig"`
ECCMode Value `xml:"ecc_mode>current_ecc"`
PendingECCMode Value `xml:"ecc_mode>pending_ecc"`
// ResetRequired and DrainAndResetRecommended come from
// gpu_reset_status, which newer reports replace with
// RecoveryAction.
ResetRequired Value `xml:"gpu_reset_status>reset_required"`
DrainAndResetRecommended Value `xml:"gpu_reset_status>drain_and_reset_recommended"`
RecoveryAction Value `xml:"gpu_recovery_action"`
MIGDevices []MIGDevice `xml:"mig_devices>mig_device"`
Platform Platform `xml:"platformInfo"`
InfoROM InfoROM `xml:"inforom_version"`
PCI PCI `xml:"pci"`
// ClockEventReasons is decoded from clocks_event_reasons or,
// in older reports, clocks_throttle_reasons.
ClockEventReasons ClockEventReasons `xml:"-"`
FBMemory Memory `xml:"fb_memory_usage"`
BAR1Memory Memory `xml:"bar1_memory_usage"`
Utilization Utilization `xml:"utilization"`
ECCErrors ECCErrors `xml:"ecc_errors"`
RetiredPages RetiredPages `xml:"retired_pages"`
RemappedRows RemappedRows `xml:"remapped_rows"`
Temperature Temperature `xml:"temperature"`
// Power is decoded from gpu_power_readings or, in older
// reports, power_readings.
Power Power `xml:"-"`
ModulePower Power `xml:"module_power_readings"`
MemoryPower Power `xml:"gpu_memory_power_readings"`
Clocks Clocks `xml:"clocks"`
ApplicationsClocks Clocks `xml:"applications_clocks"`
DefaultApplicationsClocks Clocks `xml:"default_applications_clocks"`
MaxClocks Clocks `xml:"max_clocks"`
GraphicsVoltage Value `xml:"voltage>graphics_volt"`
Fabric Fabric `xml:"fabric"`
Processes []Process `xml:"processes>process_info"`
// Other holds elements of the gpu element with no field above.
Other []Element `xml:",any"`
}
A GPU is the report for one device.
func (*SMIGPU) UnmarshalXML ¶
UnmarshalXML decodes a gpu element, accepting both the old and new names of the power and clock event reason elements.
type SMIOption ¶
type SMIOption func(*smiConfig)
SMIOption configures RunSMI and QueryCSV.
func WithSMIBinary ¶
WithSMIBinary sets the nvidia-smi executable path used by RunSMI and QueryCSV. An empty path uses the default ("nvidia-smi").
type SMIResult ¶
type SMIResult struct {
ExitCode int `json:"exit_code"` // -1 when it could not run or timed out
Error string `json:"error,omitempty"`
Output string `json:"output,omitempty"` // first 4 KiB of stdout and stderr when it failed
GPUs []HealthGPU `json:"gpus,omitempty"`
}
SMIResult is one nvidia-smi run.
type Sample ¶
type Sample struct {
Seq uint64 `json:"seq"`
QueryStartNanos int64 `json:"query_start_nanos"`
QueryEndNanos int64 `json:"query_end_nanos"`
LagNanos int64 `json:"lag_nanos"`
ClockDiscontinuity bool `json:"clock_discontinuity,omitempty"`
ClockDiscontinuityReason string `json:"clock_discontinuity_reason,omitempty"`
Readings []Reading `json:"readings"`
}
Sample packages a single scheduled polling pass across all devices.
func FetchManaged ¶
func FetchManaged(ctx context.Context, client *http.Client, request *http.Request, c ManagedImport, clock Clock, maxBytes int64) (Sample, error)
FetchManaged reads a bounded caller-selected Prometheus/OpenMetrics endpoint using explicit canonical mappings. It records local query bounds with clock; these bounds do not establish sensor time, freshness or clock calibration. c's query bounds and TimestampUnix must be zero: they are acquired here. GET is the only supported method. The client and request are not modified. Redirects are refused, and errors omit URLs, credentials and response bodies.
Example ¶
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "# TYPE DCGM_FI_DEV_POWER_USAGE gauge\nDCGM_FI_DEV_POWER_USAGE{UUID=\"GPU-a\"} 12.5\n")
}))
defer server.Close()
request, _ := http.NewRequest("GET", server.URL, nil)
sample, err := FetchManaged(context.Background(), server.Client(), request, ManagedImport{SourceID: "demo", Producer: "dcgm-exporter", ProducerVersion: "4.6.1", NativeOrigin: "dcgm", Fields: DCGMExporterFields()}, RealClock{}, 4096)
fmt.Println(len(sample.Readings), err)
Output: 1 <nil>
func ReadManaged ¶
ReadManaged reads explicitly mapped fields into a canonical sample. Unknown fields are ignored. Missing fields remain absent; callers must not infer zero. Native collector ownership and network acquisition remain with the caller.
Example ¶
c := ManagedImport{SourceID: "scrape-1", Producer: "dcgm-exporter", ProducerVersion: "explicit-fixture-v1", NativeOrigin: "dcgm/nvml/GPU-a", Fields: []ManagedField{{Metric: "power", Name: "power_milliwatts", Numerator: 1000, Denominator: 1, Integer: true}}}
s, e := ReadManaged(context.Background(), strings.NewReader("power{UUID=\"GPU-a\"} 12.5\n"), c)
fmt.Println(s.Readings[0].IntValue, s.Readings[0].HasSourceTimestamp, e)
Output: 12500 false <nil>
Example (FloatingSentinel) ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
raw := "# TYPE DCGM_FI_DEV_POWER_USAGE gauge\nDCGM_FI_DEV_POWER_USAGE{UUID=\"GPU-a\"} 140737488355344\n"
sample, err := telemetry.ReadManaged(context.Background(), strings.NewReader(raw), telemetry.ManagedImport{SourceID: "protocol-control", Producer: "dcgm-exporter", ProducerVersion: "control", NativeOrigin: "control", Fields: telemetry.DCGMExporterFields()})
reading := sample.Readings[0]
fmt.Println(err, reading.IsAvailable(), reading.UnavailableReason, reading.Source.RawValue)
}
Output: <nil> false blank 140737488355344
type SamplePoint ¶
type SamplePoint struct {
Timestamp int64
Value float64
IntValue uint64
IsInt bool
Available bool
Unit string
}
SamplePoint records a typed sample for window aggregation.
type Sampler ¶
type Sampler interface {
Sample(ctx context.Context) ([]Reading, error)
Devices() []DeviceMetadata
}
Sampler samples hardware or mock telemetry on request.
type SamplingCoverage ¶
type SamplingCoverage struct {
Status string `json:"status"`
Basis string `json:"basis,omitempty"`
Scope string `json:"scope,omitempty"`
Numerator *Number `json:"numerator,omitempty"`
Denominator *Number `json:"denominator,omitempty"`
Unit string `json:"unit,omitempty"`
Reason string `json:"reason,omitempty"`
}
SamplingCoverage records exact observed and eligible units for one observer population. A measured time basis is activity-union duration within the containing observation interval; other bases describe bounded populations, not elapsed-time duty. Nil means absent, while a present unknown status is explicit evidence that the measure is unknown.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
observed, eligible := uint64(0), uint64(100)
coverage := telemetry.SamplingCoverage{
Status: "measured",
Basis: "time",
Scope: "activity-union/eligible-window-v1",
Numerator: &telemetry.Number{Uint: &observed},
Denominator: &telemetry.Number{Uint: &eligible},
Unit: "ns",
}
fmt.Printf("%s %s %d/%d %s\n", coverage.Status, coverage.Basis, *coverage.Numerator.Uint, *coverage.Denominator.Uint, coverage.Unit)
}
Output: measured time 0/100 ns
type ServingAttempt ¶
type ServingAttempt struct {
RequestID string `json:"request_id"`
Attempt string `json:"attempt"`
Worker string `json:"worker"`
WorkerEpoch string `json:"worker_epoch"`
Role string `json:"role"` // prefill, decode, combined, unknown
Outcome string `json:"outcome"` // accepted, failed, cancelled, partial, unknown
OutputTokens *uint64 `json:"output_tokens,omitempty"`
OutputPolicy string `json:"output_policy,omitempty"`
Evidence string `json:"evidence"`
}
ServingAttempt retains a caller-supplied request outcome. RequestID alone is not unique: attempts, worker and restart epoch are required. Token counts are present only when the application reports them. No GPU attribution is made.
type ServingAttemptRef ¶
type ServingBatch ¶
type ServingBatch struct {
ID string `json:"id"`
Worker string `json:"worker"`
WorkerEpoch string `json:"worker_epoch"`
Role string `json:"role"` // prefill, decode, combined, unknown
Members []ServingAttemptRef `json:"members"`
OpIDs []obsworkload.OpID `json:"op_ids,omitempty"`
Process *obsworkload.ProcessGenID `json:"process,omitempty"`
Basis string `json:"basis"`
Evidence string `json:"evidence,omitempty"`
}
ServingBatch is a supplied batch executed by one worker restart epoch. Members and OpIDs are many-to-many: an attempt may appear in several batches and a batch's operations are shared work, not per-request shares. Process scopes OpIDs to the worker process that issued them.
type ServingCache ¶
type ServingCache struct {
Namespace string `json:"namespace"`
Generation string `json:"generation"`
Worker string `json:"worker"`
WorkerEpoch string `json:"worker_epoch"`
Evidence string `json:"evidence"`
}
ServingCache declares one cache namespace generation owned by a worker restart epoch. A cache block is not general device memory.
type ServingCacheUse ¶
type ServingCacheUse struct {
Attempt ServingAttemptRef `json:"attempt"`
Namespace string `json:"namespace"`
Generation string `json:"generation"`
Event string `json:"event"`
Basis string `json:"basis"`
Evidence string `json:"evidence,omitempty"`
}
ServingCacheUse is a supplied cache event for one attempt. Event is hit, miss, store, evict or unknown. A record is identified by its attempt, namespace, generation and event: it states that the event occurred, not how often, so a repeated event of one kind is a single record.
type ServingContext ¶
type ServingContext struct {
Version int `json:"version"`
RunID string `json:"run_id"`
Attempts []ServingAttempt `json:"attempts"`
}
ServingContext is a versioned application interchange. It is not an SGLang or Dynamo exporter mapping, and cannot expand aggregate scrapes into requests.
type ServingContextSummary ¶
type ServingContextSummary struct {
Accepted, Failed, Cancelled, Partial, Unknown uint64
KnownAcceptedTokenAttempts, AcceptedOutputTokens uint64
}
ServingContextSummary keeps accepted attempts and unsuccessful work separate. Accepted attempts are not necessarily distinct successful requests; retries remain separate. Unknown token counts never become measured zero.
func SummarizeServingContext ¶
func SummarizeServingContext(c ServingContext, l WorkloadLimits) (ServingContextSummary, error)
SummarizeServingContext counts supplied outcomes without assigning device time, energy, cache memory, or shared batch work to individual requests.
Example ¶
c := ServingContext{Version: 1, RunID: "r", Attempts: []ServingAttempt{{RequestID: "q", Attempt: "1", Worker: "w", WorkerEpoch: "e", Role: "decode", Outcome: "partial", Evidence: "application-log"}}}
out, _ := SummarizeServingContext(c, WorkloadLimits{})
fmt.Println(out.Accepted, out.Partial)
Output: 0 1
type ServingContextV2 ¶
type ServingContextV2 struct {
Version int `json:"version"`
RunID string `json:"run_id"`
Attempts []ServingAttempt `json:"attempts"`
Routes []ServingRoute `json:"routes"`
Batches []ServingBatch `json:"batches"`
Caches []ServingCache `json:"caches"`
CacheUses []ServingCacheUse `json:"cache_uses"`
Transfers []ServingTransferRef `json:"transfers"`
}
ServingContextV2 is the version 2 serving interchange. Attempts keep the version 1 meaning; routes, batches, caches and transfer references extend them. ReadServingContext refuses version 2, and ReadServingContextV2 refuses every other version.
func (ServingContextV2) V1 ¶
func (c ServingContextV2) V1() ServingContext
V1 returns the version 1 projection of the attempts. The attempt slice is copied; a nil slice stays nil so the version 1 validator still refuses it.
Example ¶
s, err := telemetry.SummarizeServingContext(servingContextV2Fixture().V1(), telemetry.WorkloadLimits{})
fmt.Println(s.Accepted, s.Failed, s.AcceptedOutputTokens, err)
Output: 1 1 9007199254740993 <nil>
type ServingRoute ¶
type ServingRoute struct {
Attempt ServingAttemptRef `json:"attempt"`
Frontend string `json:"frontend"`
Decision string `json:"decision"`
Basis string `json:"basis"`
Evidence string `json:"evidence,omitempty"`
}
ServingRoute is a supplied routing decision delivering one attempt from a frontend to its worker. Decision is routed, retried, rejected or unknown.
Basis, here and in the other version 2 edges, is native_id when the producer reported the identities natively, annotation when the application associated them, or unknown. Evidence names the supporting artifact and is required unless the basis is unknown; for native_id it is the artifact's SHA-256.
type ServingTransferRef ¶
type ServingTransferRef struct {
Attempt ServingAttemptRef `json:"attempt"`
TransferID string `json:"transfer_id"`
Basis string `json:"basis"`
Evidence string `json:"evidence,omitempty"`
}
ServingTransferRef references a MovementTransfer by ID from the movement context of the same run. It is not a second transfer record.
type SlurmAllocation ¶
type SlurmAllocation struct {
JobID string
Nodes string
TRESAlloc string
State []string
Snapshot EntitySnapshot
}
SlurmAllocation preserves a bounded squeue JSON allocation observation. TRESAlloc describes counts/types, not GPU UUIDs or CUDA process identity. Job IDs from process environment variables are not accepted by this reader.
func ReadSlurmSqueueJSON ¶
func ReadSlurmSqueueJSON(r io.Reader, snapshot EntitySnapshot) ([]SlurmAllocation, error)
ReadSlurmSqueueJSON reads jobs[].job_id, nodes, tres_alloc_str and job_state from externally supplied squeue --json data_parser v0.0.43 output. Other fields remain unconsumed. Only running jobs carry an active allocation. The caller must pin the supplying scheduler revision in snapshot.
type SlurmAttributionSource ¶
type SlurmAttributionSource struct {
Squeue string
Mappings string
Executions string
ProcDir string
PIDs []uint32
BootID string
NodeID string
PIDNamespace string
Snapshot EntitySnapshot
}
SlurmAttributionSource names explicitly configured attribution inputs in an fs.FS. File names are fs.ValidPath names. The reader opens exactly Squeue, Mappings, Executions and, for each PID, ProcDir/PID/stat, status and cgroup, followed by an optional environ observation after valid process identity. Missing, inaccessible or invalid environ supplies no self-reported value; it does not discard separately valid cgroup facts. It never lists a directory.
Squeue is squeue --json data_parser v0.0.43 output read by ReadSlurmSqueueJSON. Mappings is a version 1 document {"version":1,"mappings":[...]} of SlurmGPUMapping records. Executions is a version 1 EntityExport. Snapshot pins the scheduler revision, node, clock and validity interval; BootID, NodeID and PIDNamespace identify the host snapshot the proc files came from. The source does not authenticate its producers.
type SlurmCgroupIdentity ¶
type SlurmCgroupIdentity struct {
JobID string `json:"job_id"`
StepID string `json:"step_id,omitempty"`
TaskID string `json:"task_id,omitempty"`
CgroupPath string `json:"cgroup_path"`
}
SlurmCgroupIdentity records the parsed job, step, and task IDs extracted from a Slurm cgroup hierarchy path.
func ParseSlurmCgroupPath ¶
func ParseSlurmCgroupPath(path string) (SlurmCgroupIdentity, error)
ParseSlurmCgroupPath parses an absolute Slurm cgroup path or a proc cgroup membership line. Unified v2 lines use hierarchy 0 and no controllers. V1 lines require a positive hierarchy and a nonempty, unique list of controller names consisting of lowercase letters, digits and underscores. Named v1 hierarchies such as name=systemd are outside this profile. It requires a valid job_<jobid> component and strict hierarchy ordering (job before step, step before task). Membership is not allocation authority.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
id, err := telemetry.ParseSlurmCgroupPath("/sys/fs/cgroup/system.slice/slurmstepd.scope/job_12345/step_0/task_1")
if err != nil {
panic(err)
}
fmt.Printf("job=%s step=%s task=%s\n", id.JobID, id.StepID, id.TaskID)
}
Output: job=12345 step=0 task=1
func ResolveSlurmProcessCgroup ¶
func ResolveSlurmProcessCgroup(facts ProcEntityFacts) (SlurmCgroupIdentity, error)
ResolveSlurmProcessCgroup extracts and validates supported Slurm cgroup membership from a process's ProcEntityFacts. It returns an error if no valid Slurm cgroup is found or if contradictory memberships are listed.
type SlurmGPUMapping ¶
type SlurmGPUMapping struct {
JobID string `json:"job_id"`
StepID string `json:"step_id,omitempty"`
TaskID string `json:"task_id,omitempty"`
Device DeviceMetadata `json:"device"`
Sharing string `json:"sharing,omitempty"` // exclusive, time_slice, mig, mps, unknown
MIGConfigurationEpoch string `json:"mig_configuration_epoch,omitempty"`
MPSRole string `json:"mps_role,omitempty"`
MPSServer *EntityProcess `json:"mps_server,omitempty"`
AllocationID string `json:"allocation_id,omitempty"`
Attempt string `json:"attempt,omitempty"`
Authoritative bool `json:"authoritative"`
ClockDomain string `json:"clock_domain,omitempty"`
ClockEpoch string `json:"clock_epoch,omitempty"`
StartNanos int64 `json:"start_nanos,omitempty"`
EndNanos int64 `json:"end_nanos,omitempty"`
}
SlurmGPUMapping specifies an explicit device assignment for a Slurm job or step. Authentication and freshness are the supplying authority's responsibility.
func (SlurmGPUMapping) Validate ¶
func (m SlurmGPUMapping) Validate() error
Validate verifies structural validity of a SlurmGPUMapping.
type SlurmGRESAllocation ¶
type SlurmGRESAllocation struct {
Count int `json:"count"`
GPUType string `json:"gpu_type,omitempty"`
DeviceIDs []string `json:"device_ids,omitempty"`
Raw string `json:"raw"`
}
SlurmGRESAllocation represents parsed GRES GPU resources from Slurm TRESAlloc.
func ParseSlurmGRES ¶
func ParseSlurmGRES(tresAlloc string) (SlurmGRESAllocation, error)
ParseSlurmGRES parses the GRES GPU component from a Slurm tres_alloc_str. Contradictory, duplicate, or malformed GPU allocations return an error. Aggregate counts and typed counts that specialize or match the aggregate count are reconciled.
type Snapshot ¶
type Snapshot struct {
Owner [16]byte
Generation uint64
PublishedUnix int64
EpochID string
ClockDomain string
SchemaVersion int
Devices []DeviceMetadata
Sample Sample
}
Snapshot is one publication. Owner and Generation identify a publisher incarnation and publication; a changed Owner denotes a restart or takeover.
func DecodeBridge ¶
Decode rejects incompatible versions, bounds, identity, nonfinite values, unknown flag bits, and nonzero reserved or unused bytes.
type SourceCell ¶
type SourceCell struct{ Sheet, Coordinate, Value string }
SourceCell retains supporting interpretation or linkage text separately from a rule. It is not an instruction to perform recovery.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
cell := telemetry.DecodeSources()[0]
fmt.Println(cell.Coordinate, cell.Value)
}
Output: A1 Xid
func DecodeSources ¶
func DecodeSources() []SourceCell
DecodeSources returns detached header, guide and XID linkage cells.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
cells := telemetry.DecodeSources()
fmt.Println(cells[0].Sheet, cells[0].Coordinate, cells[0].Value)
}
Output: Xid 144-150 Decode A1 Xid
type Span ¶
A Span is one interval on a timeline: a kernel execution on the device or a CUDA API call on the host. Stream is the CUDA stream of a kernel and -1 when unknown.
func KernelSpans ¶
func KernelSpans(r *NSysReport) ([]Span, error)
KernelSpans returns the kernel executions in r in start order.
func ReadAPITraceCSV ¶
ReadAPITraceCSV reads the CSV that
nsys stats --report cuda_api_trace --format csv
writes, in start order.
type SpanWindow ¶
type SpanWindow struct {
Start, End int64
Period time.Duration
// Samples is the number of samples whose queries lie in the window.
Samples int
// Coverage is the fraction of the window within one period after a
// sample's query start. A window shorter than the period, or one
// whose samples were missed or overwritten, has coverage below 1.
Coverage float64
// window has no samples; the summaries below are then empty.
Unavailable string
TemperatureC FieldSummary
SMClockMHz FieldSummary
// ClocksEventReasons is the union of the reason bits over the window.
ClocksEventReasons Field
}
A SpanWindow summarizes a Monitor's samples over a span's interval.
func (SpanWindow) Attrs ¶
func (w SpanWindow) Attrs() map[string]any
Attrs returns the window as cudaotlp span attributes. A window with no samples carries gpu.telemetry.unavailable and no GPU readings; a field with no readings is listed in gpu.telemetry.unavailable_fields as field=reason.
type StepGroups ¶
type StepGroups struct {
// contains filtered or unexported fields
}
StepGroups gathers a run's consecutive steps into telemetry windows long enough to hold samples. A 10 ms decode step is shorter than the default 20 ms sampling period, so the window of one step usually holds no sample; a window of several steps holds some. It is safe for concurrent use.
Example ¶
package main
import (
"fmt"
"time"
"github.com/tmc/lib/nvidia/nvml"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
// l4 is a fake NVML device. Real callers use OpenMonitor, which opens
// the device through NVML.
type l4 struct{ sm uint32 }
func (l4) Temperature(nvml.TemperatureSensors) (uint32, error) { return 58, nil }
func (d l4) ClockInfo(c nvml.ClockType) (uint32, error) {
if c == nvml.ClockSm {
return d.sm, nil
}
return 6251, nil
}
func (l4) PowerUsage() (uint32, error) { return 71500, nil }
func (l4) UtilizationRates() (nvml.Utilization, error) {
return nvml.Utilization{Gpu: 97, Memory: 40}, nil
}
func (l4) MemoryInfoV2() (nvml.MemoryV2, error) { return nvml.MemoryV2{}, nvml.ErrNotSupported }
func (l4) CurrentClocksEventReasons() (uint64, error) {
return nvml.ClocksEventReasonSwPowerCap, nil
}
func main() {
clock := telemetry.NewFakeClock(0, 0)
m := telemetry.NewMonitor(l4{sm: 2040}, telemetry.MonitorConfig{Clock: clock, Period: time.Minute})
defer m.Close()
// Group 10 ms steps into windows of at least 30 ms.
g := m.StepGroups(30 * time.Millisecond)
for i := range 7 {
clock.Advance(10 * time.Millisecond) // step i runs
g.Step()
if _, n, ok := g.Window(); ok {
fmt.Printf("step %d closes a window of %d steps\n", i, n)
}
}
}
Output: step 2 closes a window of 3 steps step 5 closes a window of 3 steps
func (*StepGroups) Window ¶
func (g *StepGroups) Window() (w SpanWindow, steps int, ok bool)
Window returns the window of the steps counted since the group began, and how many there were, if they span at least the minimum; it then begins the next group. Otherwise it reports false and the group goes on. A caller asks at the end of a step whose span is to carry the window, so the window ends with that step.
type Store ¶
type Store interface {
Lookup(key, value []byte) error
Update(key, value []byte, flags uint64) error
Close() error
}
Store is a map descriptor. Lookup copies a whole value; Update must replace the hash entry, never mutate its existing value in place.
type StreamRecord ¶
type StreamRecord struct {
Manifest *Manifest `json:"manifest,omitempty"`
Sample *Sample `json:"sample,omitempty"`
Phase *PhaseMarker `json:"phase,omitempty"`
}
StreamRecord is the envelope for lines in a telemetry JSONL stream.
type Table ¶
type Table struct {
// DatabaseSHA256 identifies the stable database snapshot used by Reader.
// Reader must verify it against the actual source, not repeat an expected hash.
DatabaseSHA256 string
Columns []Column
Rows []json.RawMessage
}
Table contains declared columns and exact JSON row projections of an export. Rows must include every declared column, using null for absent values.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
t := telemetry.Table{Rows: []json.RawMessage{json.RawMessage(`{"start":1}`)}}
fmt.Println(len(t.Rows))
}
Output: 1
type Temperature ¶
type Temperature struct {
GPU Value `xml:"gpu_temp"`
Memory Value `xml:"memory_temp"`
Target Value `xml:"gpu_target_temperature"`
MaxThreshold Value `xml:"gpu_temp_max_threshold"`
SlowThreshold Value `xml:"gpu_temp_slow_threshold"`
MaxGPUThreshold Value `xml:"gpu_temp_max_gpu_threshold"`
MaxMemThreshold Value `xml:"gpu_temp_max_mem_threshold"`
TLimit Value `xml:"gpu_temp_tlimit"`
MaxTLimitThreshold Value `xml:"gpu_temp_max_tlimit_threshold"`
SlowTLimitThreshold Value `xml:"gpu_temp_slow_tlimit_threshold"`
MaxGPUTLimitThreshold Value `xml:"gpu_temp_max_gpu_tlimit_threshold"`
MaxMemTLimitThreshold Value `xml:"gpu_temp_max_mem_tlimit_threshold"`
}
Temperature holds temperatures and thresholds in degrees C. The TLimit fields, in newer reports, are margins relative to a limit rather than absolute temperatures.
type Test ¶
type Test struct {
Name string
ResultsAvailable bool
Results []Result
Summary *Result
Unknown map[string]json.RawMessage
}
Test retains per-entity results and an optional aggregate summary. An omitted results field does not identify which GPUs did not run or why.
type Topology ¶
type Topology struct {
// Devices lists the matrix rows, in order.
Devices []TopologyDevice
// Links[i][j] is the link between Devices[i] and Devices[j].
Links [][]Link
// Columns lists the affinity column headings, such as
// "CPU Affinity", "NUMA Affinity", and "GPU NUMA ID".
Columns []string
// Legend maps each link type in the legend, such as "PIX" or
// "NV#", to its description.
Legend map[string]string
// NICs maps a NIC row name, such as "NIC0", to the device name
// in the NIC legend, such as "mlx5_0". Older drivers print the
// device name as the row name and no NIC legend.
NICs map[string]string
}
A Topology is the output of nvidia-smi topo -m: a matrix of links between GPUs and NICs, the CPU and memory affinity of each GPU, and the legends printed below the matrix.
func ParseTopology ¶
ParseTopology reads the output of nvidia-smi topo -m from r.
It accepts the tab-separated text nvidia-smi writes, with or without the terminal escape codes it adds to the heading, and copies in which tabs became runs of spaces. It returns an error if the matrix is not square, a row name does not match its column heading, or a device's link to itself is not X.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"log"
"strings"
)
func main() {
const out = "\tGPU0\tGPU1\tNIC0\tCPU Affinity\tNUMA Affinity\n" +
"GPU0\t X \tNV12\tPIX\t0-15\t0\n" +
"GPU1\tNV12\t X \tSYS\t16-31\t1\n" +
"NIC0\tPIX\tSYS\t X \n" +
"\n" +
"NIC Legend:\n" +
"\n" +
" NIC0: mlx5_0\n"
topo, err := telemetry.ParseTopology(strings.NewReader(out))
if err != nil {
log.Fatal(err)
}
l, _ := topo.Link("GPU0", "GPU1")
n, _ := l.NVLinks()
fmt.Println(l, n)
l, _ = topo.Link("GPU0", "NIC0")
fmt.Println(l, topo.NICs["NIC0"])
cpus, _ := topo.Devices[1].CPUAffinity.IntList()
fmt.Println(len(cpus), cpus[0])
}
Output: NV12 12 PIX mlx5_0 16 16
func QueryTopology ¶
QueryTopology runs nvidia-smi topo -m, found in $PATH, and parses its output. nvidia-smi supports topo only on Linux.
type TopologyDevice ¶
type TopologyDevice struct {
// Name is the row name, such as "GPU0", "NIC1", or "mlx5_0".
Name string
// CPUAffinity, NUMAAffinity, and GPUNUMAID are the columns of
// the same names. NICs leave them empty. See [Value.IntList].
CPUAffinity Value
NUMAAffinity Value
GPUNUMAID Value
// Other holds affinity columns with no field above,
// keyed by heading.
Other map[string]Value
}
A TopologyDevice is one row of a Topology.
type TopologyEdge ¶
type TopologyEdge struct {
SourceID string `json:"source_id"`
From string `json:"from"`
To string `json:"to"`
Kind string `json:"kind"`
Scope string `json:"scope"`
State string `json:"state"` // available, unsupported, denied, failed
Capability string `json:"capability,omitempty"`
ValidFromNanos int64 `json:"valid_from_nanos"`
ValidUntilNanos int64 `json:"valid_until_nanos"`
}
TopologyEdge is a directed, time-bounded reported relationship. Capability is a nominal description; it is never interpreted as measured traffic.
type TrainingCheckpoint ¶
type TrainingCheckpoint struct {
CheckpointID string `json:"checkpoint_id"`
State string `json:"state"` // requested, writing, published, restored
Digest string `json:"digest,omitempty"`
Storage string `json:"storage,omitempty"`
SourceAttempt string `json:"source_attempt"`
SavedStep uint64 `json:"saved_step"`
Rank uint32 `json:"rank"`
WorldSize uint32 `json:"world_size"`
RestoredAttempt string `json:"restored_attempt,omitempty"`
ResumeGeneration *uint64 `json:"resume_generation,omitempty"`
Evidence string `json:"evidence"`
}
TrainingCheckpoint is an application-supplied checkpoint observation. SavedStep includes completed optimizer update N, so recovery counts updates strictly after N. Digest is a lowercase SHA-256 identifying the global checkpoint. Storage may differ by rank, but publication and restore must name the same storage per rank. Evidence is an application artifact reference, not verified durability proof. RestoredAttempt and ResumeGeneration are required only for restored records; generation zero is valid and distinct from an absent generation.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
p := telemetry.TrainingCheckpoint{CheckpointID: "synthetic", State: "requested", SourceAttempt: "first", SavedStep: 0, WorldSize: 1, Evidence: "application:request"}
fmt.Println(p.State, p.SavedStep)
}
Output: requested 0
type TrainingCheckpointContext ¶
type TrainingCheckpointContext struct {
Version int `json:"version"`
RunID string `json:"run_id"`
Checkpoints []TrainingCheckpoint `json:"checkpoints"`
}
TrainingCheckpointContext is a distinct version 1 application interchange. Records retain source order, which is not a measured or declared event clock. Missing lifecycle records remain missing; state names do not prove chronology, storage durability, or a framework's actual checkpoint behavior.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
c := telemetry.TrainingCheckpointContext{Version: 1, RunID: "synthetic", Checkpoints: []telemetry.TrainingCheckpoint{}}
fmt.Println(c.Version, len(c.Checkpoints))
}
Output: 1 0
type TrainingContext ¶
type TrainingContext struct {
Version int `json:"version"`
RunID string `json:"run_id"`
Updates []TrainingUpdate `json:"updates"`
}
TrainingContext is a consumer interchange, not a vendor export or native measurement. Evidence identifies an independent application artifact; its contents and quality policy are not verified by this reader.
type TrainingContextSummary ¶
type TrainingContextSummary struct {
Accepted, Rejected, Skipped, Failed, Unknown, Incomplete uint64
}
TrainingContextSummary counts complete single-rank or multi-rank updates. Unknown and unsuccessful work remain visible. No durations or GPU shares are inferred, and an accepted quality assertion is not a convergence proof.
func SummarizeTrainingContext ¶
func SummarizeTrainingContext(c TrainingContext, l WorkloadLimits) (TrainingContextSummary, error)
SummarizeTrainingContext reports optimizer outcomes by attempt and global step. Every expected rank must be present before a step is classified. A rejected rank rejects the step even if other ranks report accepted quality.
Example ¶
c := TrainingContext{Version: 1, RunID: "r", Updates: []TrainingUpdate{{Attempt: "resume", Step: 10, WorldSize: 2, Outcome: "updated", Quality: "unknown", Evidence: "rank0-log"}}}
out, _ := SummarizeTrainingContext(c, WorkloadLimits{})
fmt.Println(out.Incomplete)
Output: 1
type TrainingOperatorReference ¶
type TrainingOperatorReference struct {
GroupID string `json:"group_id"`
Binding OperatorBinding `json:"binding"`
}
TrainingOperatorReference identifies an existing supplied operator group and its complete declared binding. Equality is agreement, not native observation. Missing native/compiler identities remain unknown in the consumer.
type TrainingPhase ¶
type TrainingPhase struct {
ID string `json:"id"`
Attempt string `json:"attempt"`
Restart string `json:"restart"`
Worker string `json:"worker"`
OptimizerStep uint64 `json:"optimizer_step"`
LoggingStep uint64 `json:"logging_step"`
Epoch uint64 `json:"epoch"`
Batch uint64 `json:"batch"`
Microbatch uint64 `json:"microbatch"`
AccumulationStep uint64 `json:"accumulation_step"`
AccumulationCount uint64 `json:"accumulation_count"`
Rank uint32 `json:"rank"`
WorldSize uint32 `json:"world_size"`
CommunicatorEpoch string `json:"communicator_epoch"`
Phase string `json:"phase"`
QualityPolicy string `json:"quality_policy"`
Evidence string `json:"evidence"`
Operators []TrainingOperatorReference `json:"operators"`
}
TrainingPhase retains supplied phase identity. OptimizerStep and LoggingStep have different meanings. Multiple microbatches may name one optimizer update; phase rows are never counted as updates. No duration or additive wall time is derived. Evidence retains the raw application phase/clock/loss artifact. All integers, including zero, must be explicit on the wire.
type TrainingPhaseContext ¶
type TrainingPhaseContext struct {
Version int `json:"version"`
RunID string `json:"run_id"`
Policies []TrainingQualityPolicy `json:"policies"`
Phases []TrainingPhase `json:"phases"`
}
TrainingPhaseContext is the separate version 2 training detail interchange. The existing version 1 optimizer and checkpoint interchanges stay unchanged. Policies and phases are bounded by WorkloadLimits; no provider SDK is used.
type TrainingQualityPolicy ¶
type TrainingQualityPolicy struct {
ID string `json:"id"`
Model string `json:"model"`
Data string `json:"data"`
Configuration string `json:"configuration"`
Seed string `json:"seed"`
Precision string `json:"precision"`
LossScaling string `json:"loss_scaling"`
Optimizer string `json:"optimizer"`
LearningRateSchedule string `json:"learning_rate_schedule"`
Batching string `json:"batching"`
Oracle string `json:"oracle"`
Tolerance string `json:"tolerance"`
Metric string `json:"metric"`
ConvergenceWindow string `json:"convergence_window"`
Numerical string `json:"numerical"`
Evidence string `json:"evidence"`
}
TrainingQualityPolicy retains supplied identities, not verified quality or convergence. Empty details remain unavailable. Numerical is accepted, rejected or unknown; Evidence names the independently owned oracle artifact. Tolerance and ConvergenceWindow are opaque policy identities, not numbers from which this package invents a numerical or convergence criterion.
type TrainingRecovery ¶
type TrainingRecovery struct {
CheckpointID string
Digest string
SourceAttempt string
SavedStep uint64
RestoredAttempt string
ResumeGeneration uint64
RecoveryAvailable bool
After TrainingContextSummary
ObservedAcceptedLoss *uint64
UpdatePopulationComplete bool
}
TrainingRecovery reports one explicitly supplied restored attempt/generation. RecoveryAvailable requires matching publication and restore for every rank. After counts observed source-attempt outcomes strictly after SavedStep. ObservedAcceptedLoss is nil unless recovery and those observed rank groups are complete and consistent. A nonnil count is conditional on the supplied records: entire omitted updates are undetectable, so UpdatePopulationComplete is always false. Even an observed zero is not a total-loss claim.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var r telemetry.TrainingRecovery
fmt.Println(r.RecoveryAvailable, r.ObservedAcceptedLoss == nil, r.UpdatePopulationComplete)
}
Output: false true false
type TrainingRecoverySummary ¶
type TrainingRecoverySummary struct {
RunID string
TrainingRawSHA256 string
CheckpointRawSHA256 string
Updates TrainingContextSummary
Checkpoints []TrainingCheckpoint
Recoveries []TrainingRecovery
}
TrainingRecoverySummary binds all identities and observations to the original training and checkpoint export bytes. It does not authenticate application assertions or infer phase-to-kernel, time, quality, or durable-storage joins.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
var s telemetry.TrainingRecoverySummary
fmt.Println(len(s.Recoveries))
}
Output: 0
func SummarizeTrainingRecovery ¶
func SummarizeTrainingRecovery(training, checkpoints WorkloadExport, l WorkloadLimits) (TrainingRecoverySummary, error)
SummarizeTrainingRecovery verifies both RawSHA256 values and rereads the actual bounded Raw bytes through the context readers. Mutable decoded objects and export metadata cannot replace the run, attempt or step identities in Raw. Counts reuse SummarizeTrainingContext's all-rank outcome classification.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
// Synthetic application assertions; these do not certify durable storage.
source := telemetry.WorkloadSource{Provider: "application", Version: "synthetic-v1", RunID: "synthetic"}
training := telemetry.TrainingContext{Version: 1, RunID: source.RunID, Updates: []telemetry.TrainingUpdate{
{Attempt: "a", Step: 11, WorldSize: 1, Outcome: "updated", Quality: "accepted", QualityPolicy: "application:oracle", Evidence: "application:update"},
}}
generation := uint64(1)
publication := telemetry.TrainingCheckpoint{CheckpointID: "h", State: "published", Digest: strings.Repeat("a", 64), Storage: "application:storage", SourceAttempt: "a", SavedStep: 10, WorldSize: 1, Evidence: "application:publication"}
restore := publication
restore.State, restore.RestoredAttempt, restore.ResumeGeneration = "restored", "b", &generation
restore.Evidence = "application:restore"
checkpoints := telemetry.TrainingCheckpointContext{Version: 1, RunID: source.RunID, Checkpoints: []telemetry.TrainingCheckpoint{publication, restore}}
var t, c bytes.Buffer
if err := telemetry.WriteTrainingContext(&t, training, telemetry.WorkloadLimits{}); err != nil {
panic(err)
}
if err := telemetry.WriteTrainingCheckpointContext(&c, checkpoints, telemetry.WorkloadLimits{}); err != nil {
panic(err)
}
te, _, err := telemetry.ReadTrainingContext(&t, source, telemetry.WorkloadLimits{})
if err != nil {
panic(err)
}
ce, _, err := telemetry.ReadTrainingCheckpointContext(&c, source, telemetry.WorkloadLimits{})
if err != nil {
panic(err)
}
summary, err := telemetry.SummarizeTrainingRecovery(te, ce, telemetry.WorkloadLimits{})
if err != nil {
panic(err)
}
r := summary.Recoveries[0]
fmt.Println(r.RecoveryAvailable, *r.ObservedAcceptedLoss, r.UpdatePopulationComplete)
}
Output: true 1 false
type TrainingStepReport ¶
type TrainingStepReport struct {
StepKind string
Steps []int64
GapAfter []int64
MissingRanks []int
UnknownRank bool
GapAfterByRank map[int][]int64
MissingRanksByStep map[int64][]int
}
TrainingStepReport exposes observed steps and missing expected ranks. It does not infer convergence, phase transitions, or checkpoint correctness.
func InspectTrainingSteps ¶
func InspectTrainingSteps(exports []WorkloadExport, metric string, expectedRanks []int) (TrainingStepReport, error)
InspectTrainingSteps checks one metric and run across exported rank histories. ExpectedRanks is an explicit caller contract, not a count inferred from GPUs.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
rank := 0
source := telemetry.WorkloadSource{Provider: "mlflow", Version: "2.22.0", RunID: "train1", Rank: &rank}
raw := `{"metrics":[{"key":"loss","value":0.5,"step":0},{"key":"loss","value":0.2,"step":2}]}`
export, err := telemetry.ReadMLflowHistory(strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
report, err := telemetry.InspectTrainingSteps([]telemetry.WorkloadExport{export}, "loss", []int{0, 1})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(report.Steps, report.GapAfter, report.MissingRanks)
}
Output: [0 2] [0] [1]
type TrainingUpdate ¶
type TrainingUpdate struct {
Attempt string `json:"attempt"`
Step uint64 `json:"step"`
Rank uint32 `json:"rank"`
WorldSize uint32 `json:"world_size"`
Outcome string `json:"outcome"` // updated, skipped, failed, unknown
Quality string `json:"quality"` // accepted, rejected, unknown
QualityPolicy string `json:"quality_policy,omitempty"`
Evidence string `json:"evidence"`
}
TrainingUpdate is an application-supplied optimizer outcome. Step is the optimizer step, not an experiment logging index. Attempt separates resumed runs. Unknown quality cannot qualify useful work.
type TrainingWorkloadOTLPOptions ¶
type TrainingWorkloadOTLPOptions struct {
UnixClockProvenance string
UnitEvidence map[string]string
Limits WorkloadLimits
}
TrainingWorkloadOTLPOptions declares the original producer timestamps as Unix time in the selected profile's units. UnixClockProvenance is required caller evidence, not authenticated synchronization or a clock transform. The source ClockDomain must be unix_utc. UnitEvidence names caller evidence for each explicit Source.Units entry used; absent units remain unknown. Limits bound input, points, names and output. A finite export may have one series per retained history step and raw digest; these bounds are not a continuous collector's cardinality policy.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
options := telemetry.TrainingWorkloadOTLPOptions{
UnixClockProvenance: "caller-owned SDK timestamp contract; no synchronization bound",
Limits: telemetry.WorkloadLimits{MaxMetrics: 10},
}
fmt.Println(options.Limits.MaxMetrics, len(options.UnitEvidence))
}
Output: 10 0
type TriggerPolicy ¶
type TriggerPolicy struct {
MetricName string `json:"metric_name"`
Threshold float64 `json:"threshold"`
Comparison string `json:"comparison"` // ">" (also the default), ">=", "<", "<="
TenantID string `json:"tenant_id,omitempty"`
Reason string `json:"reason,omitempty"`
}
TriggerPolicy evaluates telemetry readings against an escalation threshold.
func (TriggerPolicy) Matches ¶
func (tp TriggerPolicy) Matches(r Reading) bool
Matches reports whether reading r satisfies the trigger condition. Unavailable, histogram and malformed scalar readings never match. An empty Comparison means ">"; other unsupported comparisons never match. Integer readings are converted to float64 for comparison with Threshold; integers outside [-2^53, 2^53] may round. The Reading retains its exact value.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
r := telemetry.Reading{Name: "queue_depth", Evidence: telemetry.EvidenceMeasured, Value: 11}
p := telemetry.TriggerPolicy{MetricName: r.Name, Threshold: 10}
fmt.Println(p.Matches(r))
p.Comparison = ">>"
fmt.Println(p.Matches(r))
}
Output: true false
type UnixTimeMapping ¶
type UnixTimeMapping struct {
SourceClockDomain string
SourceClockEpoch string
SourceValidFromNanos int64
SourceValidUntilNanos int64
UnixOffsetNanos int64
Provenance string
}
UnixTimeMapping asserts a 1:1 nanosecond transform within an inclusive source range. The zero value is invalid. These facts are supplied by the caller and establish no independently verified calibration or source authenticity.
type Unjoined ¶
Unjoined explains why a device activity has no unique API correlation.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
u := telemetry.Unjoined{Event: 1, Reason: "ambiguous API correlation"}
fmt.Println(u.Reason)
}
Output: ambiguous API correlation
type UnsupportedError ¶
type UnsupportedError struct{ Version, Format string }
UnsupportedError reports an unsupported producer version or document shape. Version is empty unless a version string was actually present in the input.
func (*UnsupportedError) Error ¶
func (e *UnsupportedError) Error() string
type Utilization ¶
type Utilization struct {
GPU Value `xml:"gpu_util"`
Memory Value `xml:"memory_util"`
Encoder Value `xml:"encoder_util"`
Decoder Value `xml:"decoder_util"`
JPEG Value `xml:"jpeg_util"`
OFA Value `xml:"ofa_util"`
}
Utilization holds engine utilization percentages.
type Value ¶
type Value string
A Value is the text of one leaf element, such as "45 C", "1024 MiB", "Enabled", or "N/A". The zero Value means the element was absent.
Its methods ignore surrounding white space.
func (Value) Available ¶
Available reports whether v holds a reading. It is false for an absent element and for placeholders such as "N/A", "N/A", "Not Supported", "[Not Supported]", and "Requested functionality has been deprecated".
func (Value) Bool ¶
Bool interprets the state words nvidia-smi prints: "Enabled", "Yes", "Active", and "True" are true; "Disabled", "No", "Not Active", and "False" are false. Case is ignored. It reports ok=false for anything else.
func (Value) Bytes ¶
Bytes returns v as a number of bytes. The unit must be one nvidia-smi uses for sizes: B, KiB, MiB, GiB, or TiB. It reports ok=false for any other unit, so "4000 KB/s" is not a size.
func (Value) Float ¶
Float returns the number at the start of v, ignoring any unit: 70.12 for "70.12 W". It reports ok=false if v is unavailable or does not start with a number.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
for _, v := range []telemetry.Value{"45 C", "N/A", "[Not Supported]"} {
f, ok := v.Float()
fmt.Println(f, ok)
}
}
Output: 45 true 0 false 0 false
func (Value) Int ¶
Int returns the integer at the start of v, ignoring any unit: 45 for "45 C" and 16 for "16x". A whole value with a 0x prefix, such as "0x100", is read as hexadecimal. It reports ok=false if v is unavailable or does not start with an integer.
func (Value) IntList ¶
IntList parses a list of non-negative integers and inclusive ranges, such as "0-19,40-59", as nvidia-smi topo -m prints CPU and NUMA affinity. It reports ok=false for placeholders like "N/A", for malformed lists, and for lists of more than 65536 integers.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
list, ok := telemetry.Value("0-3,8").IntList()
fmt.Println(list, ok)
}
Output: [0 1 2 3 8] true
type Warning ¶
type Warning struct {
Code dcgm.ErrorCode
Category, Severity uint32
Message string
Unknown map[string]json.RawMessage
}
Warning retains the producer's numeric diagnostic code, category and severity. Message does not supply a guessed code; unknown codes remain numeric values.
type WindowOptions ¶
type WindowOptions struct {
MaxAllowedGapNanos int64 // maximum acceptable gap between samples before flagging coverage gap
}
WindowOptions controls aggregation constraints.
type WindowSummary ¶
type WindowSummary struct {
HistogramBoundaryCount int `json:"histogram_boundary_count,omitempty"`
HistogramBoundaryReason HistogramWindowReason `json:"histogram_boundary_reason,omitempty"`
WindowName string `json:"window_name"`
DeviceUUID string `json:"device_uuid"`
MetricName string `json:"metric_name"`
Unit string `json:"unit"`
// Aggregation is AggregationDelta for a cumulative counter, whose
// TimeWeightedMean and ArithmeticMean are zero because a running total
// has no meaningful mean. It is empty for a summary that holds means.
Aggregation string `json:"aggregation,omitempty"`
// Delta is a counter's increase from its first to its last reading in
// the window, and RatePerSecond is Delta per second between those
// readings. DeltaReason, when set, says why both are withheld.
Delta uint64 `json:"delta,omitempty"`
RatePerSecond float64 `json:"rate_per_second,omitempty"`
DeltaReason string `json:"delta_reason,omitempty"`
// TimeWeightedMean is a float64 approximation computed by integrating
// floating-point sample values over covered intervals.
TimeWeightedMean float64 `json:"time_weighted_mean"`
// ArithmeticMean is a float64 approximation computed from valid sample
// values. It is not an exact average of large integer inputs.
ArithmeticMean float64 `json:"arithmetic_mean"`
Min float64 `json:"min"`
Max float64 `json:"max"`
StartValue float64 `json:"start_value"`
EndValue float64 `json:"end_value"`
// SampleValuesStatus and SampleValuesReason cover Min, Max, StartValue and
// EndValue only. They are set when those fields are withheld for precision.
// An empty status is compatible with older summaries and does not assert
// either metric unavailability or exact sample values.
SampleValuesStatus string `json:"sample_values_status,omitempty"`
SampleValuesReason string `json:"sample_values_reason,omitempty"`
CoveredDurationNanos int64 `json:"covered_duration_nanos"`
TotalDurationNanos int64 `json:"total_duration_nanos"`
CoverageRatio float64 `json:"coverage_ratio"`
MaxGapNanos int64 `json:"max_gap_nanos"`
SampleCount int `json:"sample_count"`
}
WindowSummary aggregates one metric over a named window.
type WorkloadAnnotation ¶
type WorkloadAnnotation struct {
Name string
RawStart string
RawDuration string
StartNanos int64
DurationNanos int64
PID json.RawMessage
TID json.RawMessage
Args json.RawMessage
}
WorkloadAnnotation preserves a bounded PyTorch user annotation interval. Names are not parsed into steps, phases or ranks. Producer timestamp offsets retain the caller-declared trace clock; they are not NVML sensor timestamps.
type WorkloadDelta ¶
type WorkloadDelta struct {
Name string
Unit string
Semantic string
Kind string
Labels map[string]string
Delta string
StartNanos int64
EndNanos int64
}
WorkloadDelta is an exact decimal counter difference between two aggregate observations. It never supplies request identity or successful-token policy.
func CounterWorkloadWindow ¶
func CounterWorkloadWindow(before, after WorkloadExport, start, end int64, domain, epoch string) ([]WorkloadDelta, error)
CounterWorkloadWindow computes differences for matching cumulative counters. Both exports must bound the requested window exactly in the declared clock domain and epoch. Visible decreases, missing series and rolling versions are errors. A counter reset that recovers between observations is not observable. Gauges and histogram components remain in the exports, without interpolation.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
source := telemetry.WorkloadSource{Provider: "triton", Version: "25.06", RunID: "serving1"}
read := func(count string, when int64) telemetry.WorkloadExport {
raw := "# TYPE nv_inference_request_success counter\nnv_inference_request_success{model=\"example\",version=\"1\"} " + count + "\n"
e, err := telemetry.ReadServingExposition(context.Background(), strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return telemetry.WorkloadExport{}
}
e, err = telemetry.StampWorkloadSnapshot(e, when, "replay", "epoch1")
if err != nil {
fmt.Println(err)
}
return e
}
a, b := read("10", 0), read("13", 100)
delta, err := telemetry.CounterWorkloadWindow(a, b, 0, 100, "replay", "epoch1")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(delta[0].Semantic, delta[0].Delta)
}
Output: successful_requests 3
func HistogramWorkloadWindow ¶
func HistogramWorkloadWindow(before, after WorkloadExport, start, end int64, domain, epoch string) ([]WorkloadDelta, error)
HistogramWorkloadWindow differences compatible cumulative histogram buckets, counts and sums. Bounds and all label identities must match between snapshots. The result describes aggregate observations, never individual latencies.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
source := telemetry.WorkloadSource{Provider: "vllm", Version: "0.8.5", RunID: "serving1"}
raw := `# TYPE vllm:time_to_first_token_seconds histogram
vllm:time_to_first_token_seconds_bucket{model_name="example",le="+Inf"} 1
vllm:time_to_first_token_seconds_count{model_name="example"} 1
vllm:time_to_first_token_seconds_sum{model_name="example"} 0.5
`
e, err := telemetry.ReadServingExposition(context.Background(), strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
a, err := telemetry.StampWorkloadSnapshot(e, 0, "replay", "epoch1")
if err != nil {
fmt.Println(err)
return
}
b, err := telemetry.StampWorkloadSnapshot(e, 10, "replay", "epoch1")
if err != nil {
fmt.Println(err)
return
}
delta, err := telemetry.HistogramWorkloadWindow(a, b, 0, 10, "replay", "epoch1")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(delta), delta[0].Delta)
}
Output: 3 0
type WorkloadExport ¶
type WorkloadExport struct {
Source WorkloadSource
Raw []byte
RawSHA256 string
Metrics []WorkloadMetric
NextPageToken string
UnmappedNames []string
}
WorkloadExport contains bounded original bytes and normalized observations. RawSHA256 is computed by the reader and can be checked independently.
func ReadClearMLScalars ¶
func ReadClearMLScalars(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, error)
ReadClearMLScalars reads the response body of ClearML 1.18.0 API v2.9 events.get_task_events. Only training_stats_scalar events are normalized; other event kinds remain in Raw. Timestamp units are milliseconds.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
source := telemetry.WorkloadSource{Provider: "clearml", Version: "1.18.0/api-2.9", RunID: "train1"}
raw := `{"events":[{"type":"training_stats_scalar","task":"train1","metric":"loss","variant":"train","value":0.5,"iter":0}]}`
export, err := telemetry.ReadClearMLScalars(strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(export.Metrics[0].Labels["variant"], export.Metrics[0].HasTime)
}
Output: train false
func ReadMLflowHistory ¶
func ReadMLflowHistory(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, error)
ReadMLflowHistory reads MLflow 2.22.0 /api/2.0/mlflow/metrics/get-history response JSON. RunID is required because this response does not contain it. Pagination is retained in NextPageToken; one page is not a complete run.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
source := telemetry.WorkloadSource{Provider: "mlflow", Version: "2.22.0", RunID: "train1", Units: map[string]string{"loss": "1"}}
raw := `{"metrics":[{"key":"loss","value":0.5,"timestamp":1700000000000,"step":0}]}`
export, err := telemetry.ReadMLflowHistory(strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
p := export.Metrics[0]
fmt.Println(p.Name, p.RawValue, p.RawTime, p.Step, p.HasStep)
}
Output: loss 0.5 1700000000000 0 true
func ReadServingExposition ¶
func ReadServingExposition(ctx context.Context, r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, error)
ReadServingExposition reads pinned Triton 25.06, vLLM 0.8.5, Ray 2.44.0, SGLang 0.5.21 or Dynamo 1.5.1 Prometheus text 0.0.4 snapshots through the shared bounded exposition parser. The SGLang and Dynamo versions are separate source contracts, not a claim that a Dynamo image bundles that SGLang version. Optional native timestamps are retained. A timestamp absent from the export stays absent; use StampWorkloadSnapshot for a separately recorded scrape time. Unmapped fields remain in Raw, listed in UnmappedNames.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
source := telemetry.WorkloadSource{Provider: "triton", Version: "25.06", RunID: "serving1"}
raw := `# TYPE nv_inference_exec_count counter
nv_inference_exec_count{model="batching",version="1"} 2
`
export, err := telemetry.ReadServingExposition(context.Background(), strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
p := export.Metrics[0]
fmt.Println(p.Semantic, p.RawValue, p.Unit, p.HasTime)
}
Output: uncached_batch_executions 2 executions false
Example (RayMemoryUnits) ¶
Ray 2.44.0 reports GPU memory as integer MiB. The input below is a constructed Prometheus text control in Ray's metric shape, not a Ray export.
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
source := telemetry.WorkloadSource{Provider: "ray", Version: "2.44.0", RunID: "cluster1"}
raw := `# HELP ray_node_gram_used Total GPU RAM usage on a ray node
# TYPE ray_node_gram_used gauge
ray_node_gram_used{GpuIndex="0",ip="10.0.0.1"} 1234.0
# HELP ray_node_gram_available Total GPU RAM available on a ray node
# TYPE ray_node_gram_available gauge
ray_node_gram_available{GpuIndex="0",ip="10.0.0.1"} 80686.0
`
export, err := telemetry.ReadServingExposition(context.Background(), strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
for _, p := range export.Metrics {
fmt.Println(p.Semantic, p.RawValue, p.Unit)
}
}
Output: node_gpu_memory_used 1234.0 MiB node_gpu_memory_available 80686.0 MiB
Example (VllmV1) ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
// Constructed source-derived control, not a deployment capture.
raw := "# TYPE vllm:prompt_tokens_total counter\nvllm:prompt_tokens_total{model_name=\"m\",engine=\"0\"} 7\n"
source := telemetry.WorkloadSource{Provider: "vllm", Version: "0.8.5", Engine: "v1", RunID: "example"}
export, err := telemetry.ReadServingExposition(context.Background(), strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(export.Source.Engine, export.Metrics[0].Semantic, export.Metrics[0].Labels["engine"])
}
Output: v1 processed_prefill_tokens 0
func ReadWandBHistory ¶
func ReadWandBHistory(r io.Reader, s WorkloadSource, l WorkloadLimits) (WorkloadExport, error)
ReadWandBHistory reads W&B 0.19.11 wandb-history.jsonl scalar rows. Nested/media records remain in Raw and are not interpreted as scalar metrics. Reserved _timestamp (seconds) and _step fields retain their presence.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
source := telemetry.WorkloadSource{Provider: "wandb", Version: "0.19.11", RunID: "train1"}
export, err := telemetry.ReadWandBHistory(strings.NewReader("{\"loss\":0.5,\"_step\":0}\n"), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(export.Metrics[0].Unit, export.Metrics[0].HasTime)
}
Output: unknown false
func StampWorkloadSnapshot ¶
func StampWorkloadSnapshot(e WorkloadExport, nanos int64, domain, epoch string) (WorkloadExport, error)
StampWorkloadSnapshot adds an explicit collector observation timestamp to a snapshot whose producer samples have no timestamps. It returns a copy and refuses to replace any native timestamp. Raw bytes and hash remain unchanged. This establishes a scrape observation, never a sensor or request timestamp.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func main() {
source := telemetry.WorkloadSource{Provider: "triton", Version: "25.06", RunID: "serving1"}
raw := "# TYPE nv_inference_request_success counter\nnv_inference_request_success{model=\"example\",version=\"1\"} 1\n"
e, err := telemetry.ReadServingExposition(context.Background(), strings.NewReader(raw), source, telemetry.WorkloadLimits{})
if err != nil {
fmt.Println(err)
return
}
e, err = telemetry.StampWorkloadSnapshot(e, 0, "replay", "epoch1")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(e.Metrics[0].HasTime, e.Metrics[0].TimeNanos, e.Metrics[0].TimeSource, e.Metrics[0].RawTime == "")
}
Output: true 0 collector_observation true
type WorkloadHTTPResult ¶
type WorkloadHTTPResult struct {
Export WorkloadExport
Annotations []WorkloadAnnotation
}
WorkloadHTTPResult contains an unchanged response export and, for PyTorch, explicit CPU annotations. An HTTP observation does not establish sensor time.
func FetchClearMLScalarPages ¶
func FetchClearMLScalarPages(ctx context.Context, client *http.Client, request *http.Request, source WorkloadSource, limits WorkloadLimits, maxPages int) ([]WorkloadHTTPResult, error)
FetchClearMLScalarPages follows ClearML 1.18.0 API v2.9 events.get_task_events scroll pagination for one explicitly selected task. Pinned references: clearml/backend_api/services/v2_9/events.py lines 1809..1921 (request event_type string, batch_size, scroll_id), lines 1924..2008 (response events, total number/null, returned int, scroll_id string), and clearml/backend_api/session/callresult.py (envelope data, meta.result_code == 200).
Each original page and hash is retained. No task-wide completeness or stable server snapshot is inferred. maxPages must be 1..32. limits bound the aggregate raw bytes and metrics, not merely each page. All raw events (including filtered non-scalar events) count against the aggregate metric/event bound. On any refusal no partial history is returned. GetBody is used when available; otherwise the caller-owned Body is consumed. Custom body readers must honor cancellation; blocked reads cannot be interrupted. The POST request must target events.get_task_events with matching task in the JSON request body and an initial empty scroll_id. Only scroll_id is updated for subsequent pages, preserving all other request fields byte-for-byte.
Example ¶
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, `{
"data": {
"events": [
{"type":"training_stats_scalar","task":"demo-task","metric":"loss","variant":"train","value":0.42,"iter":1,"timestamp":1700000000}
],
"scroll_id": "",
"returned": 1,
"total": 1
},
"meta": {"result_code": 200}
}`)
}))
defer server.Close()
reqBody := []byte(`{"task":"demo-task","event_type":"training_stats_scalar","batch_size":100}`)
request, _ := http.NewRequestWithContext(context.Background(), http.MethodPost, server.URL+"/events.get_task_events", bytes.NewReader(reqBody))
source := WorkloadSource{Provider: "clearml", Version: "1.18.0/api-2.9", RunID: "demo-task"}
pages, err := FetchClearMLScalarPages(context.Background(), server.Client(), request, source, WorkloadLimits{}, 4)
if err != nil {
panic(err)
}
fmt.Println(len(pages), len(pages[0].Export.Metrics))
Output: 1 1
func FetchMLflowHistoryPages ¶
func FetchMLflowHistoryPages(ctx context.Context, client *http.Client, request *http.Request, source WorkloadSource, limits WorkloadLimits, maxPages int) ([]WorkloadHTTPResult, error)
FetchMLflowHistoryPages follows MLflow 2.22.0 get-history page tokens for one explicitly selected run and metric. Each original page and hash is retained. No run-wide completeness or stable server snapshot is inferred. maxPages must be 1..32. limits bound the aggregate raw bytes and metrics, not merely each page. On any refusal no partial history is returned. The GET request must contain matching run_id and a nonempty metric_key; only page_token is changed, on a cloned request at the same endpoint.
Example ¶
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"metrics":[{"key":"loss","value":0.5,"timestamp":1,"step":0}]}`)
}))
defer server.Close()
request, _ := http.NewRequest("GET", server.URL+"/api/2.0/mlflow/metrics/get-history?run_id=run&metric_key=loss", nil)
pages, err := FetchMLflowHistoryPages(context.Background(), server.Client(), request, WorkloadSource{Provider: "mlflow", Version: "2.22.0", RunID: "run"}, WorkloadLimits{}, 4)
fmt.Println(len(pages), err)
Output: 1 <nil>
func FetchWorkload ¶
func FetchWorkload(ctx context.Context, client *http.Client, request *http.Request, source WorkloadSource, limits WorkloadLimits) (WorkloadHTTPResult, error)
FetchWorkload reads one caller-selected API response or artifact download. The caller owns endpoint selection, request encoding, credentials and paging. The request must identify a pinned format supported by the corresponding reader; this function does not invent framework endpoints or fetch pages.
Redirects are refused. The client is copied and its timeout capped at 30 seconds. Response bytes use WorkloadLimits; request bodies must be bounded by the caller. Errors omit URLs, credentials, response bodies and transport text. A custom transport must honor request cancellation, as net/http transports do.
Example ¶
client := &http.Client{Transport: workloadRoundTrip(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"metrics":[{"key":"loss","value":0.5,"timestamp":1,"step":0}]}`))}, nil
})}
request, _ := http.NewRequest("GET", "https://example.invalid/api/2.0/mlflow/metrics/get-history", nil)
result, err := FetchWorkload(context.Background(), client, request, WorkloadSource{Provider: "mlflow", Version: "2.22.0", RunID: "run"}, WorkloadLimits{})
fmt.Println(len(result.Export.Metrics), err)
Output: 1 <nil>
type WorkloadLimits ¶
WorkloadLimits bounds offline export readers. Zero values select defaults: 4 MiB of input, 10000 observations and 4096 bytes per string.
type WorkloadMetric ¶
type WorkloadMetric struct {
Source WorkloadSource
Name string
Semantic string
Unit string
Kind string // gauge, counter, histogram_bucket, histogram_count, histogram_sum
Temporality string // instantaneous or cumulative
Labels map[string]string
RawValue string
RawTime string
RawTimeUnit string
TimeNanos int64
HasTime bool
TimeSource string // producer or collector_observation; never sensor
Step int64
HasStep bool
StepKind string // logged_metric_step, history_step or reported_iteration
}
WorkloadMetric preserves a producer metric's identity and numeric spelling. TimeNanos is meaningful only when HasTime is true. Clock metadata identifies an aggregate observation, not a request-to-kernel clock calibration.
type WorkloadOTLPOptions ¶
type WorkloadOTLPOptions struct {
StartNanos, EndNanos int64
ClockDomain, ClockEpochID string
HasUnixMapping bool
StartUnixNanos, EndUnixNanos int64
MappingProvenance string
Limits WorkloadLimits
}
WorkloadOTLPOptions binds an aggregate interval to a caller-proven Unix clock mapping. Equal native and Unix durations are required. MappingProvenance names an external calibration receipt; uncertainty and exact joins are not inferred.
type WorkloadRefresher ¶
type WorkloadRefresher struct {
// contains filtered or unexported fields
}
WorkloadRefresher periodically fetches one workload source and serves the last successful result while it is within MaxAge. A snapshot whose metrics carry no producer timestamps is stamped with the collector's observation time; producer timestamps are never replaced. It is exercised only against loopback fixtures; it does not qualify a live framework endpoint. The zero value is not usable; use NewWorkloadRefresher.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"net/http"
"net/http/httptest"
"time"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "# TYPE vllm:generation_tokens_total counter")
fmt.Fprintln(w, `vllm:generation_tokens_total{model_name="example"} 40`)
}))
defer srv.Close()
src := telemetry.WorkloadSource{Provider: "vllm", Version: "0.8.5", RunID: "run"}
fetch := func(ctx context.Context) (telemetry.WorkloadHTTPResult, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
if err != nil {
return telemetry.WorkloadHTTPResult{}, err
}
return telemetry.FetchWorkload(ctx, srv.Client(), req, src, telemetry.WorkloadLimits{})
}
clock := telemetry.NewFakeClock(0, 1_700_000_000_000_000_000)
r, err := telemetry.NewWorkloadRefresher(fetch, clock, "synthetic_unix_utc", "example-epoch",
telemetry.RefreshConfig{Interval: time.Second, Timeout: time.Second, MaxAge: 5 * time.Second})
if err != nil {
fmt.Println(err)
return
}
defer r.Close()
if err := r.Step(context.Background()); err != nil {
fmt.Println(err)
return
}
res, fresh := r.Latest(clock.NowMonotonic())
m := res.Export.Metrics[0]
fmt.Println(fresh, m.RawValue, m.TimeSource, m.TimeNanos)
clock.Advance(6 * time.Second)
_, fresh = r.Latest(clock.NowMonotonic())
fmt.Println(fresh)
}
Output: true 40 collector_observation 1700000000000000000 false
func NewWorkloadRefresher ¶
func NewWorkloadRefresher(fetch func(context.Context) (WorkloadHTTPResult, error), clock Clock, domain, epoch string, cfg RefreshConfig) (*WorkloadRefresher, error)
NewWorkloadRefresher returns a refresher that calls fetch, typically a closure over FetchWorkload, once per cycle. Untimed snapshots are stamped with clock.NowUnix in the named wall clock domain and epoch. Freshness uses the clock's monotonic time.
func (*WorkloadRefresher) Close ¶
func (w *WorkloadRefresher) Close() error
Close stops Run, cancels an in-flight fetch and refuses later cycles. Close is safe to call more than once.
func (*WorkloadRefresher) Latest ¶
func (w *WorkloadRefresher) Latest(now int64) (WorkloadHTTPResult, bool)
Latest returns a copy of the last successful result and whether it was obtained within MaxAge of now, a time on the refresher clock's monotonic scale. Before any success it returns the zero result and false.
func (*WorkloadRefresher) Ready ¶
func (w *WorkloadRefresher) Ready() bool
Ready reports whether a fetch has succeeded within MaxAge.
func (*WorkloadRefresher) Run ¶
func (w *WorkloadRefresher) Run(ctx context.Context) error
Run calls Step immediately and then every Interval until ctx is done or the refresher is closed. Step errors are reported by Status. Run returns ctx.Err() on cancellation and nil after Close.
func (*WorkloadRefresher) Status ¶
func (w *WorkloadRefresher) Status() RefreshStatus
Status returns a copy of the refresher's cycle accounting.
type WorkloadSource ¶
type WorkloadSource struct {
Provider string
Version string
// Engine selects an additional producer contract; empty preserves legacy.
Engine string `json:",omitempty"`
RunID string
Phase string
Rank *int
ClockDomain string
ClockEpochID string
// Units declares units for user-defined training metrics. Missing units
// remain unknown; a metric named "loss" does not prove convergence.
Units map[string]string
}
WorkloadSource identifies an offline producer export. RunID, Phase and Rank are caller-supplied export context, never inferred from hardware activity.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer writes streaming telemetry records to an io.Writer with budget enforcement.
func NewWriter ¶
func NewWriter(w io.Writer, cfg CollectorConfig) *Writer
NewWriter creates a telemetry stream writer.
func (*Writer) BytesWritten ¶
BytesWritten returns total bytes successfully written to the stream.
func (*Writer) FamilyLoss ¶
func (w *Writer) FamilyLoss() map[string]tracecontract.Loss
FamilyLoss returns a copy of V3 attempted and dropped reading counts. A Counts use canonical readings, independently of producer receipt units. A missing family is unassessed, not measured zero loss. Overflow saturates the affected count and marks it unknown.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"io"
)
func main() {
w := telemetry.NewWriter(io.Discard, telemetry.CollectorConfig{})
_, ok := w.FamilyLoss()["activity"]
fmt.Println(ok)
}
Output: false
func (*Writer) LostRecords ¶
LostRecords returns the count of records dropped due to budget exhaustion.
func (*Writer) RecordDrop ¶
RecordDrop increments the dropped record counter.
func (*Writer) WriteManifest ¶
WriteManifest writes the manifest header to the stream.
func (*Writer) WritePhase ¶
func (w *Writer) WritePhase(p *PhaseMarker) error
WritePhase writes a phase transition marker to the stream.
func (*Writer) WriteSample ¶
WriteSample writes a sample line to the stream.
type XIDLogFormat ¶
type XIDLogFormat uint8
Format selects supplied line input or a one-record-per-Read kmsg reader.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
fmt.Println(telemetry.Text != telemetry.KernelRecords)
}
Output: true
const ( Text XIDLogFormat = iota + 1 KernelRecords )
type XIDLogOptions ¶
type XIDLogOptions struct {
Source XIDLogSource
Product Architecture
Driver string
MaxRecordBytes, MaxBytes, MaxRecords int
}
Options supplies provenance and product-specific catalog interpretation. Driver is retained verbatim; parsing does not infer a driver from log text. Zero bounds use finite defaults. Larger limits than the defaults are refused.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func inputs() telemetry.XIDLogOptions {
return telemetry.XIDLogOptions{Source: telemetry.XIDLogSource{BootID: "supplied-boot", InputID: "constructed example"}, Product: "L4", Driver: "580"}
}
func main() {
fmt.Println(inputs().Product)
}
Output: L4
type XIDLogReader ¶
type XIDLogReader struct {
// contains filtered or unexported fields
}
Reader parses bounded caller-owned input. It is not safe for concurrent Next calls. EOF means this supplied input ended, not that a boot is complete.
func NewReader ¶
func NewReader(input io.Reader, format XIDLogFormat, o XIDLogOptions) (*XIDLogReader, error)
NewReader validates provenance, limits and input framing. It never opens files.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func inputs() telemetry.XIDLogOptions {
return telemetry.XIDLogOptions{Source: telemetry.XIDLogSource{BootID: "supplied-boot", InputID: "constructed example"}, Product: "L4", Driver: "580"}
}
func main() {
r, _ := telemetry.NewReader(strings.NewReader("unrelated\n"), telemetry.Text, inputs())
v, _ := r.Next()
fmt.Println(v.Kind)
}
Output: other
func (*XIDLogReader) Next ¶
func (r *XIDLogReader) Next() (Record, error)
Next returns facts and explicit malformed/fragment/gap records. Limits stop reading with an error. Kernel EPIPE produces Gap and permits subsequent reads; other I/O errors are returned unchanged. No lost count is inferred.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func inputs() telemetry.XIDLogOptions {
return telemetry.XIDLogOptions{Source: telemetry.XIDLogSource{BootID: "supplied-boot", InputID: "constructed example"}, Product: "L4", Driver: "580"}
}
func main() {
r, _ := telemetry.NewReader(strings.NewReader("truncated"), telemetry.Text, inputs())
v, _ := r.Next()
fmt.Println(v.Kind, v.Partial)
}
Output: malformed true
type XIDLogSource ¶
Source is caller-supplied provenance. PreviousBoot labels the supplied input; it does not prove completeness or that events belong to the claimed boot.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
s := telemetry.XIDLogSource{BootID: "previous", InputID: "caller supplied text", PreviousBoot: true}
fmt.Println(s.PreviousBoot)
}
Output: true
type XIDNotification ¶
type XIDNotification struct {
Kind Kind
Source XIDLogSource
Product Architecture
Driver string
PCI, DeviceUUID string
DeviceIdentityKnown bool
Code uint64
HasKernelTimestamp bool
KernelMonotonicMicroseconds uint64
KernelSequence uint64
Catalog Entry
Applicability Applicability
}
XIDNotification is a supplied kernel fact, not a fault diagnosis or action. DeviceUUID is known only through the caller's explicit PCI identity mapping. Kernel timestamps retain microseconds in the supplied boot's monotonic domain; they are neither sensor timestamps nor collector wall timestamps. Raw lines, process names, and driver error text are not retained.
type XIDNotifications ¶
type XIDNotifications struct {
Records []XIDNotification
InputEnded bool
LossUnknown bool
}
XIDNotifications is a bounded supplied-input result. InputEnded means EOF, never complete boot coverage. LossUnknown is always true: supplied log input cannot prove records were not lost before collection or filtering.
func ReadXIDNotifications ¶
func ReadXIDNotifications(input io.Reader, format XIDLogFormat, options XIDLogOptions, pciIdentities map[string]string) (XIDNotifications, error)
ReadXIDNotifications reads caller-owned text or record-framed kmsg input. PCI identities are explicit caller assertions, never inferred from proximity. Duplicate/reversed kmsg sequence numbers and reversed timestamps are refused. Fragments, malformed records and gaps retain their class without exposing their raw payload.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
"strings"
)
func xidOptions() telemetry.XIDLogOptions {
return telemetry.XIDLogOptions{Source: telemetry.XIDLogSource{BootID: "boot", InputID: "supplied"}, Product: telemetry.H100, Driver: "580"}
}
func main() {
result, err := telemetry.ReadXIDNotifications(strings.NewReader("NVRM: Xid (PCI:0000:65:00): 79, constructed\n"), telemetry.Text, xidOptions(), nil)
fmt.Println(result.Records[0].Code, result.Records[0].DeviceIdentityKnown, result.LossUnknown, err)
}
Output: 79 false true <nil>
Source Files
¶
- accounting.go
- accounting_scope.go
- armcheck.go
- attribution_refresh.go
- benchmark.go
- bridge_bridge.go
- bridge_layout.go
- catalog.gen.go
- clock.go
- collector.go
- collector_daemon.go
- dcgm.go
- dcgm_notifications.go
- dcgm_oracle.go
- dcgm_read.go
- dcgm_v3_adapter.go
- dd_mapping.go
- decode.gen.go
- delivery.go
- doc.go
- durable_delivery.go
- durable_delivery_flock_unix.go
- endpoint_http.go
- entity.go
- entity_cache.go
- entity_cache_file.go
- entity_export.go
- entity_nvml.go
- entity_proc.go
- export.go
- export_entity.go
- fake_sampler.go
- fitness.go
- governance.go
- gpm_sampler.go
- gpuhealth_devnum_unix.go
- gpuhealth_gpuhealth.go
- health.go
- health_fabric.go
- health_nvlink.go
- health_nvlink_counters.go
- health_nvml.go
- histogram_window.go
- http.go
- ib_netlink_linux.go
- ib_sampler.go
- job_attribution.go
- k8s_cgroup.go
- k8s_podresources.go
- k8s_pods.go
- log_event.go
- managed.go
- managed_http.go
- managed_parser.go
- metric_unit.go
- monitor.go
- ncu_import.go
- ncu_raw.go
- node_health.go
- nsys_gaps.go
- nsys_import.go
- nsys_json.go
- nsys_schema.go
- nvlink_fields.go
- nvml_sampler.go
- otlp_histogram.go
- otlp_proto.go
- proc_environ.go
- process_source.go
- reading_copy.go
- registry.go
- replay.go
- retention.go
- runtime_load.go
- smi_exec.go
- smi_nvidiasmi.go
- smi_query.go
- smi_reset.go
- smi_topo.go
- smi_value.go
- stepgroups.go
- stream.go
- throttle.go
- trigger.go
- types.go
- window.go
- workload_checkpoint.go
- workload_clearml_http.go
- workload_context.go
- workload_dynamo.go
- workload_export.go
- workload_http.go
- workload_metrics.go
- workload_movement.go
- workload_nixl.go
- workload_operator.go
- workload_operator_cpu.go
- workload_pages.go
- workload_prometheus.go
- workload_pytorch.go
- workload_refresh.go
- workload_serving_context.go
- workload_sglang.go
- workload_training.go
- workload_training_context.go
- workload_training_export.go
- workload_vllm_v1.go
- xid_notifications.go
- xidcatalog_catalog.go
- xidcatalog_decode.go
- xidcatalog_product.go
- xidcatalog_recovery.go
- xidlog_parse.go
- xidlog_reader.go