diag

package
v0.1.0 Latest Latest
Warning

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

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

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

README

Isolated launch reproducers

Generate optional capture methods alongside ordinary typed launches:

go run github.com/tmc/lib/nvidia/x/cmd/cudabind -type Module -repro kernel.cu

CaptureWriteAt(stream, grid, block, limit, out, alias, index, value) has the same kernel arguments as WriteAt, plus a maximum number of allocation bytes to retain. It synchronizes the stream and returns a *cudarepro.Launch without launching the kernel. Explicitly save that record with record.Write(file) before submitting suspect work. Capture is intended for a quiescent diagnostic run: callers keep allocations alive and exclude writes from other streams.

The record contains the native CUBIN and digest, argument names and C types, captured ABI widths, original addresses, full backing allocation contents, launch geometry, stream handle and Go call site. Generated captures also retain the embedded source files. Their target names the capture device; source files are the generator inputs, excluding its appended ABI assertions. Compiler options are optional provenance, not reconstructed from the native image. Replay loads the retained CUBIN; it does not recompile those source files.

Full allocations are captured once even when several arguments alias them. Replay allocates them again and relocates each argument by its original offset. The allocation-byte limit counts complete backing allocations, not only slice lengths. A capture includes application data; save it only where that data may be stored. Use records from trusted producers: replay executes their GPU code, and the schema is producer metadata rather than an authenticated ABI proof.

Build the runner, then execute a saved capture in a fresh process:

go build -o "$HOME/tmp/cudarepro" github.com/tmc/lib/nvidia/x/cmd/cudarepro
compute-sanitizer --tool memcheck --error-exitcode 66 \
  "$HOME/tmp/cudarepro" -record "$HOME/tmp/replay.json" capture.json

The required -record writes relocated addresses before submission, so a fault cannot prevent attribution metadata from being saved. Files must not already exist. -output optionally writes output buffer bytes as JSON. Replay checks argument count against the captured ABI and each argument width against the loaded function before driver submission.

For a saved sanitizer log, print findings and candidate arguments without a GPU:

"$HOME/tmp/cudarepro" -attribute sanitizer.log "$HOME/tmp/replay.json"

Or parse the sanitizer output with cudasanitizer.ParseLog, then pass findings and the relocated record to cudarepro.Attribute. Results are candidates: aliased arguments, address reuse, or several possible launches remain ambiguous. The join uses contained addresses or the sanitizer's explicitly identified nearest allocation, never symbol-name similarity. Unsupported report formats retain text and produce no attribution. Restrict records to the failing process and execution interval using independent evidence.

This first implementation supports ordinary native JIT-loaded cudabind modules with scalar values and direct allocation pointers. Capture from precompiled loaders, graph capture, mutable module globals, pointers inside records or allocation contents, texture/surface objects and concurrent execution are unsupported. It does not reproduce races or a whole stream dependency graph. Capture synchronizes its stream; replay runs that isolated saved state in a new stream. The CUBIN requires compatible hardware, and scalar bytes require the same host ABI.

Qualification

The maintained opt-in hardware test builds a generated binding fixture, captures an out-of-bounds write, and replays it under real memcheck in a fresh process. It attributes the fault to the named out argument, checks alias relocation, then captures a corrected index and verifies both clean memcheck and output bytes. CPU tests cover unknown report formats, aliases, reused addresses, invalid capture metadata, byte limits and generated-name collisions.

Run from the NVIDIA module under the shared GPU serializer:

GPU_LANE=cudarepro "$HOME/ml-explore/bin/gpu-slot" -- \
  env GOWORK=off CUDABIND_REPRO_TEST=1 \
  go test -count=1 -v -run '^TestReproducer$' ./x/cmd/cudabind

The fixture is x/cmd/cudabind/testdata/repro; regeneration requires compatible libclang CUDA headers. Its normal test path explicitly skips hardware work unless requested. This qualification establishes the isolated native path, not full sanitizer coverage of an application's asynchronous execution.

Documentation

Overview

Package diag provides GPU roofline models, kernel census, evidence records, microbenchmark probes, reproducer reduction, sanitizer runners, quarantined candidate launches, and workload diagnostics.

Quarantine runs one ReproLaunch in a child process with its own CUDA context, so a kernel that hangs, faults or writes out of bounds is reported in a QuarantineVerdict and never touches the caller's context.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Example (Diag)
package main

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

func main() {
	// Build a deterministic synthetic host delay fixture
	fixture := diag.BuildSyntheticFixture(diag.InjectionHostDelay)

	// Diagnose without providing the injection label to the engine
	result := diag.Diagnose(fixture.Workload, fixture.OpID, fixture.Input)

	fmt.Printf("Admitted: %t\n", result.Admitted)
	fmt.Printf("Mechanism: %s\n", result.Mechanism)
	fmt.Printf("Primary Finding Rule: %s\n", result.PrimaryFinding.Rule)
	fmt.Printf("Primary Finding Class: %s\n", result.PrimaryFinding.Class)

}
Output:
Admitted: true
Mechanism: host_submission_delay
Primary Finding Rule: host_submission_delay
Primary Finding Class: observed
Example (Diagdemo)
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	cfg := diag.DemonstrationConfig{
		NumRequests:       4,
		Concurrency:       2,
		HostDelay:         5 * time.Millisecond,
		DeviceDelay:       200 * time.Microsecond,
		SkipIntervention:  true,
		ExerciseCorruptEv: false,
	}

	result, err := diag.RunDemonstration(ctx, cfg)
	if err != nil {
		fmt.Printf("demonstration error: %v\n", err)
		return
	}

	fmt.Println("Synthetic:", result.Synthetic)
	fmt.Println("Separate pre-entry metric:", result.HostDelayDiagnosis.TimeAccounting.PreEntryDuration != nil)
	fmt.Println("Scheduler capture:", result.DiagnosticInputs["host"].Sched.ProbePresent)

}
Output:
Synthetic: true
Separate pre-entry metric: true
Scheduler capture: false
Example (Diageval)
package main

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

func main() {
	proto := diag.DefaultProtocol(diag.PhasePilot)
	cfg := diag.DefaultEvalConfig()
	cfg.ExerciseStress = false

	report, err := diag.RunEvaluation(context.Background(), proto, cfg)
	if err != nil {
		fmt.Printf("evaluation error: %v\n", err)
		return
	}

	fmt.Printf("Passed: %t\n", report.Passed)
	fmt.Printf("Exact joins: %d\n", report.Attribution.ExactJoins)
	fmt.Printf("Incorrect joins: %d\n", report.Attribution.IncorrectJoins)
}
Output:
Passed: false
Exact joins: 20
Incorrect joins: 0
Example (Regress)
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/tmc/lib/nvidia/x/host/timing"
	"github.com/tmc/lib/nvidia/x/obs/cudaprof/tracecontract"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	ctx := context.Background()

	// 1. Ingest an admitted incident from cudadiag / tracecontract.
	incident := diag.Incident{
		ID:       "inc-gemm-slowdown-101",
		Admitted: true,
		Workload: diag.WorkloadIdentity{
			WorkloadName: "llm_prefill_gemm",
			RunID:        "run-42",
		},
		Diagnosis: diag.DiagnosisResult{
			Admitted:  true,
			Mechanism: diag.MechanismDeviceBottleneck,
		},
		PrimaryFinding: tracecontract.Finding{
			ID:    "finding-dev-bottleneck",
			Class: tracecontract.FindingObserved,
			Admission: tracecontract.Admission{
				Admitted: true,
				Status:   "admitted",
			},
		},
		ObservedEnvironment: diag.Environment{
			DeviceIndex:       0,
			Model:             "NVIDIA GB10",
			ComputeCapability: "sm_121a",
			Driver:            "550.54.14",
			CUDA:              "12.8",
		},
		CreatedAt: time.Now(),
	}

	// 2. Generate a bounded, replayable ExperimentPlan.
	plan, planRec, err := diag.NewPlanFromIncident(incident, diag.PlanOptions{
		Oracle:     diag.CorrectnessOracle{Method: "numerical-tolerance"},
		WarmupRuns: 1,
		Rounds:     3,
		ExecutionScope: diag.TimingScope{
			Channel: timing.TimingSummedKernel,
		},
		StoppingRules: diag.RegressStoppingRules{
			RelativeThreshold: 0.10, // 10% regression threshold
			MinSamples:        3,
		},
	})
	if err != nil {
		fmt.Printf("plan generation failed: %v\n", err)
		return
	}

	fmt.Printf("Plan created: %s (closure valid: %t)\n", plan.IncidentID, planRec.ArtifactClosureValid)

	// 3. Replay with runner executing baseline and candidate arms.
	runner := diag.ReplayFunc(func(ctx context.Context, armName string, round int) (timing.Receipt, []float64, error) {
		dur := 100 * time.Microsecond
		if armName == "candidate" {
			dur = 125 * time.Microsecond // 25% regression
		}
		r := timing.Receipt{
			Name:         armName,
			Round:        round,
			Complete:     true,
			Digest:       "digest-ok",
			SummedKernel: dur,
			DeviceNs:     dur.Nanoseconds(),
			TimingKind:   timing.TimingSummedKernel,
		}
		_ = r.RecordTiming(timing.TimingSummedKernel, dur)
		return r, []float64{1.0, 2.0}, nil
	})

	execRec, compRec, err := diag.Replay(ctx, plan, runner, diag.ReplayOptions{
		CurrentEnvironment: incident.ObservedEnvironment,
		ReferenceValues:    []float64{1, 2},
	})
	if err != nil {
		fmt.Printf("replay failed: %v\n", err)
		return
	}

	fmt.Printf("Rounds completed: %d\n", execRec.RoundsCompleted)
	fmt.Printf("Verdict: %s (regression detected: %t)\n", compRec.Verdict, compRec.RegressionDetected)

}
Output:
Plan created: inc-gemm-slowdown-101 (closure valid: true)
Rounds completed: 3
Verdict: fail (regression detected: true)

Index

Examples

Constants

View Source
const (
	FamilyExperts   = "experts"
	FamilyDenseQ8   = "dense_q8"
	FamilyF16       = "F16"
	FamilyAttention = "attention"
	FamilyNormPrep  = "norm_prep"
	FamilyModelPrep = "model_prep"
	FamilyResidual  = "residual"
)

Architectural families defined for differential profiling.

View Source
const (
	RuleMovementBytes      = "movement_bytes"
	RuleMovementDirection  = "movement_direction"
	RuleMovementCompletion = "movement_completion"
	RuleMovementDuration   = "movement_duration"
	RuleMovementPath       = "movement_path"
	RuleMovementActivity   = "movement_activity_link"
	RuleMovementAttempt    = "movement_attempt_link"
	RuleMovementCongestion = "movement_congestion"
)

Movement claim rules.

View Source
const (
	// QuarantinePass means the launch finished within its deadline, wrote
	// every output element, left every other byte and both guard bands of
	// every allocation unchanged, and matched the reference bit for bit.
	QuarantinePass = "pass"

	// QuarantineDeadline means the launch did not finish within
	// [QuarantineSpec.Deadline]: the child gave up waiting, or the parent
	// killed it. The name matches the cause
	// [github.com/tmc/lib/nvidia/x/tile/mega.AbortDeadline], but the
	// mechanism here is the host's: an arbitrary kernel has no abort word.
	QuarantineDeadline = "deadline"

	// QuarantineFault means the launch returned a device error, or the
	// child died or exited without a valid report and output bytes.
	QuarantineFault = "fault"

	// QuarantineOutOfBounds means a byte outside every declared output
	// changed: the kernel wrote to an input, to slack in an allocation, or
	// to the guard band before or after one.
	QuarantineOutOfBounds = "out-of-bounds"

	// QuarantineUnwritten means an output element still held the fill.
	QuarantineUnwritten = "unwritten"

	// QuarantineMismatch means an output element differed from the reference.
	QuarantineMismatch = "mismatch"

	// QuarantineSanitizer means a compute-sanitizer run reported errors.
	QuarantineSanitizer = "sanitizer"

	// QuarantineNoLease means the child did not inherit a gpu-lock lease
	// and so did not touch the GPU.
	QuarantineNoLease = "no-lease"
)

Quarantine verdicts. The empty verdict is not a pass.

View Source
const (
	// StatusHardwareUnspecified is the zero value.
	StatusHardwareUnspecified = timing.StatusHardwareUnspecified

	// StatusPendingHardware indicates that no physical GPU device is present,
	// qualified or locked for hardware coverage capture. Generating mock or
	// synthetic coverage bytes is strictly forbidden.
	StatusPendingHardware = timing.StatusPendingHardware

	// StatusHardwareAvailable indicates that physical GPU hardware is present
	// and verified.
	StatusHardwareAvailable = timing.StatusHardwareAvailable
)
View Source
const (
	// ChildFlagName is the flag [Main] prepends to the child test binary's
	// arguments to mark it as the process running under compute-sanitizer.
	// The flag marks the child, but it does not by itself identify one:
	// arguments do leak, through `go test -args`, wrapper scripts and copied
	// command lines. [Child] requires [ActiveEnv] as well, so that a stray
	// flag cannot make a parent skip instrumentation and report success.
	ChildFlagName = "cudasanitizer.child"

	// ActiveEnv is set to "1" in the child's environment. [Main] refuses to
	// launch compute-sanitizer when it is already set, which stops a parent
	// that somehow lost the child flag from re-executing itself forever.
	// Descendant processes can also read it to tell that they are running
	// under the sanitizer.
	ActiveEnv = "CUDASANITIZER_ACTIVE"
)
View Source
const AnyTensorActive = re_obsmodel.AnyTensorActive
View Source
const BF16Tensor = re_obsmodel.BF16Tensor
View Source
const BandwidthRecordEnv = re_obsmodel.BandwidthRecordEnv
View Source
const BandwidthRecordVersion = re_obsmodel.BandwidthRecordVersion
View Source
const ClassAboveCeiling = re_obsmodel.ClassAboveCeiling
View Source
const ClassComputeBound = re_obsmodel.ClassComputeBound
View Source
const ClassMemoryBound = re_obsmodel.ClassMemoryBound
View Source
const ClassUnconstrained = re_obsmodel.ClassUnconstrained
View Source
const Complete = re_obsmodel.Complete
View Source
const ComputeLimited = re_obsmodel.ComputeLimited
View Source
const ConfidenceCounterRatio = re_obsmodel.ConfidenceCounterRatio
View Source
const ConfidenceIdle = re_obsmodel.ConfidenceIdle
View Source
const ConfidenceStaticMix = re_obsmodel.ConfidenceStaticMix
View Source
const ConfidenceUnavailable = re_obsmodel.ConfidenceUnavailable
View Source
const ContentionCPUThresholdPct = systeminfo.ContentionCPUThresholdPct

ContentionCPUThresholdPct is the single-process CPU utilization threshold (>= 50%) that flags host CPU contention on unified-memory architectures (such as GB10 and GH200) where host CPU bandwidth contends with GPU memory.

View Source
const DFMATensorActive = re_obsmodel.DFMATensorActive
View Source
const DMMATensorActive = re_obsmodel.DMMATensorActive
View Source
const DRAMBandwidthUtil = re_obsmodel.DRAMBandwidthUtil
View Source
const DefaultErrorExitCode = 66

DefaultErrorExitCode is the value passed as --error-exitcode when Config.ErrorExitCode is zero.

compute-sanitizer defaults --error-exitcode to 0, which makes a run with detected errors indistinguishable from a clean run by exit status alone. This package never uses that default. The value is deliberately far from the codes a Go test binary produces (0 pass, 1 fail, 2 flag or panic exit) so that a collision with the application's own status is unlikely; [Run] reports the remaining collision explicitly through Result.ExitCodeCollision.

View Source
const DefaultKillDelay = 5 * time.Second

DefaultKillDelay bounds waiting for inherited output pipes to close after the process exits, used when Config.KillDelay is zero.

View Source
const DefaultMaxOutputBytes = 1 << 20

DefaultMaxOutputBytes bounds how much of the application's stdout and stderr each Result retains when Config.MaxOutputBytes is zero.

View Source
const DefaultMinWorkingSetBytes = re_obsmodel.DefaultMinWorkingSetBytes
View Source
const DefaultReproducerPTX = ".version 8.0\n.target sm_80\n.address_size 64\n.visible .entry fixture() { ret; }\n"

DefaultReproducerPTX is a pristine, syntactically valid baseline PTX kernel fixture.

View Source
const DefaultToolName = "compute-sanitizer"

DefaultToolName is the name of the compute-sanitizer executable sought when Config.Path is empty, in the toolkit installs ToolSearchPaths names and then on PATH.

View Source
const Derived = re_obsmodel.Derived
View Source
const DeviceResident = re_obsmodel.DeviceResident
View Source
const DeviceWide = re_obsmodel.DeviceWide
View Source
const Errored = re_obsmodel.Errored
View Source
const EvidenceMeasured = re_obsmodel.EvidenceMeasured
View Source
const FP16Active = re_obsmodel.FP16Active
View Source
const FP16Tensor = re_obsmodel.FP16Tensor
View Source
const FP32Active = re_obsmodel.FP32Active
View Source
const FP64Active = re_obsmodel.FP64Active
View Source
const FP8Tensor = re_obsmodel.FP8Tensor
View Source
const Failed = re_obsmodel.Failed
View Source
const FloorAbsent = re_obsmodel.FloorAbsent
View Source
const FloorFromBothAxes = re_obsmodel.FloorFromBothAxes
View Source
const FloorFromComputeOnly = re_obsmodel.FloorFromComputeOnly
View Source
const FloorFromMemoryOnly = re_obsmodel.FloorFromMemoryOnly
View Source
const FloorUnavailable = re_obsmodel.FloorUnavailable
View Source
const FromCounterRatio = re_obsmodel.FromCounterRatio
View Source
const FromInstructionMix = re_obsmodel.FromInstructionMix
View Source
const GoldenVectorPath = re_obsmodel.GoldenVectorPath
View Source
const GraphicsActive = re_obsmodel.GraphicsActive
View Source
const HMMATensorActive = re_obsmodel.HMMATensorActive
View Source
const HostMeasuredCeiling = re_obsmodel.HostMeasuredCeiling
View Source
const HostPageTableResident = re_obsmodel.HostPageTableResident
View Source
const IMMATensorActive = re_obsmodel.IMMATensorActive
View Source
const INT8Tensor = re_obsmodel.INT8Tensor
View Source
const Incomplete = re_obsmodel.Incomplete
View Source
const Inferred = re_obsmodel.Inferred
View Source
const IntActive = re_obsmodel.IntActive
View Source
const Measured = re_obsmodel.Measured
View Source
const MemoryLimited = re_obsmodel.MemoryLimited
View Source
const MinRuns = re_obsmodel.MinRuns
View Source
const Modeled = re_obsmodel.Modeled
View Source
const NoLimit = re_obsmodel.NoLimit
View Source
const NominalCeiling = re_obsmodel.NominalCeiling
View Source
const OutcomeAmbiguous = re_obsworkload.OutcomeAmbiguous
View Source
const OutcomeAssociated = re_obsworkload.OutcomeAssociated
View Source
const OutcomeExact = re_obsworkload.OutcomeExact
View Source
const OutcomeMissing = re_obsworkload.OutcomeMissing
View Source
const Passed = re_obsmodel.Passed
View Source
const PerSM = re_obsmodel.PerSM
View Source
const PerWarp = re_obsmodel.PerWarp
View Source
const ProvenanceCUPTI = re_obsworkload.ProvenanceCUPTI
View Source
const ProvenanceGraphNode = re_obsworkload.ProvenanceGraphNode
View Source
const ProvenanceRuntimeAPI = re_obsworkload.ProvenanceRuntimeAPI
View Source
const ProvenanceSynthetic = re_obsworkload.ProvenanceSynthetic
View Source
const ProvenanceUninstrumented = re_obsworkload.ProvenanceUninstrumented
View Source
const ProvenanceUprobe = re_obsworkload.ProvenanceUprobe
View Source
const QuarantineGuard = 4096

QuarantineGuard is the size of the guard band the child allocates before and after every allocation.

View Source
const ReasonConflictingExternalID = re_obsworkload.ReasonConflictingExternalID
View Source
const ReasonConflictingOperations = re_obsworkload.ReasonConflictingOperations
View Source
const ReasonExpiredFIFO = re_obsworkload.ReasonExpiredFIFO
View Source
const ReasonExplicitExternalMatch = re_obsworkload.ReasonExplicitExternalMatch
View Source
const ReasonExplicitNativeMatch = re_obsworkload.ReasonExplicitNativeMatch
View Source
const ReasonGraphReplayMatch = re_obsworkload.ReasonGraphReplayMatch
View Source
const ReasonLateAttach = re_obsworkload.ReasonLateAttach
View Source
const ReasonNoDeviceActivity = re_obsworkload.ReasonNoDeviceActivity
View Source
const ReasonNoHostSubmission = re_obsworkload.ReasonNoHostSubmission
View Source
const ReasonProcessGenMismatch = re_obsworkload.ReasonProcessGenMismatch
View Source
const ReasonStreamContextMatch = re_obsworkload.ReasonStreamContextMatch
View Source
const ReasonUnannotatedActivity = re_obsworkload.ReasonUnannotatedActivity
View Source
const RecordVersion = re_obsmodel.RecordVersion
View Source
const SMActive = re_obsmodel.SMActive
View Source
const SMOccupancy = re_obsmodel.SMOccupancy
View Source
const StatusMeasured = re_obsmodel.StatusMeasured
View Source
const StatusUnmeasured = re_obsmodel.StatusUnmeasured
View Source
const TF32Tensor = re_obsmodel.TF32Tensor
View Source
const Unattributed = re_obsmodel.Unattributed
View Source
const UnknownResidency = re_obsmodel.UnknownResidency
View Source
const Unmeasured int64 = -1

Unmeasured indicates an unmeasured or unavailable timing dimension. It is returned instead of zero or host wall-clock time.Since fallbacks.

View Source
const Unqualified = re_obsmodel.Unqualified
View Source
const Unread = re_obsmodel.Unread
View Source
const Unverified = re_obsmodel.Unverified
View Source
const VerdictAccepted = re_obsmodel.VerdictAccepted
View Source
const VerdictRejected = re_obsmodel.VerdictRejected
View Source
const VerdictUnjudged = re_obsmodel.VerdictUnjudged
View Source
const VerificationPending = re_obsmodel.VerificationPending
View Source
const Version = 1

Variables

View Source
var (
	// ErrProtocolFrozen indicates an attempt to modify an already frozen protocol.
	ErrProtocolFrozen = errors.New("cudadiageval: protocol is frozen and cannot be modified")

	// ErrProtocolNotFrozen indicates qualification attempted on an unfrozen protocol.
	ErrProtocolNotFrozen = errors.New("cudadiageval: qualification requires a frozen protocol")

	// ErrInvalidProtocol indicates invalid or incomplete protocol parameters.
	ErrInvalidProtocol = errors.New("cudadiageval: invalid protocol specification")

	// ErrGateFailed indicates an evaluation acceptance gate failed.
	ErrGateFailed = errors.New("cudadiageval: acceptance gate failed")
)
View Source
var (
	ErrInvalidManifest       = errors.New("cudaflightrecorder: invalid reproducer manifest")
	ErrInvalidLaunchGeometry = errors.New("cudaflightrecorder: invalid launch geometry")
	ErrInvalidTensorShape    = errors.New("cudaflightrecorder: invalid tensor shape")
	ErrInvalidInputLengths   = errors.New("cudaflightrecorder: invalid input lengths")
	ErrUnsupportedIncident   = errors.New("cudaflightrecorder: unsupported incident type")
	ErrIncidentNotTriggered  = errors.New("cudaflightrecorder: incident not triggered")
)

Sentinel errors for reproducer bridge.

View Source
var (
	// ErrIncidentNotAdmitted indicates an incident lacks valid evidence admission.
	ErrIncidentNotAdmitted = fmt.Errorf("cudaregress: incident not admitted by evidence contract: %w", cuda.ErrUnsupported)

	// ErrArtifactMissing indicates a required source, binary, input, or reference artifact is not accessible.
	// This constitutes a reconstruction blocker.
	ErrArtifactMissing = errors.New("cudaregress: required artifact is missing on disk (reconstruction blocker)")

	// ErrArtifactCorrupted indicates an artifact's content hash does not match its declared digest.
	// This constitutes a reconstruction blocker.
	ErrArtifactCorrupted = errors.New("cudaregress: artifact content digest mismatch (reconstruction blocker)")

	// ErrEnvironmentDrift indicates execution environment differs from the declared plan.
	ErrEnvironmentDrift = errors.New("cudaregress: environment drift detected")

	// ErrUnsupportedTimingChannel indicates an unmeasured or unsupported timing channel was requested.
	ErrUnsupportedTimingChannel = fmt.Errorf("cudaregress: requested timing channel is unsupported: %w", cuda.ErrUnsupported)

	// ErrCorrectnessOracleFailed indicates candidate outputs failed the correctness oracle.
	ErrCorrectnessOracleFailed = errors.New("cudaregress: output correctness oracle evaluation failed")

	// ErrUnsafeCommandRefused indicates an arbitrary shell command or unverified executable was refused.
	ErrUnsafeCommandRefused = errors.New("cudaregress: execution of arbitrary shell command refused by policy")

	// ErrExecutionHalted indicates replay execution stopped due to failure or cancellation.
	ErrExecutionHalted = errors.New("cudaregress: replay execution halted")

	// ErrNoiseFloorExceeded indicates the null control baseline-vs-baseline drift exceeds allowable noise.
	ErrNoiseFloorExceeded = errors.New("cudaregress: null control noise floor exceeds threshold")
)
View Source
var (
	// ErrToolNotFound means the compute-sanitizer executable was not found.
	// [Config.MissingTool] decides whether that is a skip or a failure.
	ErrToolNotFound = errors.New("compute-sanitizer not found")

	// ErrTimeout means the run exceeded [Config.Timeout] or the caller's
	// context deadline. The runner kills its process group on Unix, its
	// process job on Windows, and the direct child on other platforms.
	ErrTimeout = errors.New("run timed out")

	// ErrUnsupportedOption means the resolved compute-sanitizer does not
	// accept an option the [Config] would emit, by name or by arity.
	// [Config.CheckOptions] reports it before a run starts, so the tool
	// never rejects the command line while writing no report.
	ErrUnsupportedOption = cudatool.ErrUnsupportedOption

	// ErrNoVerdict means no complete report was available: the tool emitted
	// no summary, or its fallback output was truncated. A run that ends
	// this way is classified as a tool failure no matter what the exit
	// status was, because no verdict was reached.
	ErrNoVerdict = errors.New("compute-sanitizer produced no complete report")
)

Sentinel errors reported through Result.Err for OutcomeToolFailure.

CanonicalFamilies lists the canonical families in standard display order.

View Source
var DefaultFamilyClassifier = NewFamilyClassifier(nil)

DefaultFamilyClassifier is a classifier using pure-Go normalization.

View Source
var ErrAboveCeiling = re_obsmodel.ErrAboveCeiling
View Source
var ErrCapacity = errors.New("cudashadow: policy capacity exhausted")

ErrCapacity indicates that policy state reached its configured bound.

View Source
var (
	// ErrIncompleteClaim indicates required claim fields are missing.
	ErrIncompleteClaim = errors.New("cudadiageval: claim missing required bounded fields")
)
View Source
var ErrIncompleteSystemInfo = systeminfo.ErrIncompleteSystemInfo

ErrIncompleteSystemInfo is returned when required hardware, clock, power, or CUDA library provenance fields are missing from a SystemInfo record.

View Source
var ErrIneligibleComparison = errors.New("cudacmp: ineligible comparison")
View Source
var ErrInvalidConfig = errors.New("invalid config")

ErrInvalidConfig is returned by [Run] for a Config that cannot be used.

View Source
var ErrMutationForbidden = errors.New("cudashadow: active backend mutation forbidden in shadow mode")

ErrMutationForbidden is returned if any code path mistakenly attempts an active backend mutation.

View Source
var ErrNaiveSumDoubleCounts = errors.New("cudacmp: naive sum of host, device, queue, and API durations causes double-counting")

ErrNaiveSumDoubleCounts indicates an attempt to naively sum non-additive timing channels.

View Source
var (
	// ErrRelatedBaseline indicates an attempt to count related projects as independent baselines.
	ErrRelatedBaseline = errors.New("cudadiageval: related engine cannot be classified as independent baseline")
)
View Source
var ErrWarmBufferReuse = re_obsmodel.ErrWarmBufferReuse

Functions

func AcceptRate

func AcceptRate(identity ReproIdentity, baseline, candidate Measurement, allowOneOff bool) (bool, error)

AcceptRate reports whether a candidate preserves the baseline empirical frequency. Both measurements must contain the same declared number of runs. An absent failure cannot establish a baseline. A one-off baseline requires allowOneOff. Counts are rechecked against retained execution evidence.

Example
i := ReproIdentity{Policy: "exact-uint64"}
m := Measurement{Reproductions: 2, Runs: []ptx.RunRecord{mismatchRecord(0), mismatchRecord(0)}}
accepted, err := AcceptRate(i, m, m, false)
fmt.Println(accepted, err)
Output:
true <nil>

func ActiveIntervalNs

func ActiveIntervalNs(p0 [][2]int64) int64

func ActiveNs

func ActiveNs(p0 []re_obsmodel.CensusLaunch) int64

func AllCounters

func AllCounters() []re_obsmodel.Counter

func AnalyticalDataMovement

func AnalyticalDataMovement(p0, p1, p2 map[string]int, p3 map[string]bool) (re_obsmodel.CompoundDataMovement, error)

func BandwidthRecordDir

func BandwidthRecordDir() (string, error)

func CheckCompatibility

func CheckCompatibility(baseline, candidate ComparisonIdentity) error

CheckCompatibility verifies that two comparison identities are compatible for comparative analysis.

func CheckDemoNumericalCorrectness

func CheckDemoNumericalCorrectness(reference, candidate []float64, tolerance float64) error

CheckNumericalCorrectness compares candidate outputs against reference outputs within a tolerance.

func CheckNumericalCorrectness

func CheckNumericalCorrectness(controlOut, interventionOut []float64, tolerance float64) error

CheckNumericalCorrectness compares test outputs against control reference outputs. It verifies that numerical correctness was preserved under the intervention.

func CheckQualificationLedgerSuccessor

func CheckQualificationLedgerSuccessor(prev, next QualificationLedger) error

CheckQualificationLedgerSuccessor reports whether next preserves the evidence history recorded in prev. Both ledgers must validate. Every cell in prev must remain in next, and its attempts must be an exact ordered prefix of the attempts in next.

References are a set: every earlier reference must appear, unchanged, in next, while order and duplicates are ignored. A reference recorded with an empty SHA256 (an unknown artifact) cannot gain a digest in place; a recovered artifact is added as a new reference beside it.

A cell with attempts may not change its closure, gate, capability ID, source paths, consumers or dependencies. Changed scope requires a new cell ID, which leaves earlier failures intact. Status, capability, owner and next action may change.

It compares declarations only. It does not read receipts; use VerifyQualificationLedger to check retained evidence.

Example
prev := pendingLedgerExample()
next := pendingLedgerExample()
next.Cells = append(next.Cells, next.Cells[0])
next.Cells[1].ID = "nvml-h100-native-v2"
fmt.Println(CheckQualificationLedgerSuccessor(prev, next))
fmt.Println(CheckQualificationLedgerSuccessor(next, prev))
Output:
<nil>
ledger successor: cell "nvml-h100-native-v2" removed

func CheckReconstruction

func CheckReconstruction(plan *ExperimentPlan, currentEnv Environment) (bool, []string)

CheckReconstruction evaluates whether an experiment plan can be reconstructed against the caller-supplied environment. It authenticates the plan and declared files with ValidatePlan, then checks ValidateEnvironment. It does not observe the environment, execute the plan, or authenticate claimed lineage.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"os"
	"path/filepath"
)

func exampleReconstructionPlan(dir string) (*diag.ExperimentPlan, error) {
	path := filepath.Join(dir, "supplied-source")
	if err := os.WriteFile(path, []byte("supplied source bytes, never compiled"), 0600); err != nil {
		return nil, err
	}
	digest, size, err := diag.ComputeFileDigest(path)
	if err != nil {
		return nil, err
	}
	plan, _, err := diag.NewPlanFromIncident(diag.Incident{
		ID: "supplied-incident", Admitted: true,
		ObservedEnvironment: diag.Environment{Model: "supplied-model"},
	}, diag.PlanOptions{
		Sources: []diag.ArtifactRef{{Name: "source", Path: path, Digest: digest, SizeBytes: size}},
	})
	return plan, err
}

func main() {
	dir, err := os.MkdirTemp("", "reconstruction-example-")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)
	plan, err := exampleReconstructionPlan(dir)
	if err != nil {
		fmt.Println(err)
		return
	}
	// This environment is supplied by the caller; the check does not observe it.
	ok, blockers := diag.CheckReconstruction(plan, diag.Environment{Model: "supplied-model"})
	fmt.Println(ok, len(blockers))
}
Output:
true 0

func CheckRegistrationSuccessor

func CheckRegistrationSuccessor(previous, next Registration) error

CheckRegistrationSuccessor requires immutable same-ID content or a new ID linked to the frozen predecessor. It never rewrites earlier receipt attempts.

Example
r, _ := exampleRegistration()
r, err := r.Freeze(time.Date(2026, 10, 11, 0, 0, 0, 0, time.UTC))
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(CheckRegistrationSuccessor(r, r))
Output:
<nil>

func CheckRegressNumericalCorrectness

func CheckRegressNumericalCorrectness(reference, candidate []float64, tolerance float64) error

CheckNumericalCorrectness compares candidate outputs against reference outputs under a tolerance bound.

func Child

func Child() bool

Child reports whether this process is the test binary that Main re-executed under compute-sanitizer.

Both the flag and ActiveEnv must be present. The flag alone is not trusted: it is an ordinary argument, so `go test -args -cudasanitizer.child` or a stale wrapper script puts it in a parent's os.Args, and a parent that believed it were the child would run the tests uninstrumented and exit 0 with nothing to show that no validation happened. Only Main sets ActiveEnv, and it sets it solely on the process it launches under the tool.

It inspects os.Args directly rather than the parsed flag value, because TestMain runs before the testing package parses flags.

func ClassifySymbol

func ClassifySymbol(p0 string, p1 []re_obsmodel.FamilyRule) string

func CmpUnionDuration

func CmpUnionDuration(intervals []Interval) (int64, error)

UnionDuration computes the total length of the union of half-open intervals [StartNs, EndNs). Overlapping intervals are merged so no time is double-counted. Returns an error if any interval has EndNs < StartNs, negative timestamps, or if duration overflows.

func ColdRingPlan

func ColdRingPlan(p0, p1 int64) (int, int64, error)

func CompareCounts

func CompareCounts(p0, p1 re_obsprobe.Count) (re_obsprobe.Comparison, error)

func ComputeExecutionSpecDigest

func ComputeExecutionSpecDigest(spec ExecutionSpec) (string, error)

ComputeExecutionSpecDigest returns the canonical spec digest. SpecDigest is ignored while hashing, so callers can set it to the returned value.

func ComputeFileDigest

func ComputeFileDigest(path string) (string, int64, error)

ComputeFileDigest returns the hex-encoded SHA-256 digest of the specified file.

func ComputeIntervalUnion

func ComputeIntervalUnion(intervals []tracecontract.Interval) []tracecontract.Interval

ComputeIntervalUnion takes a set of intervals and merges all overlapping or contiguous spans.

func ComputeNumericalOracle

func ComputeNumericalOracle(data []float64) ([]float64, string)

ComputeNumericalOracle evaluates an independent IEEE 754 reference transformation: y_i = 3.0 * x_i^2 - 2.0 * x_i + 1.0, returning the transformed vector and SHA256 digest.

func ComputePlanDigest

func ComputePlanDigest(plan *ExperimentPlan) (string, error)

ComputePlanDigest calculates a deterministic SHA-256 digest of the ExperimentPlan.

func ComputeReferenceOutput

func ComputeReferenceOutput(input []float64, weight, bias float64) []float64

ComputeReferenceOutput calculates the expected numerical transform $y_i = w \cdot x_i + b$.

func Coverage

func Coverage(p0 []re_obsmodel.Entry) (int64, int64)

func DecodeBandwidthRecord

func DecodeBandwidthRecord(p0 []byte) (re_obsmodel.BandwidthRecord, error)

func DecodeEvidence

func DecodeEvidence(p0 []byte) (obsevidence.EvidenceValue, error)

func DecodeRecord

func DecodeRecord(p0 io.Reader) (re_obsmodel.Record, error)

func DetectionAttempts

func DetectionAttempts(identity ReproIdentity, measured Measurement, repeats int, targetProbability float64, maxAttempts int) (int, error)

DetectionAttempts plans a finite export run under an explicit model: independent attempts, each reproducing with probability equal to the measured frequency (reproductions / repeats). An empirical frequency does not establish that model or provide a confidence bound. The caller must retain this assumption with the export.

Example
identity := ReproIdentity{Index: 0, Policy: "exact-uint64"}
run := mismatchRecord(0)
run.Mismatch = &ptx.MismatchIdentity{Index: 0, Policy: "exact-uint64"}
m := Measurement{Reproductions: 2, Runs: []ptx.RunRecord{run, run}}
attempts, err := DetectionAttempts(identity, m, 2, 0.99, 10)
fmt.Println(attempts, err)
Output:
1 <nil>

func DetectionProbability

func DetectionProbability(reproductions, repeats, attempts int) (float64, error)

DetectionProbability calculates the probability of observing at least one reproduction across attempts independent trials, where each trial reproduces with probability p = float64(reproductions) / float64(repeats).

The calculation assumes independent identically distributed (i.i.d.) attempts. An empirical frequency does not establish an i.i.d. model or provide a statistical confidence bound.

Example
p, err := DetectionProbability(1, 2, 3)
fmt.Println(p, err)
Output:
0.875 <nil>

func Devices

func Devices() []string

func EmitQualifyABFTCUDA

func EmitQualifyABFTCUDA(tau float32) string

EmitQualifyABFTCUDA returns CUDA C++ source for the ABFT checksum GEMM probe kernel and fault-ring writer using device tolerance tau.

func EmitQualifyDeterministicCUDA

func EmitQualifyDeterministicCUDA(rounds int, key [2]uint32) (string, error)

EmitQualifyDeterministicCUDA returns CUDA C++ source for the deterministic stochastic-rounding and fixed-tree GEMV qualification probes.

func EmitQualifyDeterministicStochasticRoundPTX

func EmitQualifyDeterministicStochasticRoundPTX(globalSeed uint64, rounds int, key [2]uint32, funcName string) (string, error)

EmitQualifyDeterministicStochasticRoundPTX emits PTX 8.7 source for sm_100a Philox4x32 stochastic rounding to packed e2m1x4.

func EmitQualifyPacedPrologueCUDA

func EmitQualifyPacedPrologueCUDA(rampBuckets int, bucketStepNs uint32) string

EmitQualifyPacedPrologueCUDA returns CUDA C++ source for the cluster-staggered nanosleep prologue and paced AXPY probe kernel.

func EvaluateHostCPUOutput

func EvaluateHostCPUOutput(psOutput, engineName string, selfPID int, unifiedMem bool) (topProcs []string, contended bool)

EvaluateHostCPUOutput parses `ps -eo pid,pcpu,comm` output, returning top non-engine processes (>= 10% CPU, up to 5) and whether host CPU contention (>= 50% CPU by a non-engine process on a unified-memory architecture) occurred.

func EvaluateIntervention

func EvaluateIntervention(
	plan InterventionPlan,
	control DiagnosisResult,
	controlOut []float64,
	intervention DiagnosisResult,
	interventionOut []float64,
) (tracecontract.InterventionReceipt, error)

EvaluateIntervention executes verification against the paired intervention plan. It checks one supplied pair and its numerical oracle. It does not execute trials or verify that the declared ordering and stopping protocol ran.

func EvaluatedCoverage

func EvaluatedCoverage(p0 *re_obsmodel.Model, p1 []re_obsmodel.Entry) (int64, int64)

func ExecuteReplay

func ExecuteReplay(
	ctx context.Context,
	plan *ExperimentPlan,
	runner ReplayRunner,
	opts ReplayOptions,
) (*ExecutionReceipt, *ComparisonReceipt, error)

ExecuteReplay coordinates interleaved trial execution across warmup, null controls, and ABBA rounds.

func ExportArtifacts

func ExportArtifacts(dir string, result *DemonstrationResult, reqs []Request, logs []GroundTruthLog, captureBytes []byte) (map[string]string, error)

ExportArtifacts writes the full demonstration artifact chain to the designated directory.

func ExportFiles

func ExportFiles(finding isa_ptx.SeedResult, reduction Reduction, opts ExportOptions) (map[string][]byte, error)

ExportFiles generates the file tree of a standalone reproducer package without writing to disk.

func ExportMinimalReproducer

func ExportMinimalReproducer(plan *ExperimentPlan, targetDir string) error

ExportMinimalReproducer exports a minimal, bounded reproducer bundle to targetDir. It serializes the plan, generates an artifact manifest with digests, and writes reproduction documentation without copying unbounded raw capture archives. It calls ValidatePlan before creating output files. The manifest records a verified artifact closure, but leaves reconstruction blocked until a caller supplies a separately observed environment to CheckReconstruction. No plan execution or environment observation is performed.

Example
package main

import (
	"encoding/json"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"os"
	"path/filepath"
)

func exampleReconstructionPlan(dir string) (*diag.ExperimentPlan, error) {
	path := filepath.Join(dir, "supplied-source")
	if err := os.WriteFile(path, []byte("supplied source bytes, never compiled"), 0600); err != nil {
		return nil, err
	}
	digest, size, err := diag.ComputeFileDigest(path)
	if err != nil {
		return nil, err
	}
	plan, _, err := diag.NewPlanFromIncident(diag.Incident{
		ID: "supplied-incident", Admitted: true,
		ObservedEnvironment: diag.Environment{Model: "supplied-model"},
	}, diag.PlanOptions{
		Sources: []diag.ArtifactRef{{Name: "source", Path: path, Digest: digest, SizeBytes: size}},
	})
	return plan, err
}

func main() {
	dir, err := os.MkdirTemp("", "reproducer-example-")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)
	plan, err := exampleReconstructionPlan(dir)
	if err != nil {
		fmt.Println(err)
		return
	}
	target := filepath.Join(dir, "export")
	if err := diag.ExportMinimalReproducer(plan, target); err != nil {
		fmt.Println(err)
		return
	}
	data, err := os.ReadFile(filepath.Join(target, "manifest.json"))
	if err != nil {
		fmt.Println(err)
		return
	}
	var manifest diag.Manifest
	if err := json.Unmarshal(data, &manifest); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("artifact closure:", manifest.ArtifactClosureValid)
	fmt.Println("host reconstruction:", manifest.Reconstructable)
}
Output:
artifact closure: true
host reconstruction: false

func ExportPackage

func ExportPackage(dir string, finding isa_ptx.SeedResult, reduction Reduction, opts ExportOptions) error

ExportPackage emits a standalone, runnable Go test package into a caller-named directory. The directory must be absolute, canonical, and not exist prior to export. TestReproduce refuses execution without a pinned caller-supplied runner. Each attempt starts a fresh process and retains bounded raw output in receipts. Candidate and oracle metadata from the runner remain assertions; they do not independently establish CUDA execution, custody, or native qualification. The emitted package contains:

  • go.mod: module file for the standalone test package;
  • testdata/source.ptx: original pristine kernel source;
  • testdata/candidate.ptx: replayed/injected artifact to execute;
  • testdata/finding.json: serialized campaign seed result;
  • testdata/case.json: reduced workload inputs, shape, and launch geometry;
  • testdata/policy.json: failure identity, measurement, and attempt policy;
  • testdata/digests.json: SHA-256 digests of all preserved artifacts;
  • reproducer_test.go: clean, runnable Go test verifying artifact integrity and reproducing the recorded defect with the required oracle and bounded attempts.
Example
err := ExportPackage("relative", ptx.SeedResult{}, Reduction{}, ExportOptions{})
fmt.Println(err)
Output:
export package: directory must be absolute and canonical

func ExtractPhaseLaunches

func ExtractPhaseLaunches(c *obsmodel.CensusCapture, phase CmpPhase) ([]obsmodel.CensusLaunch, error)

ExtractPhaseLaunches finds all kernel launches falling within the time window of the specified phase.

func ExtractPhaseSpans

func ExtractPhaseSpans(c *obsmodel.CensusCapture, phase CmpPhase) []obsmodel.Span

ExtractPhaseSpans returns all application spans in c associated with the given phase.

func FactsBandwidthRecords

func FactsBandwidthRecords(p0 devicetable.Facts) ([]re_obsmodel.BandwidthRecord, error)

func FinishCaptureSystemInfo

func FinishCaptureSystemInfo(ctx context.Context, info *SystemInfo, opts SystemInfoOptions)

FinishCaptureSystemInfo updates the end-of-run clocks, power, throttle bitmask, host load average, and host CPU contention fields on an existing SystemInfo record.

func FlightRingMinimalReproducerBundle

func FlightRingMinimalReproducerBundle(s *iket.FlightRingSnapshot, opts ReproducerBundleOptions) (*iket.Bundle, error)

FlightRingMinimalReproducerBundle creates a diagnostic Bundle from a decoded FlightRingSnapshot, embedding reproducer assets and optionally a GPUVis timeline JSON trace.

func FormulatePlan

func FormulatePlan(inc Incident, opts PlanOptions) (*ExperimentPlan, *PlanReceipt, error)

FormulatePlan derives an immutable, reproducible ExperimentPlan from an admitted incident.

func IsUnifiedMemoryGPU

func IsUnifiedMemoryGPU(gpuName, smArch string) bool

IsUnifiedMemoryGPU reports whether the given GPU model name or SM architecture represents a coherent unified-memory SoC (such as NVIDIA GB10, GB200, or GH200) where host CPU memory traffic shares package/memory bandwidth with the GPU.

func LinkToProfileHistory

func LinkToProfileHistory(plan *ExperimentPlan, execRec *ExecutionReceipt, compRec *ComparisonReceipt, opts HistoryLinkOptions) (cudaprof.HistoryRecord, error)

LinkToProfileHistory constructs an immutable, validated cudaprofilehistory.Record from execution and comparison receipts.

func LookTool

func LookTool(path string) (string, error)

LookTool returns the path to the compute-sanitizer executable. A non-empty path is resolved the way a shell would, including a bare name on PATH. An empty path tries the toolkit installs ToolSearchPaths names and then DefaultToolName on PATH. The error wraps ErrToolNotFound.

func LookupCeiling

func LookupCeiling(p0 string, p1 re_obsmodel.Residency) (re_obsmodel.Ceiling, error)

func LookupDeviceCeiling

func LookupDeviceCeiling(p0 string, p1 re_obsmodel.Residency) (re_obsmodel.Ceiling, error)

func Main

func Main(m *testing.M, cfg Config) int

Main runs a package's tests under compute-sanitizer. It is meant to be the whole body of TestMain:

func TestMain(m *testing.M) {
	os.Exit(cudasanitizer.Main(m, cudasanitizer.Config{
		Tool:          cudasanitizer.Memcheck,
		MissingTool:   cudasanitizer.MissingToolSkip,
		RequireOutput: []string{"--- PASS: TestVectorAdd"},
	}))
}

In the child process — the one launched under compute-sanitizer, recognized by ChildFlagName in its arguments — Main runs m.Run and returns its exit code, so the tests themselves behave normally.

In the parent, Main re-executes the current test binary under compute-sanitizer and returns 0 only for OutcomeClean. The parent's own os.Args are passed through unchanged, with ChildFlagName prepended, so -run, -v, -count, -timeout and -args all reach the tests the caller asked for. Note that -test.timeout is enforced inside the child, where every kernel launch is instrumented and correspondingly slower; a suite that fits in the default timeout uninstrumented may need a larger one here.

When compute-sanitizer is not installed, Config.MissingTool decides: MissingToolFail returns a nonzero code without running anything, and MissingToolSkip runs the tests uninstrumented after announcing on stderr that no sanitizer validation took place. Main never reports success for validation that did not happen.

Config.Timeout also bounds the preliminary tool version query.

Main writes its own diagnostics to stderr and passes the child's output through to the parent's stdout and stderr as it is produced.

Example

Running a package's own tests under compute-sanitizer is the common case. Main handles both halves of the re-execution: in the parent it launches the tool, and in the child it runs the tests.

package main

import (
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"os"
	"testing"
	"time"
)

func main() {
	main := func(m *testing.M) {
		os.Exit(diag.Main(m, diag.Config{
			Tool: diag.Memcheck,
			// Leaks count toward the tool's error summary.
			LeakCheck: diag.ToggleYes,
			// Without compute-sanitizer installed, run the tests
			// uninstrumented and say so, rather than claiming a pass.
			MissingTool: diag.MissingToolSkip,
			// A report of zero errors means nothing unless the kernel
			// under test actually ran.
			RequireOutput: []string{"--- PASS: TestVectorAdd"},
			Timeout:       10 * time.Minute,
			LogDir:        "testdata/sanitizer-logs",
		}))
	}
	_ = main
}

func MajorMinor

func MajorMinor(v string) string

MajorMinor returns the major.minor prefix of a dotted version string.

func Median

func Median(p0 []float64) obsevidence.Statistic

func MergeTopCPUProcs

func MergeTopCPUProcs(existing, latest []string) []string

MergeTopCPUProcs merges two slices of "<comm>(pid=<pid>):<pct>%" strings, keeping the highest observed CPU percentage per process.

func NewDCGMReader

func NewDCGMReader(p0 dcgm.Handle, p1 int32, p2 []re_obsmodel.Counter, p3 time.Duration) (*re_obsmodel.DCGMReader, error)

func NewDemangler

func NewDemangler(p0 string, p1 int) (*re_obsprobe.Demangler, error)

func NewHostModel

func NewHostModel(p0, p1, p2 string, p3 re_obsmodel.Residency, p4 []re_obsmodel.BandwidthRecord) (*re_obsmodel.Model, error)

func NewModel

func NewModel(p0 string, p1 re_obsmodel.Residency) (*re_obsmodel.Model, error)

func NewModelWithCeiling

func NewModelWithCeiling(p0 re_obsmodel.Ceiling) *re_obsmodel.Model

func NewPlanFromIncident

func NewPlanFromIncident(inc Incident, opts PlanOptions) (*ExperimentPlan, *PlanReceipt, error)

NewPlanFromIncident derives a bounded, replayable ExperimentPlan from an admitted incident. If the incident was not admitted by its evidence contract, plan generation is visibly refused.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	incident := diag.Incident{
		ID:       "inc-norm-01",
		Admitted: true,
		Workload: diag.WorkloadIdentity{WorkloadName: "layernorm"},
		ObservedEnvironment: diag.Environment{
			Model:             "NVIDIA H100",
			ComputeCapability: "sm_90",
		},
	}

	plan, receipt, err := diag.NewPlanFromIncident(incident, diag.PlanOptions{
		WarmupRuns: 2,
		Rounds:     4,
	})
	if err != nil {
		fmt.Printf("error: %v\n", err)
		return
	}

	fmt.Printf("Plan ID: %s, Rounds: %d, Verified: %d\n",
		plan.IncidentID, plan.Rounds, receipt.ArtifactsVerified)

}
Output:
Plan ID: inc-norm-01, Rounds: 4, Verified: 0

func NewTracker

func NewTracker(p0 re_obsprobe.Process, p1 int) (*re_obsprobe.Tracker, error)

func Observe

Observe reports independent timing observations. A missing host return blocks that call's duration, not kernel timing. Device busy time requires bounded activity loss; scheduler claims remain subject to scheduler admission in Diagnose. None of these observations establishes a cause or an operation correlation.

Example
f := BuildSyntheticFixture(InjectionMissingReturn)
findings := Observe(f.Input)
fmt.Println(findings[0].Admission.Admitted, findings[1].Admission.Admitted)
Output:
false true

func OperationFromContext

func OperationFromContext(p0 context.Context) (*re_obsworkload.Scope, bool)

func OutputDigest

func OutputDigest(values []float64) (string, error)

OutputDigest hashes the canonical JSON encoding of a finite, nonempty output vector.

Example
package main

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

func main() {
	digest, err := diag.OutputDigest([]float64{1, 2.5})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(len(digest))
}
Output:
64

func ParseNVCCVersionOutput

func ParseNVCCVersionOutput(output string) string

ParseNVCCVersionOutput extracts the version string from `nvcc --version` output.

func ParseProcMapsCUDALibs

func ParseProcMapsCUDALibs(mapsContent string, resolveSymlink func(string) string) map[string]string

ParseProcMapsCUDALibs extracts loaded CUDA/NVIDIA shared library versions from the text of a Linux /proc/<pid>/maps file.

func ParseTable

func ParseTable(p0 io.Reader) (re_obsmodel.Table, error)

func ProbeNVCCVersion

func ProbeNVCCVersion(ctx context.Context) string

ProbeNVCCVersion runs nvcc --version and returns the compiler version string.

func ProbeProcessCUDALibs

func ProbeProcessCUDALibs(pids ...int) map[string]string

ProbeProcessCUDALibs scans /proc/<pid>/maps for the given PIDs and returns a map of loaded CUDA/NVIDIA shared library base names (such as "libcublasLt.so", "libnvrtc.so", "libcudart.so", "libcuda.so") to their resolved version strings.

func ReadBandwidthRecords

func ReadBandwidthRecords(p0 string) ([]re_obsmodel.BandwidthRecord, error)

func ReadDir

func ReadDir(p0 string) (*re_obsmodel.CensusCapture, error)

func ReadFinding

func ReadFinding(reader io.Reader, source []byte) (ptx.SeedResult, error)

ReadFinding reads one serialized campaign SeedResult and checks its source, comparison identity and retained confirmation evidence. Input is limited to 1 MiB, 32 nesting levels and 65536 JSON tokens. Unknown or duplicate fields, trailing data and incomplete historical records are errors. Free-form input and geometry labels remain labels; this function does not turn them into a runnable Case or substitute historical confirmations for a fresh baseline.

Example
// This simulated record demonstrates import. Historical records missing
// structured comparisons and actual confirmation runs are refused.
original, source := findingRecord()
data, err := json.Marshal(original)
if err != nil {
	fmt.Println(err)
	return
}
finding, err := ReadFinding(bytes.NewReader(data), source)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(finding.Seed, finding.Confirmation.Findings, err)
Output:
17 2 <nil>

func ReadLoadAvg

func ReadLoadAvg() ([3]float64, error)

ReadLoadAvg reads the 1-, 5-, and 15-minute host CPU load averages.

func Render

func Render(w io.Writer, reports []DifferentialReport) error

Render writes a human-readable ANSI terminal summary to w.

Example
package main

import (
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"os"
)

func main() {
	reports := []diag.DifferentialReport{
		{
			Phase:              diag.PhasePrefill,
			Family:             diag.FamilyExperts,
			Availability:       diag.AvailableBoth,
			Available:          true,
			CObserved:          true,
			GoObserved:         true,
			CDurationNs:        12_000_000,
			GoDurationNs:       10_000_000,
			DeltaNs:            -2_000_000,
			Speedup:            1.20,
			NullDriftNs:        50_000,
			ExceedsDrift:       true,
			StatisticallyValid: true,
		},
	}

	_ = diag.Render(os.Stdout, reports)

}
Output:
PHASE    FAMILY   C TIME    GO TIME   DELTA     SPEEDUP  DRIFT FLOOR  EXCEEDS DRIFT?
prefill  experts  12.00 ms  10.00 ms  -2.00 ms  1.20x    50.00 µs     YES

func Replay

Replay executes the experiment plan across warmup, null control, and interleaved rounds, returning separated execution and comparison receipts.

func ResolveGitState

func ResolveGitState(repoDir string) (commit string, dirty bool)

ResolveGitState returns the VCS commit hash and dirty flag from embedded Go build info or by querying git in repoDir.

func SafeCommandArm

func SafeCommandArm(plan *ExperimentPlan, name, binaryPath string, args ...string) (timing.Arm, error)

SafeCommandArm constructs a verified trial arm that directly executes a declared binary. It verifies that binaryPath corresponds to a declared and digest-verified binary artifact, and executes directly without shell interpolation. Each invocation is limited to 30 seconds and 16 MiB of combined output, hashed without retaining it.

func SampleHostCPU

func SampleHostCPU(ctx context.Context, engineName string, unifiedMem bool) (topProcs []string, contended bool)

SampleHostCPU inspects running host processes via ps and returns the top non-engine CPU processes ("<comm>(pid=<pid>):<pct>%") and whether any non-engine process uses >= 50% CPU on a unified-memory GPU.

func ServeQuarantine

func ServeQuarantine()

ServeQuarantine makes the running program a Quarantine child when the parent started it as one, and otherwise returns at once. A program used as QuarantineConfig.Command, including a test binary through TestMain, calls it before doing anything else.

As a child it reads the request, refuses without an inherited gpu-lock lease, creates its own CUDA context on device 0, allocates every buffer with guard bands, launches, writes every byte back for the parent to judge, and exits. It never sees the reference. If the launch has not finished at the request's deadline it reports a deadline and exits without waiting for the kernel.

func SharedObjectVersion

func SharedObjectVersion(filename string) (base, version string)

SharedObjectVersion splits a versioned shared object filename such as "libcublasLt.so.13.1.0.3" into ("libcublasLt.so", "13.1.0.3").

func SumDuration

func SumDuration(intervals []tracecontract.Interval) (time.Duration, error)

SumDuration computes the arithmetic sum of positive interval durations. Empty, zero-length and inverted intervals contribute zero. It returns an error if an interval duration or the total cannot be represented by time.Duration.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/cudaprof/tracecontract"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	d, err := diag.SumDuration([]tracecontract.Interval{{Start: 0, End: 10}, {Start: 5, End: 15}})
	fmt.Println(d, err)
}
Output:
20ns <nil>

func Targets

func Targets() []re_obsprobe.Target

func ToolSearchPaths

func ToolSearchPaths() []string

ToolSearchPaths returns the executables LookTool tries before PATH, in order. The list is empty on GOOS values Compute Sanitizer does not ship for, leaving PATH as the only source.

A toolkit install is preferred over PATH because a distribution package can leave an older compute-sanitizer earlier on PATH than the toolkit's own. Such a binary is not merely out of date: it does not know the current devices, and one that shipped against different sanitizer libraries fails to start at all rather than reporting that it is too old. Checking the toolkit first picks the build that matches the libraries beside it.

A non-empty Config.Path, or a toolkit root in CUDA_HOME, CUDA_PATH or CUDA_ROOT, overrides the defaults.

func ToolVersion

func ToolVersion(ctx context.Context, path string) (string, error)

ToolVersion runs compute-sanitizer --version and returns the line naming the build, for recording which one produced a report. An empty path resolves the tool the way LookTool does.

The first line of --version output is a product banner identical across every release, so it identifies nothing; the build is on the line that starts with "Version", as in "Version 2026.3.0.0 (build 38637409) (public-release)". When no line says that, the first non-empty line is returned instead.

func TransfersActiveNs

func TransfersActiveNs(p0 []re_obsmodel.Transfer) int64

func UnionDuration

func UnionDuration(intervals []tracecontract.Interval) (time.Duration, error)

UnionDuration computes the duration of the interval union. Empty, zero-length and inverted intervals contribute zero. It returns an error if the duration cannot be represented by time.Duration.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/cudaprof/tracecontract"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	d, err := diag.UnionDuration([]tracecontract.Interval{{Start: 0, End: 10}, {Start: 5, End: 15}})
	fmt.Println(d, err)
}
Output:
15ns <nil>

func ValidateBaselines

func ValidateBaselines(baselines []Baseline) error

ValidateBaselines checks baseline declarations against evaluation rules.

func ValidateCase

func ValidateCase(c Case) error

ValidateCase checks that c has non-empty source, valid non-zero shapes and launch geometry.

func ValidateCeiling

func ValidateCeiling(p0 re_obsmodel.Ceiling) error

func ValidateEnvironment

func ValidateEnvironment(plan *ExperimentPlan, env Environment) error

ValidateEnvironment checks that the current host and GPU match the plan's requirements. If drift is detected, a descriptive ErrEnvironmentDrift is returned.

func ValidateExecutionSpec

func ValidateExecutionSpec(plan *ExperimentPlan, spec *ExecutionSpec) error

ValidateExecutionSpec verifies versioned identity and exact artifact closure.

func ValidateHardwareCoverage

func ValidateHardwareCoverage(raw []byte, status HardwareStatus) error

ValidateHardwareCoverage verifies that coverage bytes were produced by genuine physical hardware execution. If status is StatusPendingHardware or not StatusHardwareAvailable, it returns an error wrapping cudaerrors.ErrHardwarePending.

func ValidatePlan

func ValidatePlan(plan *ExperimentPlan) error

ValidatePlan verifies structural completeness and authenticates all declared artifacts on disk.

For a derived plan, ValidatePlan checks only the shape of the lineage fields; the lineage itself is a claim that only VerifyDerivation authenticates against the parent plan.

func ValidateReproducerManifest

func ValidateReproducerManifest(m *ReproducerManifest) error

ValidateReproducerManifest checks that m has non-empty inputs, non-zero tensor shape extents, valid launch geometry within device bounds, and valid underlying reproducer.

func VerifyDerivation

func VerifyDerivation(parent, derived *ExperimentPlan) error

VerifyDerivation checks that derived is exactly the plan that DerivePlan produces from parent with derived's device fields and rationale. It returns an error if either plan fails ValidatePlan, if derived is a root plan, if derived names a different parent, or if derived differs from parent in anything other than its device fields and lineage.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	parent, _, err := diag.NewPlanFromIncident(diag.Incident{
		ID:       "inc-001",
		Admitted: true,
		ObservedEnvironment: diag.Environment{
			Model:             "NVIDIA GB10",
			ComputeCapability: "sm_121a",
		},
	}, diag.PlanOptions{Rounds: 3})
	if err != nil {
		fmt.Println(err)
		return
	}
	derived, err := diag.DerivePlan(parent, diag.Environment{
		Model:             "NVIDIA H100",
		ComputeCapability: "sm_90",
	}, "evaluate on Hopper")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(derived.ParentPlanDigest == parent.PlanDigest)
	fmt.Println(derived.DerivationRationale)
	fmt.Println(diag.VerifyDerivation(parent, derived))
}
Output:
true
evaluate on Hopper
<nil>

func WatchDCGM

func WatchDCGM(p0 *dcgm.Session, p1 string, p2 int32, p3 []re_obsmodel.Counter, p4, p5 time.Duration) (*re_obsmodel.DCGMReader, error)

func WithDefaultLabels

func WithDefaultLabels(p0 map[string]string) re_obsworkload.AnnotatorOption

func WithOperation

func WithOperation(p0 context.Context, p1 *re_obsworkload.Scope) context.Context

func WithScopeLabels

func WithScopeLabels(p0 map[string]string) re_obsworkload.ScopeOption

func WriteArtifactPackage

func WriteArtifactPackage(dir string, finding isa_ptx.SeedResult, reduction Reduction, opts ArtifactOptions) error

WriteArtifactPackage writes an artifact directory containing preserved testdata and an integrity test. Callers should prefer ExportPackage, which additionally emits a runnable failure reproducer test.

func WriteComparison

func WriteComparison(w io.Writer, gates []ComparisonGate) error

WriteComparison writes machine-readable gates without omitting unknown cells.

func WriteHistory

func WriteHistory(w io.Writer, snapshots []Snapshot) error

WriteHistory writes a version 1 or 2 offline replay corpus. It validates every snapshot and refuses more than 4096 snapshots or 16 MiB of encoded data before encoding the history, without writing to w. A stateful policy requires a complete history from its initial state; a wrapped evaluator's retained suffix is not necessarily replayable.

Example
package main

import (
	"bytes"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	var data bytes.Buffer
	if err := diag.WriteHistory(&data, nil); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(data.String())
}
Output:
{"version":1,"snapshots":null}

func WriteQualificationLedger

func WriteQualificationLedger(w io.Writer, l QualificationLedger) error

WriteQualificationLedger validates and serializes a ledger. A short write is an error. It does not verify receipt files; use VerifyQualificationLedger.

Example
var output bytes.Buffer
err := WriteQualificationLedger(&output, pendingLedgerExample())
fmt.Println(err, output.Len() > 0)
Output:
<nil> true

func WriteRegisteredReceipt

func WriteRegisteredReceipt(w io.Writer, v RegisteredReceipt) error

WriteRegisteredReceipt writes canonical envelope bytes without a newline. It checks structure only, and propagates errors and short writes.

Example
err := WriteRegisteredReceipt(io.Discard, RegisteredReceipt{})
fmt.Println(err)
Output:
registered receipt: invalid identity

func WriteRegistration

func WriteRegistration(w io.Writer, r Registration) error

WriteRegistration validates and writes one canonical JSON record. A short write is an error. It does not authenticate policy artifacts or measurements.

Example
r, _ := exampleRegistration()
var b bytes.Buffer
fmt.Println(WriteRegistration(&b, r), b.Len() > 0)
Output:
<nil> true

Types

type AcceptanceRecord

type AcceptanceRecord struct {
	Version               int             `json:"version"`
	RequestDigest         string          `json:"request_digest"`
	AuthorityID           string          `json:"authority_id"`
	AuthorityPolicyDigest string          `json:"authority_policy_digest"`
	AuthorityConfigDigest string          `json:"authority_config_digest"`
	Disposition           string          `json:"disposition"`
	ScopedRoleDecisions   []ScopeDecision `json:"scoped_role_decisions"`
	Reason                string          `json:"reason"`
	Owner                 string          `json:"owner"`
	NextAction            string          `json:"next_action"`
}

AcceptanceRecord retains explicit bounded evidence identities, not acquisition authority.

type Access

type Access struct {
	Address         uint64
	Bytes           uint64
	Write           bool
	Allocation      uint64
	AllocationBytes uint64
}

Access describes an invalid global-memory access. Address is the accessed address; Allocation and AllocationBytes, when present, are the tool's nearest allocation, which is evidence rather than proof of ownership. Unknown report formats remain available in Finding's original text.

type AcquisitionBounds

type AcquisitionBounds struct {
	Domain      string   `json:"domain"`
	Family      string   `json:"family"`
	Epoch       string   `json:"epoch"`
	Start       int64    `json:"start"`
	End         int64    `json:"end"`
	Uncertainty *float64 `json:"uncertainty"`
	Unit        string   `json:"unit"`
}

AcquisitionBounds retains explicit bounded evidence identities, not acquisition authority.

type ActiveBackendSpy

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

ActiveBackendSpy monitors backend mutation interfaces.

In shadow evaluation mode, all policy actions are strictly observational. This spy acts as a verification harness asserting that zero mutation calls occur across all normal, cancellation, and error paths.

Example
package main

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

func main() {
	spy := diag.NewActiveBackendSpy()

	// In shadow mode, no mutation methods should be called
	if err := spy.AssertZeroMutations(); err != nil {
		fmt.Printf("mutation error: %v\n", err)
		return
	}

	fmt.Printf("active mutation calls recorded: %d\n", spy.CallCount())

}
Output:
active mutation calls recorded: 0

func NewActiveBackendSpy

func NewActiveBackendSpy() *ActiveBackendSpy

NewActiveBackendSpy constructs a fresh backend spy with zero recorded calls.

func (*ActiveBackendSpy) AssertZeroMutations

func (s *ActiveBackendSpy) AssertZeroMutations() error

AssertZeroMutations verifies that no mutation calls were executed. If any mutation call occurred, it returns an error detailing the illegal calls.

func (*ActiveBackendSpy) CallCount

func (s *ActiveBackendSpy) CallCount() int

CallCount returns the number of recorded mutation attempts.

func (*ActiveBackendSpy) Calls

func (s *ActiveBackendSpy) Calls() []MutationCall

Calls returns a copy of all recorded mutation calls.

func (*ActiveBackendSpy) EvictChunk

func (s *ActiveBackendSpy) EvictChunk(chunkAddr uint64) error

EvictChunk simulates an active UVM page chunk eviction call.

func (*ActiveBackendSpy) MutatePTX

func (s *ActiveBackendSpy) MutatePTX(kernelName string, ptx []byte) error

MutatePTX simulates an active PTX kernel modification call.

func (*ActiveBackendSpy) PrefetchPages

func (s *ActiveBackendSpy) PrefetchPages(va uint64, count uint32) error

PrefetchPages simulates an active UVM page prefetch request.

func (*ActiveBackendSpy) Reset

func (s *ActiveBackendSpy) Reset()

Reset clears recorded calls.

func (*ActiveBackendSpy) SetTimeslice

func (s *ActiveBackendSpy) SetTimeslice(channelID uint32, timesliceUS uint64) error

SetTimeslice simulates an active scheduler timeslice update.

type ActivityAnalysis

type ActivityAnalysis struct {
	Version  int                        `json:"version"`
	Joins    []obsworkload.ActivityJoin `json:"joins"`
	Findings []tracecontract.Finding    `json:"findings"`
}

func AnalyzeActivities

func AnalyzeActivities(batch obsworkload.ActivityBatch, annotations []obsworkload.HostSubmission, receipt tracecontract.Receipt) (ActivityAnalysis, error)

AnalyzeActivities joins a bounded frozen producer batch and admits each operation's activity duration independently. The receipt must identify the actual raw export and producer clock. Missing identity or timestamps withhold that row; loss of another record family cannot upgrade or invalidate it. This entry point does not perform a native collection or infer a scheduler join.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/cudaprof/tracecontract"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	_, err := diag.AnalyzeActivities(diag.ActivityBatch{}, nil, tracecontract.Receipt{})
	fmt.Println(err != nil)
}
Output:
true

func AnalyzeActivityJSONL

func AnalyzeActivityJSONL(reader io.Reader, metadata obsworkload.ActivityBatch, annotations []obsworkload.HostSubmission, receipt tracecontract.Receipt) (ActivityAnalysis, error)

AnalyzeActivityJSONL reads the existing cuptiactivity.Record JSON-lines export. Metadata identifies the producer session, process, run and timestamp epoch. It refuses truncated lines, unknown fields, more than 32 MiB, and a raw hash differing from the receipt. It never derives producer identity from timestamps.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/cudaprof/tracecontract"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	_, err := diag.AnalyzeActivityJSONL(bytes.NewReader(nil), diag.ActivityBatch{}, nil, tracecontract.Receipt{})
	fmt.Println(err != nil)
}
Output:
true

type ActivityBatch

type ActivityBatch = re_obsworkload.ActivityBatch

type ActivityJoin

type ActivityJoin = re_obsworkload.ActivityJoin

type AnalysisCheck

type AnalysisCheck struct {
	MethodArtifact            RegistrationArtifact `json:"method_artifact"`
	OrderArtifact             RegistrationArtifact `json:"order_artifact"`
	Seed                      *uint64              `json:"seed"`
	Repetitions               uint64               `json:"repetitions"`
	Warmup                    uint64               `json:"warmup"`
	Order                     string               `json:"order"`
	Population                []Population         `json:"population"`
	ResultArtifact            RegistrationArtifact `json:"result_artifact"`
	StoppingContractDigest    string               `json:"stopping_contract_digest"`
	MissingDataContractDigest string               `json:"missing_data_contract_digest"`
}

AnalysisCheck retains explicit bounded evidence identities, not acquisition authority.

type AnalysisResult

type AnalysisResult struct {
	Version             int                    `json:"version"`
	Profile             string                 `json:"profile"`
	RegistrationDigest  string                 `json:"registration_digest"`
	ProtocolDigest      string                 `json:"protocol_digest"`
	Arm                 string                 `json:"arm"`
	SelectedCell        SelectedCellIdentity   `json:"selected_cell"`
	OriginalToolReceipt RegistrationArtifact   `json:"original_tool_receipt"`
	MethodArtifact      RegistrationArtifact   `json:"method_artifact"`
	Population          []Population           `json:"population"`
	Scope               AnalysisResultScope    `json:"scope"`
	OutputArtifacts     []RegistrationArtifact `json:"output_artifacts"`
}

AnalysisResult binds separately produced analysis output to original arm evidence. Its canonical analysis-result-v1 bytes establish a relation only; independent execution, statistical validity and acquisition require policy acceptance. It contains no enclosing scope, pair or acceptance digest.

Example
// This prints the profile identity, not a complete admissible result.
result := AnalysisResult{Version: 1, Profile: "analysis-result-v1", Arm: "candidate"}
fmt.Println(result.Profile, result.Arm)
Output:
analysis-result-v1 candidate

type AnalysisResultScope

type AnalysisResultScope struct {
	Role             string                     `json:"role"`
	TargetID         string                     `json:"target_id"`
	SelectedTargets  []string                   `json:"selected_targets"`
	Property         string                     `json:"property"`
	Unit             string                     `json:"unit"`
	Denominator      uint64                     `json:"denominator"`
	PopulationFamily string                     `json:"population_family"`
	TimingFamily     string                     `json:"timing_family"`
	ClockDomain      string                     `json:"clock_domain"`
	ClockEpoch       string                     `json:"clock_epoch"`
	RangeStart       int64                      `json:"range_start"`
	RangeEnd         int64                      `json:"range_end"`
	ExperimentPhase  string                     `json:"experiment_phase"`
	Properties       []RegistrationPropertySpec `json:"properties"`
	ClockDomains     []RegistrationClockDomain  `json:"clock_domains"`
}

AnalysisResultScope is the semantic scope of an analysis result. It omits ScopeID, artifact digests and enclosing identities to keep result and scope preimages acyclic. An empty Property denotes the registered property set; Properties still binds every exact unit, denominator and timing method.

Example
scope := AnalysisResultScope{Properties: []RegistrationPropertySpec{{Property: "reproducibility", Unit: "bytes", Denominator: 1}}}
fmt.Println(scope.Properties[0].Unit, scope.Properties[0].Denominator)
Output:
bytes 1

type Annotator

type Annotator = re_obsworkload.Annotator

type AnnotatorOption

type AnnotatorOption = re_obsworkload.AnnotatorOption

type Argument

type Argument struct {
	Name    string
	Type    string
	Buffer  bool
	Address uint64
	Size    uint64
	Value   []byte
}

Argument describes a scalar value or a device slice. For a buffer, Address and Size describe the slice, not necessarily its whole allocation. Value is the host ABI representation of a scalar; embedded pointers are unsupported.

type ArmCount

type ArmCount = re_obsmodel.ArmCount

type ArmRunner

type ArmRunner func(ctx context.Context, phase CmpPhase) (timing.Receipt, error)

ArmRunner executes a workload phase and returns a receipt with measured timings and output digest.

func CommandArmRunner

func CommandArmRunner(binPath string, args ...string) ArmRunner

CommandArmRunner returns an ArmRunner that executes an external binary with the specified arguments followed by the phase. It is Command{Path: binPath, Args: args}.Runner().

type ArmValue

type ArmValue struct {
	Property                string  `json:"property"`
	Unit                    string  `json:"unit"`
	Denominator             uint64  `json:"denominator"`
	CandidateValue          float64 `json:"candidate_value"`
	CandidateAbsoluteBound  float64 `json:"candidate_absolute_bound"`
	ComparatorValue         float64 `json:"comparator_value"`
	ComparatorAbsoluteBound float64 `json:"comparator_absolute_bound"`
	MaxValue                float64 `json:"max_value"`
	ThresholdPolicy         string  `json:"threshold_policy"`
}

ArmValue retains explicit bounded evidence identities, not acquisition authority.

type ArtifactManifest

type ArtifactManifest struct {
	Version        int               `json:"version"`
	Timestamp      string            `json:"timestamp"`
	Files          map[string]string `json:"files"`
	ManifestSHA256 string            `json:"manifest_sha256"`
}

ArtifactManifest records all generated artifacts and their cryptographically verified digests.

func VerifyManifest

func VerifyManifest(dir string) (*ArtifactManifest, error)

VerifyManifest verifies a version 1 manifest and its declared regular files. It refuses symlinks, non-local paths, more than 1024 files, manifests over 1 MiB, files over 64 MiB, and total artifact contents over 256 MiB.

func WriteReportArtifacts

func WriteReportArtifacts(outDir string, report *EvaluationReport) (*ArtifactManifest, error)

WriteReportArtifacts persists the evaluation report, claim, protocol, and receipts to outDir, producing an ArtifactManifest with SHA256 digests.

type ArtifactOptions

type ArtifactOptions struct {
	Repeats              int
	DetectionProbability float64
	MaxAttempts          int
}

ArtifactOptions bounds a preserved exporter artifact package. Detection assumes independent attempts with probability equal to the measured rate; that model is explicit and is not a statistical confidence guarantee.

type ArtifactRef

type ArtifactRef struct {
	Name      string `json:"name"`
	Path      string `json:"path"`
	Digest    string `json:"sha256"`
	SizeBytes int64  `json:"size_bytes"`
	Role      string `json:"role,omitempty"` // source, binary, input, library, trace, reference
}

ArtifactRef references an immutable artifact by path, size, and SHA-256 digest.

type AsyncMemory

type AsyncMemory = re_obsprobe.AsyncMemory

type Attribution

type Attribution = re_obsmodel.Attribution

type AttributionReceipt

type AttributionReceipt struct {
	TotalRequests   int     `json:"total_requests"`
	JoinedRequests  int     `json:"joined_requests"`
	ExactJoins      int     `json:"exact_joins"`
	IncorrectJoins  int     `json:"incorrect_joins"`
	MissingJoins    int     `json:"missing_joins"`
	AmbiguousJoins  int     `json:"ambiguous_joins"`
	JoinPrecision   float64 `json:"join_precision"`
	JoinRecall      float64 `json:"join_recall"`
	GateDisposition string  `json:"gate_disposition"`
}

AttributionReceipt summarizes join accuracy against independent ground truth.

type Availability

type Availability string

Availability indicates whether an architectural family was observed in both comparison arms.

const (
	AvailableBoth   Availability = "both"
	AvailableCOnly  Availability = "c_only"
	AvailableGoOnly Availability = "go_only"
	AvailableNone   Availability = "none"
)

type BandwidthPoint

type BandwidthPoint = re_obsmodel.BandwidthPoint

type BandwidthRecord

type BandwidthRecord = re_obsmodel.BandwidthRecord

type Baseline

type Baseline struct {
	Name             string   `json:"name"`
	Category         string   `json:"category"`
	Version          string   `json:"version"`
	ComparisonScope  string   `json:"comparison_scope"`
	Independent      bool     `json:"independent"`
	SupportedModes   []string `json:"supported_modes"`
	UnavailableModes []string `json:"unavailable_modes"`
}

Baseline records configuration and capabilities of an alternative tool.

func DefaultBaselines

func DefaultBaselines() []Baseline

DefaultBaselines returns candidate alternatives, without asserting versions or supported modes. Qualification must supply observed frozen ToolSpec receipts.

type BatchingCandidate

type BatchingCandidate struct {
	StreamID        int64
	StartNs         int64
	EndNs           int64
	LaunchCount     int
	Kernels         []string
	Hypothesis      string
	MissingEvidence []string
}

BatchingCandidate identifies a contiguous region of closely spaced kernel launches on a stream that may be candidates for CUDA graph capture or operator batching.

type Binding

type Binding = re_obsprobe.Binding

type Calibration

type Calibration = re_obsmodel.Calibration

type CalibrationReceipt

type CalibrationReceipt = re_obsmodel.CalibrationReceipt

type CaptureConfig

type CaptureConfig struct {
	Enabled         bool   `json:"enabled"`
	Collector       string `json:"collector,omitempty"`
	SamplingRateHz  int    `json:"sampling_rate_hz,omitempty"`
	MaxCaptureBytes int64  `json:"max_capture_bytes,omitempty"`
	TraceLossBudget uint64 `json:"trace_loss_budget"`
}

CaptureConfig specifies collection parameters for non-perturbing telemetry.

type Case

type Case struct {
	Source    string
	Inputs    []uint64
	Shape     []uint64
	Grid      [3]uint32
	Block     [3]uint32
	SharedMem uint32
	Schedule  *Schedule
}

Case supplies explicit workload inputs and launch dimensions. It is not an interpretation of a campaign's free-form input or geometry labels. Callers importing campaign records must obtain these values from the workload's recorded input contract. This capability supports uint64 inputs only. Schedule, when present, binds injection decisions to pristine Source.

func (Case) Artifact

func (c Case) Artifact() (string, error)

Artifact returns the exact PTX a runner must load for this case. With no Schedule it returns Source unchanged. Recorded decisions are validated by the campaign producer's Replay API; source and options are never inferred.

Example
c := Case{Source: ".version 8.7\n.target sm_70\n.address_size 64\n.visible .entry k() { ret; }\n", Schedule: &Schedule{Options: isa_ptx.Options{Seed: 17, Intensity: 1}}}
ptx, err := c.Artifact()
fmt.Println(ptx == c.Source, err)
Output:
true <nil>

type Ceiling

type Ceiling = re_obsmodel.Ceiling

type CeilingBasis

type CeilingBasis = re_obsmodel.CeilingBasis

type CensusCapture

type CensusCapture = re_obsmodel.CensusCapture

type CensusIdentity

type CensusIdentity = re_obsmodel.CensusIdentity

type CensusLaunch

type CensusLaunch = re_obsmodel.CensusLaunch

type CensusPhase

type CensusPhase = re_obsmodel.CensusPhase

type CheckedBinding

type CheckedBinding struct {
	Path           string `json:"path"`
	ArtifactDigest string `json:"artifact_digest"`
	DecoderProfile string `json:"decoder_profile"`
	ScopeID        string `json:"scope_id"`
	Membership     string `json:"membership"`
}

CheckedBinding retains explicit bounded evidence identities, not acquisition authority.

type Claim

type Claim struct {
	Task              string   `json:"task"`
	SpecificAdvantage string   `json:"specific_advantage"`
	ComparedWith      []string `json:"compared_with"`
	QualifiedOn       string   `json:"qualified_on"`
	Evidence          string   `json:"evidence"`
	Limits            []string `json:"limits"`
}

Claim encapsulates a bounded comparative claim qualified by evaluation evidence.

func FormulateClaim

func FormulateClaim(report *EvaluationReport) (*Claim, error)

FormulateClaim checks the report's local no-fault receipt but cannot derive a comparative claim without independently verified paired evidence. Imported report assertions and named baselines do not supply that evidence.

Example
package main

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

func main() {
	proto := diag.DefaultProtocol(diag.PhasePilot)
	cfg := diag.DefaultEvalConfig()
	cfg.ExerciseStress = false

	report, err := diag.RunEvaluation(context.Background(), proto, cfg)
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}

	claim, err := diag.FormulateClaim(report)
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}

	fmt.Printf("Has Task: %t\n", claim.Task != "")
	fmt.Printf("Has Alternatives: %t\n", len(claim.ComparedWith) > 0)
	fmt.Printf("Has Limits: %t\n", len(claim.Limits) > 0)
}
Output:
err: cudadiageval: qualification evidence incomplete

func FormulateComparisonClaim

func FormulateComparisonClaim(ctx context.Context, c RegisteredComparison, authority EvidenceAuthority, provider EvidenceAcceptance) (claim *Claim, resultErr error)

FormulateComparisonClaim consumes the shared pair admission attempt before checking context, provider or scope. Every failure consumes it; retry requires a new explicit pair acquisition. Provider policy is an external trust boundary, never decoded from a receipt. Record ownership transfers on Check return, even with an error; close is called exactly once and its error prevents a Claim.

Example
_, err := FormulateComparisonClaim(context.Background(), RegisteredComparison{}, EvidenceAuthority{}, nil)
fmt.Println(err)
Output:
cudadiageval: claim missing required bounded fields: invalid comparison handle

func (*Claim) Format

func (c *Claim) Format() string

Format renders the diagnostic claim with comparisons, hardware, evidence and limits.

func (*Claim) JSON

func (c *Claim) JSON() ([]byte, error)

JSON returns indented JSON representation of the Claim.

func (*Claim) Validate

func (c *Claim) Validate() error

Validate verifies that the diagnostic claim contains its required bounded fields.

type Class

type Class = re_obsmodel.Class

type CmpPhase

type CmpPhase string
const (
	PhasePrefill CmpPhase = "prefill"
	PhaseDecode  CmpPhase = "decode"
)

type ColdCheckInput

type ColdCheckInput = re_obsmodel.ColdCheckInput

type ColdCheckResult

type ColdCheckResult = re_obsmodel.ColdCheckResult

type CollectionCostReport

type CollectionCostReport struct {
	TotalSubmissions       uint64        `json:"total_submissions"`
	TotalActivities        uint64        `json:"total_activities"`
	RingBufferCapacity     int           `json:"ring_buffer_capacity"`
	RetainedRecords        int           `json:"retained_records"`
	CaptureBundleBytes     int64         `json:"capture_bundle_bytes"`
	AverageRecordLatencyNs int64         `json:"average_record_latency_ns"`
	ElapsedCaptureDuration time.Duration `json:"elapsed_capture_duration"`
	// MeasurementStatus distinguishes collected counts/bytes from unavailable
	// record latency and matched collector-off/on workload cost.
	MeasurementStatus string `json:"measurement_status"`
}

CollectionCostReport captures overhead and resource measurements for the telemetry pipeline.

type Command

type Command struct {
	Path string
	Args []string

	// NoPhaseArg leaves the phase off the end of Args. A program that takes
	// no such argument can read the phase from CUDACMP_PHASE instead.
	NoPhaseArg bool

	// Digest, if set, selects the lines of standard output that are
	// digested: only lines it matches count, in order, so output that varies
	// from run to run, such as a throughput line, can be left out. A run in
	// which it matches no line is an error, since its digest would then say
	// nothing about the output.
	Digest *regexp.Regexp
}

A Command runs one arm of a trial as an external program. The receipt's timing is the program's wall-clock time and its digest is the SHA-256 of the program's standard output.

The program's environment is the caller's with CUDACMP_PHASE set to the phase.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"regexp"
)

func main() {
	// Digest only the result line, so the throughput line, which differs
	// from run to run, cannot make two runs of one arm disagree.
	arm := diag.Command{
		Path:       "/bin/sh",
		Args:       []string{"-c", `echo "result 42"; echo "tok/s $$"`},
		NoPhaseArg: true,
		Digest:     regexp.MustCompile(`^result `),
	}
	r, err := arm.Runner()(context.Background(), diag.PhaseDecode)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(r.Digest[:12])
}
Output:
258a08a02096

func (Command) Runner

func (c Command) Runner() ArmRunner

Runner returns an ArmRunner that runs c.

type CommandArm

type CommandArm struct {
	Path   string   `json:"path"`
	SHA256 string   `json:"sha256"`
	Args   []string `json:"args"`
}

CommandArm declares one direct executable invocation. Args are passed literally to the executable; no shell or environment expansion is used.

type CommandArtifact

type CommandArtifact struct {
	Name   string `json:"name"`
	Path   string `json:"path"`
	SHA256 string `json:"sha256"`
}

CommandArtifact binds a named plan input or library to its on-disk bytes.

type CommandAttempt

type CommandAttempt struct {
	Arm          string         `json:"arm"`
	Round        int            `json:"round"`
	Started      time.Time      `json:"started"`
	Finished     time.Time      `json:"finished"`
	ExitCode     int            `json:"exit_code"`
	StdoutBytes  int            `json:"stdout_bytes"`
	StderrBytes  int            `json:"stderr_bytes"`
	StdoutSHA256 string         `json:"stdout_sha256"`
	StderrSHA256 string         `json:"stderr_sha256"`
	Partial      bool           `json:"partial"`
	Result       *CommandResult `json:"result,omitempty"`
	Error        string         `json:"error,omitempty"`
}

CommandAttempt preserves process evidence for each invocation requested by Replay, including failures that Replay cannot retain in its core receipt.

type CommandReplayRunner

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

CommandReplayRunner executes one declared arm directly and retains bounded output and attempt evidence. Construct it with NewCommandReplayRunner.

func NewCommandReplayRunner

func NewCommandReplayRunner(plan *ExperimentPlan, spec ExecutionSpec) (*CommandReplayRunner, error)

NewCommandReplayRunner validates the plan, spec, artifact closure, and selected mode before any child process can start.

func (*CommandReplayRunner) Attempts

func (r *CommandReplayRunner) Attempts() []CommandAttempt

Attempts returns a copy of all child invocations attempted so far.

func (*CommandReplayRunner) RunArm

func (r *CommandReplayRunner) RunArm(ctx context.Context, armName string, round int) (host_timing.Receipt, []float64, error)

RunArm executes one declared arm with the spec's bounded timeout/output.

type CommandResult

type CommandResult struct {
	Version      int           `json:"version"`
	OutputValues []float64     `json:"output_values"`
	OutputSHA256 string        `json:"output_sha256"`
	Timing       CommandTiming `json:"timing"`
}

CommandResult is the exact result envelope accepted from a child process.

type CommandTiming

type CommandTiming struct {
	Kind   host_timing.TimingKind `json:"kind"`
	Status string                 `json:"status"`
	Unit   string                 `json:"unit"`
	Count  int64                  `json:"count"`
}

CommandTiming is the child's explicit measurement declaration.

type Comparison

type Comparison = re_obsprobe.Comparison

type ComparisonGate

type ComparisonGate struct {
	Property string `json:"property"`
	Status   string `json:"status"`
	Reason   string `json:"reason,omitempty"`
}

ComparisonGate is one independent comparison result.

func CompareTool

func CompareTool(p Protocol, receipt ToolReceipt, raw io.Reader) ([]ComparisonGate, error)

CompareTool verifies a bounded raw artifact before evaluating preregistered thresholds. Each property remains unknown unless measured and supported. It makes no claim about independent lineage or superiority over other tools.

Example
package main

import (
	"crypto/sha256"
	"encoding/json"
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag"
	"strings"
)

func main() {
	p := diag.DefaultProtocol(diag.PhaseQualification)
	tool := diag.ToolSpec{Name: "fixture", Version: "1", Configuration: "cpu-control", Lineage: "fixture", Support: "unknown"}
	p.Tools = []diag.ToolSpec{tool}
	p.PropertyLimits = map[string]float64{"attribution": 0}
	_ = p.Freeze()
	receipt := diag.ToolReceipt{Tool: tool, ProtocolDigest: p.FrozenDigest}
	data, _ := json.Marshal(receipt)
	raw := string(data)
	receipt.RawDigest = fmt.Sprintf("%x", sha256.Sum256(data))
	gates, _ := diag.CompareTool(p, receipt, strings.NewReader(raw))
	fmt.Println(gates[0].Property, gates[0].Status)
}
Output:
attribution unknown

type ComparisonIdentity

type ComparisonIdentity = obsprofcore.ComparisonIdentity

ComparisonIdentity provides a versioned identity schema for captures and trial runs.

type ComparisonReceipt

type ComparisonReceipt struct {
	ExecutionID          string              `json:"execution_id"`
	PlanID               string              `json:"plan_id"`
	EvaluatedAt          time.Time           `json:"evaluated_at"`
	BaselineArm          string              `json:"baseline_arm"`
	CandidateArm         string              `json:"candidate_arm"`
	TimingChannel        timing.TimingKind   `json:"timing_channel"`
	BaselineDuration     time.Duration       `json:"baseline_duration"`
	CandidateDuration    time.Duration       `json:"candidate_duration"`
	Delta                time.Duration       `json:"delta"`
	Ratio                float64             `json:"ratio"`
	NullDriftNoiseFloor  time.Duration       `json:"null_drift_noise_floor"`
	ExceedsNoiseFloor    bool                `json:"exceeds_noise_floor"`
	RegressionDetected   bool                `json:"regression_detected"`
	Verdict              cudaprof.Verdict    `json:"verdict"` // "pass", "fail", "unknown"
	Reason               string              `json:"reason"`
	MissingFamilies      []string            `json:"missing_families,omitempty"`
	MeasuredZeroFamilies []string            `json:"measured_zero_families,omitempty"`
	ResourceChanges      []ResourceChange    `json:"resource_changes,omitempty"`
	PerformanceChanges   []PerformanceChange `json:"performance_changes,omitempty"`
	HistoryRecordKey     string              `json:"history_record_key,omitempty"`
}

ComparisonReceipt certifies the differential analysis and regression verdict.

func CompareExecution

func CompareExecution(plan *ExperimentPlan, exec *ExecutionReceipt, opts ReplayOptions) (*ComparisonReceipt, error)

CompareExecution analyzes completed trial receipts, evaluating differential performance, noise floor significance, missing architectural families, and resource divergence.

type ComparisonSpec

type ComparisonSpec struct {
	Task       string                      `json:"task"`
	Candidate  string                      `json:"candidate"`
	Comparator string                      `json:"comparator"`
	Properties map[string]MeasurementScope `json:"properties"`
}

ComparisonSpec registers a task and two tool arms before measurements exist. Values retain the lower-is-better convention of PropertyMeasurement.

type CompletedCrashTrace

type CompletedCrashTrace struct {
	Identity CrashIdentity
	Complete bool
	MapSize  int
	Bitmap   *timing.EdgeBitmap
}

CompletedCrashTrace is the preceding trial's host trace. Complete must be true only after the caller observed completion. MapSize declares its exact expected size; Bitmap holds raw counters, not quantized hit classes. The caller must not mutate the bitmap while CrashSignature reads it.

type CompoundDataMovement

type CompoundDataMovement = re_obsmodel.CompoundDataMovement

type Confidence

type Confidence = re_obsmodel.Confidence

type Config

type Config struct {
	// Tool selects the checking tool (--tool). Required.
	Tool Tool

	// MissingTool says how an absent compute-sanitizer is handled.
	// Required; see [MissingToolPolicy].
	MissingTool MissingToolPolicy

	// Path is the compute-sanitizer executable. Empty means find
	// [DefaultToolName] the way [LookTool] does: the CUDA toolkit installs
	// [ToolSearchPaths] names, then PATH.
	Path string

	// ErrorExitCode is passed as --error-exitcode. Zero selects
	// [DefaultErrorExitCode], so there is no way to configure the tool's
	// own default of 0, which hides detected errors behind a successful
	// application.
	ErrorExitCode int

	// RequireCUDAInit maps to --require-cuda-init, whose tool default is
	// yes. Note that satisfying it proves only that some CUDA API call was
	// reached, not that the intended kernels ran; use RequireOutput for
	// that.
	RequireCUDAInit Toggle

	// LeakCheck maps to --leak-check: ToggleYes emits "full", ToggleNo
	// emits "no". Leaks reported under "full" count toward the tool's
	// error summary. Meaningful for [Memcheck].
	LeakCheck Toggle

	// TrackUnusedMemory maps to --track-unused-memory. CUDA 12.6 and later
	// spell it as a bare flag: ToggleYes emits it and ToggleNo emits nothing,
	// leaving the tool's default. Earlier releases take yes or no, which [Run]
	// passes when the installed tool does. Meaningful for [Initcheck].
	TrackUnusedMemory Toggle

	// CheckAPIMemoryAccess maps to --check-api-memory-access. Meaningful
	// for [Memcheck].
	CheckAPIMemoryAccess Toggle

	// Kill maps to --kill, which terminates the application on a
	// communication error. It is spelled like [Config.TrackUnusedMemory].
	Kill Toggle

	// NVTX maps to --nvtx, enabling NVTX range support in reports.
	NVTX Toggle

	// RacecheckReport maps to --racecheck-report: "analysis", "hazard" or
	// "all". Meaningful for [Racecheck].
	RacecheckReport string

	// TargetProcesses maps to --target-processes: "application-only" or
	// "all". Use "all" when the program under test spawns the processes
	// that actually touch the GPU.
	TargetProcesses string

	// Demangle maps to --demangle: "full", "simple" or "no".
	Demangle string

	// DestroyOnDeviceError maps to --destroy-on-device-error: "context" or
	// "kernel".
	DestroyOnDeviceError string

	// PrintLimit maps to --print-limit, the maximum number of errors
	// printed per kernel launch. Zero emits no flag.
	PrintLimit int

	// LaunchTimeout maps to --launch-timeout, the tool's own wait for the
	// application to launch. It is rounded down to whole seconds. Zero
	// emits no flag. It bounds the launch only; use [Config.Timeout] to
	// bound the whole run.
	LaunchTimeout time.Duration

	// ExtraArgs are passed to compute-sanitizer ahead of the application.
	// They may not repeat an option this Config already manages; [Run]
	// rejects that rather than emitting the option twice.
	ExtraArgs []string

	// Dir is the working directory for the run. Empty means the current
	// process's directory.
	Dir string

	// Env is the child environment. Nil means the current process's
	// environment. Entries are appended to it in [Main].
	Env []string

	// Stdout and Stderr, when non-nil, receive a copy of the application's
	// output as it is produced. A bounded copy is retained on the [Result]
	// regardless. If a killed process is abandoned unreaped, they may still
	// be written after [RunSanitizer] returns.
	Stdout, Stderr io.Writer

	// RequireOutput lists substrings that must appear in the application's
	// combined output for the run to count as evidence that the intended
	// work executed. A run missing any of them is
	// [OutcomeApplicationFailed]. Matching includes output beyond MaxOutputBytes.
	RequireOutput []string

	// ForbidOutput lists substrings whose presence means the run did not do
	// the intended work, such as a harness warning that nothing ran. A run
	// containing any of them is [OutcomeApplicationFailed], including matches
	// beyond MaxOutputBytes.
	ForbidOutput []string

	// Timeout bounds the whole run. Zero means the run is bounded only by
	// the context passed to [Run]. Whichever deadline comes first applies,
	// and either produces [OutcomeToolFailure], never a pass.
	//
	// One timeout rarely serves every tool. Instrumented cost varies by more
	// than 100x across tools on the same workload; measured on GB10 over one
	// chain of 1<<20 elements and two iterations:
	//
	//	memcheck    2.3s
	//	initcheck   over 300s
	//	racecheck   over 300s
	//
	// racecheck with --report all and initcheck with --track-unused-memory are
	// the expensive ones. A timeout sized for memcheck turns the other two into
	// [OutcomeToolFailure], which is not a pass but is easy to read as one if
	// the caller tests for "not clean"; see [Result.FoundDefect]. Size this per
	// tool, or large enough for the slowest one selected.
	Timeout time.Duration

	// KillDelay bounds waiting for output pipes after the process exits.
	// Cancellation terminates the owned processes immediately; this delay
	// does not postpone that signal. Zero means [DefaultKillDelay].
	KillDelay time.Duration

	// LogDir, when non-empty, is a directory in which the tool's log file
	// is kept after the run and named by [Result.LogPath]. When empty the
	// log is written to a temporary file, read into [Result.Log], and
	// removed.
	LogDir string

	// MaxOutputBytes bounds the retained copy of each of the application's
	// output streams. Zero means [DefaultMaxOutputBytes].
	MaxOutputBytes int

	// Gating selects the trace-abstraction gating mode for trial execution.
	// When unset (zero), trace gating is disabled or uses default runner policy.
	Gating SanitizerGating
}

Config describes one compute-sanitizer invocation.

The zero Config is not usable: Config.Tool and Config.MissingTool must both be set. Every other field has a documented default.

The typed option fields map one-to-one onto compute-sanitizer options and keep the tool's own flag names. Options this package does not model go in Config.ExtraArgs.

func (Config) Args

func (c Config) Args(logFile, prog string, appArgs ...string) ([]string, error)

Args returns the full compute-sanitizer argument vector for running prog with appArgs, writing the tool's report to logFile, as CUDA 12.6 and later spell it. [Run] spells it for the installed tool. The returned slice starts with the compute-sanitizer options, then prog, then appArgs, matching the tool's "compute-sanitizer [options] app [app args]" form. It does not include the executable itself.

Args reports an error for a Config that [Run] would reject. It runs nothing: whether the installed compute-sanitizer accepts these options is Config.CheckOptions's question, because answering it means executing the tool.

Example

The argument vector always carries an explicit nonzero --error-exitcode. compute-sanitizer's own default is 0, which makes a run with detected errors look like a clean one.

package main

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

func main() {
	cfg := diag.Config{
		Tool:            diag.Memcheck,
		MissingTool:     diag.MissingToolFail,
		LeakCheck:       diag.ToggleYes,
		RequireCUDAInit: diag.ToggleYes,
	}
	args, err := cfg.Args("/tmp/report.log", "./vectoradd", "-n", "1024")
	if err != nil {
		panic(err)
	}
	for _, a := range args {
		fmt.Println(a)
	}
}
Output:
--tool
memcheck
--error-exitcode
66
--log-file
/tmp/report.log
--require-cuda-init
yes
--leak-check
full
./vectoradd
-n
1024

func (Config) CheckOptions

func (c Config) CheckOptions(ctx context.Context) error

CheckOptions reports whether the compute-sanitizer this Config resolves to accepts the options the Config would emit, by name and by arity.

It is separate from Config.Args because it runs the tool: resolving the executable and asking it for its version is a subprocess, and Args is a pure function of the Config that a test can call without a toolkit installed. [Run] calls it before starting a run, so a mismatch is reported as a Go error naming the tool and its version rather than as a rejected command line with no report. Callers that build a command line themselves, from Config.Args, can call it directly.

The names in Config.ExtraArgs are checked too, but not their arity: how a caller spells an option this package does not model is the caller's business, while whether the installed tool has that option at all is knowable here.

A Config whose options are all accepted returns nil, and so does one whose tool cannot be resolved or whose capabilities cannot be determined: an executable that reports no version and whose --help cannot be read supports a claim about nothing. [Run] reports a missing tool through Result.Outcome and Config.MissingTool instead.

type ConfusionMatrix

type ConfusionMatrix struct {
	TotalTrials     int                                     `json:"total_trials"`
	WithheldTrials  int                                     `json:"withheld_trials"`
	WithheldReasons map[string]int                          `json:"withheld_reasons"`
	Counts          map[MechanismType]map[MechanismType]int `json:"counts"`
}

ConfusionMatrix computes classification metrics across diagnostic trials, separating valid non-withheld mechanism predictions from withheld trials.

func NewConfusionMatrix

func NewConfusionMatrix() *ConfusionMatrix

NewConfusionMatrix creates an initialized ConfusionMatrix.

func (*ConfusionMatrix) Accuracy

func (cm *ConfusionMatrix) Accuracy() float64

Accuracy computes the classification accuracy across all non-withheld trials.

func (*ConfusionMatrix) FormatReport

func (cm *ConfusionMatrix) FormatReport() string

FormatReport generates a human-readable summary of the confusion matrix, withheld breakdown, and overall accuracy.

func (*ConfusionMatrix) Record

func (cm *ConfusionMatrix) Record(actual, predicted MechanismType, withheldReason string)

Record records one trial outcome. If predicted is MechanismWithheld, it increments the withheld count and records the specific withheld reason. Otherwise, it records the actual vs predicted mechanism classification.

func (*ConfusionMatrix) WithheldFraction

func (cm *ConfusionMatrix) WithheldFraction() float64

WithheldFraction returns the fraction of total trials that were withheld.

type ContextStreamID

type ContextStreamID = re_obsworkload.ContextStreamID

type Control

type Control = re_obsprobe.Control

type Copy

type Copy = re_obsprobe.Copy

type CorrectnessOracle

type CorrectnessOracle struct {
	Method          string  `json:"method"` // "digest-exact" or "numerical-tolerance"
	ExpectedDigest  string  `json:"expected_digest,omitempty"`
	Tolerance       float64 `json:"tolerance,omitempty"`
	ReferencePath   string  `json:"reference_path,omitempty"`
	ReferenceDigest string  `json:"reference_digest,omitempty"`
}

CorrectnessOracle defines how candidate outputs are verified against expectations.

type CorrelationHook

type CorrelationHook = re_obsworkload.CorrelationHook

type CorrelationHookMock

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

CorrelationHookMock provides an in-memory correlation hook for testing external correlation.

func NewCorrelationHookMock

func NewCorrelationHookMock() *CorrelationHookMock

NewCorrelationHookMock creates an initialized CorrelationHookMock.

func (*CorrelationHookMock) Pop

Pop removes and returns the top ID from the caller's goroutine correlation stack.

func (*CorrelationHookMock) Push

Push appends an ID to the caller's goroutine correlation stack.

type CorrelationProvenance

type CorrelationProvenance = re_obsworkload.CorrelationProvenance

type Cost

type Cost = re_obsmodel.Cost

type CostReceipt

type CostReceipt struct {
	BaselineRPS              float64 `json:"baseline_rps"`
	CollectorRPS             float64 `json:"collector_rps"`
	ThroughputDegradationPct float64 `json:"throughput_degradation_pct"`
	BaselineP99LatencyNs     int64   `json:"baseline_p99_latency_ns"`
	CollectorP99LatencyNs    int64   `json:"collector_p99_latency_ns"`
	LatencyP99OverheadPct    float64 `json:"latency_p99_overhead_pct"`
	MemoryGrowthMB           float64 `json:"memory_growth_mb"`
	TotalSubmissions         uint64  `json:"total_submissions"`
	DroppedRecords           uint64  `json:"dropped_records"`
	LossFraction             float64 `json:"loss_fraction"`
	GateDisposition          string  `json:"gate_disposition"`
}

CostReceipt records collection-off versus collection-on paired trial overheads.

type Coster

type Coster = re_obsmodel.Coster

type CosterFunc

type CosterFunc = re_obsmodel.CosterFunc

type Count

type Count = re_obsprobe.Count

type Counter

type Counter = re_obsmodel.Counter

type CrashIdentity

type CrashIdentity struct {
	Kernel  string
	Image   [32]byte
	Epoch   string
	Trial   string
	Input   [32]byte
	Ordinal uint64
}

CrashIdentity identifies one caller-declared trial in an execution epoch. Image and Input are SHA-256 digests of the exact kernel image and input. Ordinal starts at zero and increases once per trial. All strings must be nonempty, printable UTF-8 and at most 1024 bytes. A zero identity is invalid. These declarations are not proof that a device executed the trial.

type CrashObservation

type CrashObservation struct {
	Version     string
	Signature   [32]byte
	TraceDigest [32]byte
	Tool        Tool
	Headlines   []string
	Failure     CrashIdentity
	Preceding   CrashIdentity
}

CrashObservation associates a defect with a preceding completed trace. Signature is a deduplication key, not current or faulting-input coverage. Failure and Preceding retain distinct trial and input identities. Headlines are sorted unique exact report headlines; detail lines and occurrence counts are not part of the key. Version names the signature domain.

func CrashSignature

func CrashSignature(result *Result, preceding CompletedCrashTrace, failure CrashIdentity) (CrashObservation, error)

CrashSignature reports an existing sanitizer defect using the immediately preceding completed trace. It requires FoundDefect and a complete parsed log, refuses other outcomes, and does not execute, gate or skip any work.

The signature hashes a versioned domain, tool, sorted unique exact headlines, kernel/image identity and exact raw trace bytes. Trial/input/epoch identities stay in the observation instead of the key, so identical defect signatures from different trials can be grouped without losing failing-input identity. Adjacency is checked against caller-declared epoch and ordinal; neither this check nor nonzero bytes establish hardware provenance or a live oracle.

Example
package main

import (
	"crypto/sha256"
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/timing"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	m, _ := timing.NewThreadEdgeMap(32, 1)
	m.Record(0, 3) // Caller-supplied host model, not device coverage.
	p := diag.CrashIdentity{Kernel: "kernel", Image: sha256.Sum256([]byte("image")), Epoch: "epoch", Trial: "previous", Input: sha256.Sum256([]byte("previous input"))}
	f := p
	f.Trial, f.Input, f.Ordinal = "failure", sha256.Sum256([]byte("failing input")), 1
	r := &diag.Result{Config: diag.Config{Tool: diag.Memcheck}, Outcome: diag.OutcomeSanitizerErrors, Log: diag.ParseLog("========= Invalid __global__ write of size 4 bytes\n========= ERROR SUMMARY: 1 error\n")}
	observation, err := diag.CrashSignature(r, diag.CompletedCrashTrace{Identity: p, Complete: true, MapSize: 32, Bitmap: m.Snapshot()}, f)
	fmt.Println(observation.Preceding.Trial, observation.Failure.Trial, err)
}
Output:
previous failure <nil>

type DCGMReader

type DCGMReader = re_obsmodel.DCGMReader

type DCGMSample

type DCGMSample = re_obsmodel.DCGMSample

type Decision

type Decision struct {
	Type       DecisionType     `json:"type"`
	Parameters map[string]int64 `json:"parameters,omitempty"`
	Reason     string           `json:"reason"`
}

Decision represents the proposed action, parameters, and rationale.

type DecisionType

type DecisionType string

DecisionType specifies the proposed policy action.

const (
	// DecisionBypass skips custom policy and uses default driver behavior.
	DecisionBypass DecisionType = "bypass"
	// DecisionProtect moves chunk to tail to protect it from eviction.
	DecisionProtect DecisionType = "protect"
	// DecisionEvict marks chunk for early eviction (e.g. move to head).
	DecisionEvict DecisionType = "evict"
	// DecisionPrefetch triggers asynchronous page prefetch for a target range.
	DecisionPrefetch DecisionType = "prefetch"
	// DecisionThrottle suppresses prefetching or evictions under contention.
	DecisionThrottle DecisionType = "throttle"
	// DecisionTimeslice sets the timeslice duration for a scheduling channel.
	DecisionTimeslice DecisionType = "timeslice"
	// DecisionSkip executes no action.
	DecisionSkip DecisionType = "skip"
	// DecisionReject explicitly rejects an unsupported or invalid input.
	DecisionReject DecisionType = "reject"
)

type DemangleReceipt

type DemangleReceipt = re_obsprobe.DemangleReceipt

type Demangler

type Demangler = re_obsprobe.Demangler

type DemonstrationConfig

type DemonstrationConfig struct {
	NumRequests int           `json:"num_requests"`
	Concurrency int           `json:"concurrency"`
	HostDelay   time.Duration `json:"host_delay"`
	DeviceDelay time.Duration `json:"device_delay"`
	// OutputDir retains captures and trial closure, including the executing host
	// binary. When empty, temporary closure files are removed before return;
	// returned file references then cannot reconstruct a later replay.
	OutputDir         string `json:"output_dir"`
	SkipIntervention  bool   `json:"skip_intervention,omitempty"`
	ExerciseCorruptEv bool   `json:"exercise_corrupt_ev,omitempty"`
	ExercisePressure  bool   `json:"exercise_pressure,omitempty"`
}

DemonstrationConfig configures the end-to-end demonstration.

func DefaultDemonstrationConfig

func DefaultDemonstrationConfig() DemonstrationConfig

DefaultDemonstrationConfig returns balanced demonstration defaults.

type DemonstrationResult

type DemonstrationResult struct {
	// Qualification records the evidence scope; this fixture is not native qualification.
	Qualification        string                  `json:"qualification"`
	Synthetic            bool                    `json:"synthetic"`
	AttributionMetrics   obsworkload.JoinMetrics `json:"attribution_metrics"`
	AttributionAccuracy  float64                 `json:"attribution_accuracy"`
	ConfusionMatrix      ConfusionMatrix         `json:"confusion_matrix"`
	BaselineDiagnosis    DiagnosisResult         `json:"baseline_diagnosis"`
	HostDelayDiagnosis   DiagnosisResult         `json:"host_delay_diagnosis"`
	DeviceBottleneckDiag DiagnosisResult         `json:"device_bottleneck_diagnosis"`
	WithheldDiagnosis    DiagnosisResult         `json:"withheld_diagnosis"`
	IncidentReceipt      *iket.IncidentReceipt   `json:"incident_receipt,omitempty"`
	TrialPlan            *ExperimentPlan         `json:"trial_plan,omitempty"`
	PlanReceipt          *PlanReceipt            `json:"plan_receipt,omitempty"`
	TrialExecution       *ExecutionReceipt       `json:"trial_execution,omitempty"`
	TrialComparison      *ComparisonReceipt      `json:"trial_comparison,omitempty"`
	ArtifactFiles        map[string]string       `json:"artifact_files,omitempty"`
	CollectionCost       CollectionCostReport    `json:"collection_cost"`
	// DiagnosticInputs are decoded from retained capture artifacts, independently
	// of GroundTruth. CaptureSHA256 binds each input to its containing bundle.
	DiagnosticInputs map[string]DiagnosticInput `json:"diagnostic_inputs"`
	CaptureSHA256    map[string]string          `json:"capture_sha256"`
	// CaptureBundles retains the raw portable evidence for export/replay. It is
	// omitted from summary JSON; hashes and diagnostic inputs remain visible.
	CaptureBundles    map[string][]byte  `json:"-"`
	ReplayTimings     []SubmissionTiming `json:"replay_timings,omitempty"`
	PressureDiagnosis *DiagnosisResult   `json:"pressure_diagnosis,omitempty"`
	// PhaseVerification checks one actually executed pair using the distinct
	// pre-entry metric. TrialExecution separately records the full protocol.
	PhaseVerification      *tracecontract.InterventionReceipt `json:"phase_verification,omitempty"`
	PhaseVerificationError string                             `json:"phase_verification_error,omitempty"`
}

DemonstrationResult holds the complete evaluation, diagnostics, trials, and receipts.

type Derivation

type Derivation = re_obsmodel.Derivation

type DeviceActivity

type DeviceActivity = re_obsworkload.DeviceActivity

type DeviceConfig

type DeviceConfig struct {
	DeviceIndex         int    `json:"device_index"`
	DeviceUUID          string `json:"device_uuid,omitempty"`
	Model               string `json:"model,omitempty"`
	ComputeCapability   string `json:"compute_capability,omitempty"`
	DriverVersion       string `json:"driver_version,omitempty"`
	CUDAVersion         string `json:"cuda_version,omitempty"`
	TargetClockMHz      int    `json:"target_clock_mhz,omitempty"`
	PowerLimitWatts     int    `json:"power_limit_watts,omitempty"`
	MIGMode             string `json:"mig_mode,omitempty"`
	RequireHardwareLock bool   `json:"require_hardware_lock"`
}

DeviceConfig specifies target GPU hardware requirements and operating modes.

type DeviceRecord

type DeviceRecord = re_obsmodel.DeviceRecord

type DiagnosisResult

type DiagnosisResult struct {
	Workload       obsworkload.WorkloadIdentity `json:"workload"`
	OpID           obsworkload.OpID             `json:"op_id"`
	Mechanism      MechanismType                `json:"mechanism"`
	TimeAccounting TimeAccounting               `json:"time_accounting"`
	// HostTimingBasis is pre_entry for application timing, otherwise empty for
	// the legacy API/scheduler rule. It binds intervention verification.
	HostTimingBasis string                  `json:"host_timing_basis,omitempty"`
	PrimaryFinding  tracecontract.Finding   `json:"primary_finding"`
	Findings        []tracecontract.Finding `json:"findings"`
	Admitted        bool                    `json:"admitted"`
	WithheldReason  string                  `json:"withheld_reason,omitempty"`
}

DiagnosisResult records the outcome of an evidence-admitted mechanism diagnosis.

func Diagnose

Diagnose evaluates diagnostic rules deterministically against provided evidence. It hides any synthetic injection labels and bases conclusions strictly on admitted evidence.

type DiagnosticInput

type DiagnosticInput struct {
	WallInterval tracecontract.Interval
	HostCalls    []HostCallEvent
	// PreEntries opts into application pre-entry timing. The bounded contract
	// admits one complete operation and API pair; no scheduler state is inferred.
	PreEntries   []PreEntryEvent
	Kernels      []KernelEvent
	Sched        SchedEvidence
	PowerClock   PowerClockEvidence
	Receipt      tracecontract.Receipt
	Intervention *tracecontract.InterventionReceipt
	Thresholds   Thresholds
}

DiagnosticInput encapsulates all primary observations and contracts required for diagnosis.

func CreateDiagnosticInput

func CreateDiagnosticInput(
	wall tracecontract.Interval,
	hostCalls []HostCallEvent,
	kernels []KernelEvent,
	sched SchedEvidence,
	thresh Thresholds,
) DiagnosticInput

CreateDiagnosticInput constructs legacy synthetic protocol inputs. Its gates and coverage are fixture declarations, not captured observations. Production demonstration inputs are decoded from the returned recorder bundle instead.

type DiagnosticReceipt

type DiagnosticReceipt struct {
	HeldOutTotal       int             `json:"held_out_total"`
	HeldOutCorrect     int             `json:"held_out_correct"`
	HeldOutWithheld    int             `json:"held_out_withheld"`
	HeldOutIncorrect   int             `json:"held_out_incorrect"`
	HeldOutMissing     int             `json:"held_out_missing"`
	NoFaultTotal       int             `json:"no_fault_total"`
	NoFaultPassed      int             `json:"no_fault_passed"`
	NoFaultWithheld    int             `json:"no_fault_withheld"`
	NoFaultMissing     int             `json:"no_fault_missing"`
	CompetingTotal     int             `json:"competing_total"`
	CompetingDiverted  int             `json:"competing_diverted"`
	CompetingWithheld  int             `json:"competing_withheld"`
	CompetingMissing   int             `json:"competing_missing"`
	ResilienceTotal    int             `json:"resilience_total"`
	ResiliencePassed   int             `json:"resilience_passed"`
	ResilienceWithheld int             `json:"resilience_withheld"`
	ResilienceMissing  int             `json:"resilience_missing"`
	AccuracyPct        float64         `json:"accuracy_pct"`
	ConfusionMatrix    map[string]int  `json:"confusion_matrix"`
	GateDisposition    string          `json:"gate_disposition"`
	SampleDiagnosis    DiagnosisResult `json:"sample_diagnosis,omitempty"`
}

DiagnosticReceipt summarizes causal mechanism inference on held-out faults. Counts are ground-truth cases. A Missing count is the number of cases in the matching Total that had no diagnostic input; such cases never pass. Zero means no input was missing. A Withheld count is the number of cases in the matching Total whose input was present but whose diagnosis cudadiag withheld or did not admit. Withholding a held-out, no-fault or competing case is not success: HeldOutWithheld, NoFaultWithheld and CompetingWithheld are disjoint from HeldOutCorrect, NoFaultPassed and CompetingDiverted. ResilienceWithheld is narrower: it counts only withheld outcomes that fail their mode's safety predicate, described below. A withheld resilience outcome that its mode's evidence supports is a safe refusal and is counted only in ResiliencePassed.

HeldOutCorrect, HeldOutWithheld, HeldOutIncorrect and HeldOutMissing partition HeldOutTotal.

NoFaultTotal counts no-fault cases with normal resilience. NoFaultPassed counts admitted diagnoses of exactly [cudadiag.MechanismNoFault]. NoFaultPassed, NoFaultWithheld and NoFaultMissing are disjoint; the rest of NoFaultTotal is admitted false alarms. Withheld diagnoses never pass. NoFaultPassed/NoFaultTotal is correctness over all declared cases; (NoFaultTotal-NoFaultWithheld-NoFaultMissing)/NoFaultTotal is diagnostic coverage. Specificity among admitted answers uses that admitted count as its denominator and is undefined when no answers were admitted.

CompetingDiverted counts competing device bottleneck cases diagnosed as exactly [cudadiag.MechanismDeviceBottleneck] and admitted; only these pass. CompetingDiverted, CompetingWithheld and CompetingMissing are disjoint, and the rest of CompetingTotal is the competing cases misclassified as another admitted mechanism.

ResilienceTotal counts cases with a resilience mode other than ResilienceNormal. A case is judged by its own diagnostic input and by the join results that carry its process generation and native correlation ID; no association is inferred from time, stream or thread. A buffer overflow case passes only if its receipt reports dropped activity records and its diagnosis was withheld. A process restart case passes only if its scheduler evidence names a later generation of the same process, its diagnosis was withheld for identity mismatch, and the joins report the request only as missing or ambiguous. A late attach case passes only if its receipt declares an activity coverage gap or unknown activity loss, its diagnosis was withheld by activity admission for unknown loss, and the joins report the request only as missing or ambiguous; withholding for scheduler evidence or measured activity loss does not count. The joins prove nothing when any record of the run expired from the joiner's bounded queue, and then no restart or late attach case passes. No other mode passes. A pass is a safe refusal, not a successful diagnosis or a complete population, and never counts toward the no-fault counts. ResilienceWithheld counts the cases whose diagnosis was withheld but that do not pass. ResiliencePassed, ResilienceWithheld and ResilienceMissing are disjoint; the rest of ResilienceTotal fails its mode's predicate. Passing on fixture output shows only that the fixture, joiner and evaluator agree; it does not qualify a live collector across a real restart or attach.

type DifferentialReport

type DifferentialReport struct {
	Phase              CmpPhase
	Family             string
	Availability       Availability // Observation status across comparison arms
	Available          bool         // true only when observed in both arms
	CObserved          bool         // true if observed in C baseline
	GoObserved         bool         // true if observed in Go candidate
	CDurationNs        int64        // C baseline device execution duration (or Unmeasured)
	GoDurationNs       int64        // Go candidate device execution duration (or Unmeasured)
	DeltaNs            int64        // Go - C duration in nanoseconds (or Unmeasured)
	Speedup            float64      // C / Go speedup factor
	LaunchDeltaNs      int64        // Host launch overhead difference (only computed when Available is true)
	NullDriftNs        int64        // Noise floor from null control basket
	ExceedsDrift       bool         // true if |DeltaNs| > NullDriftNs (only computed when Available is true)
	StatisticallyValid bool         // true if ExceedsDrift is true; exceeding drift threshold alone does not establish statistical validity
	RooflineGo         *obsmodel.KernelPoint
	RooflineC          *obsmodel.KernelPoint
}

DifferentialReport records comparison metrics for one architectural family within a phase.

func CompareCaptures

func CompareCaptures(cCap, goCap *obsmodel.CensusCapture, coster obsmodel.Coster, fc *FamilyClassifier, nullDriftNs int64, model *obsmodel.Model) ([]DifferentialReport, error)

CompareCaptures extracts phases from cCap and goCap, compares them, and returns differential reports for prefill and decode.

func ComparePhases

func ComparePhases(cPhase, goPhase PhaseCensus, nullDriftNs int64, model *obsmodel.Model) ([]DifferentialReport, error)

ComparePhases compares two PhaseCensus instances of the same phase and computes DifferentialReport entries across all architectural families. It returns an error if the phases are incompatible or inputs are invalid.

func (DifferentialReport) CDuration

func (r DifferentialReport) CDuration() time.Duration

CDuration returns the C baseline device execution duration, or Unmeasured if unavailable.

func (DifferentialReport) Delta

func (r DifferentialReport) Delta() time.Duration

Delta returns the duration difference (Go - C), or Unmeasured if unavailable.

func (DifferentialReport) GoDuration

func (r DifferentialReport) GoDuration() time.Duration

GoDuration returns the Go candidate device execution duration, or Unmeasured if unavailable.

type Domain

type Domain string
const (
	// DomainEviction represents UVM physical memory page/chunk eviction policy.
	DomainEviction Domain = "eviction"
	// DomainPrefetch represents UVM page prefetch policy.
	DomainPrefetch Domain = "prefetch"
	// DomainScheduling represents GPU compute channel and timeslice scheduling policy.
	DomainScheduling Domain = "scheduling"
	// DomainPTXInstrument represents dynamic PTX instrumentation policy.
	DomainPTXInstrument Domain = "ptx_instrument"
)

type Engine

type Engine struct {
	Thresholds Thresholds
}

Engine encapsulates evidence-admitted diagnostic mechanism evaluation.

func NewEngine

func NewEngine(thresh Thresholds) *Engine

NewEngine creates an Engine with specified thresholds.

func (*Engine) Diagnose

Diagnose evaluates primary evidence deterministically against admitted contracts.

type Entry

type Entry = re_obsmodel.Entry

type Environment

type Environment struct {
	DeviceIndex       int    `json:"device_index"`
	DeviceUUID        string `json:"device_uuid,omitempty"`
	Model             string `json:"model,omitempty"`
	ComputeCapability string `json:"compute_capability,omitempty"`
	Driver            string `json:"driver,omitempty"`
	CUDA              string `json:"cuda,omitempty"`
	Clock             string `json:"clock,omitempty"`
	Domain            string `json:"domain,omitempty"`
	HostArch          string `json:"host_arch,omitempty"`
	KernelVersion     string `json:"kernel_version,omitempty"`
}

type EnvironmentCheck

type EnvironmentCheck struct {
	SourceClosure          QualificationClosure      `json:"source_closure"`
	LeaseArtifact          RegistrationArtifact      `json:"lease_artifact"`
	ClockBounds            []AcquisitionBounds       `json:"clock_bounds"`
	ObserverContractDigest string                    `json:"observer_contract_digest"`
	ObserverPhase          *ObserverPhaseAcquisition `json:"observer_phase,omitempty"`
	WorkloadContractDigest string                    `json:"workload_contract_digest"`
}

EnvironmentCheck retains explicit bounded evidence identities, not acquisition authority.

type EscalateOptions

type EscalateOptions struct {
	OutputDir            string
	TestName             string
	PackageName          string
	Source               string
	Inputs               []uint64
	Shape                []uint64
	Grid                 [3]uint32
	Block                [3]uint32
	SharedMem            uint32
	Repeats              int
	DetectionProbability float64
	MaxAttempts          int
	AllowOneOff          bool
	Replay               func(context.Context, Case) (cudaschedule.RunRecord, error)
	Finding              *cudaschedule.SeedResult
	Reproducer           *iket.Reproducer
}

EscalateOptions configures escalation to a standalone reproducer package.

type Estimate

type Estimate = re_obsmodel.Estimate

type EvalConfig

type EvalConfig struct {
	BatchSize         int
	Iterations        int
	Concurrency       int
	ExerciseStress    bool
	InjectedSeed      int64
	SimulateCostTrial bool
}

EvalConfig controls options for running an evaluation.

func DefaultEvalConfig

func DefaultEvalConfig() EvalConfig

DefaultEvalConfig returns recommended evaluation runner settings.

type EvalPhase

type EvalPhase string

Phase defines the stage of protocol execution.

const (
	// PhasePilot explores feasible budgets and system behaviors.
	// Results from PhasePilot are not admissible as qualification evidence.
	PhasePilot EvalPhase = "pilot"

	// PhaseQualification executes the frozen protocol against held-out evidence.
	PhaseQualification EvalPhase = "qualification"
)

type EvaluationReport

type EvaluationReport struct {
	// Synthetic indicates fixture-generated evidence rather than native capture.
	Synthetic       bool                   `json:"synthetic"`
	Protocol        Protocol               `json:"protocol"`
	Timestamp       time.Time              `json:"timestamp"`
	Duration        time.Duration          `json:"duration"`
	Baselines       []Baseline             `json:"baselines"`
	Attribution     AttributionReceipt     `json:"attribution"`
	Diagnostic      DiagnosticReceipt      `json:"diagnostic"`
	Cost            CostReceipt            `json:"cost"`
	Reproducibility ReproducibilityReceipt `json:"reproducibility"`
	Gates           []PropertyGate         `json:"gates"`
	Passed          bool                   `json:"passed"`
	Claim           *Claim                 `json:"claim,omitempty"`
}

EvaluationReport contains full receipts across all four evaluation properties.

func RunEvaluation

func RunEvaluation(ctx context.Context, proto Protocol, cfg EvalConfig) (*EvaluationReport, error)

RunEvaluation executes the full independent evaluation suite against a protocol.

func (*EvaluationReport) AllGates

func (r *EvaluationReport) AllGates() []PropertyGate

AllGates returns all recorded property gates including passes, failures, and withheld gates.

type Evaluator

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

Evaluator manages shadow policy evaluation, freshness checks, sequence ordering, and bounded snapshot recording.

func NewEvaluator

func NewEvaluator(capacity int) (*Evaluator, error)

NewEvaluator creates a new Evaluator with a bounded snapshot capacity. Capacity must be greater than zero.

func (*Evaluator) Evaluate

func (e *Evaluator) Evaluate(ctx context.Context, pol Policy, in Input) (Snapshot, error)

Evaluate records proposed decisions. The evaluator never executes them. Policy implementations are caller code and must themselves be observational.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"time"
)

func main() {
	eval, err := diag.NewEvaluator(10)
	if err != nil {
		fmt.Printf("new evaluator error: %v\n", err)
		return
	}
	eval.SetClock(func() int64 { return 5000 })

	pol, err := diag.NewFIFOPolicy(diag.PolicyInfo{
		Name:    "gpu_ext-fifo",
		Version: "1.0.0",
		Domain:  diag.DomainEviction,
	})
	if err != nil {
		fmt.Printf("new policy error: %v\n", err)
		return
	}

	ctx := context.Background()

	// 1. Activate chunk 0x1000
	snap1, err := eval.Evaluate(ctx, pol, diag.Input{
		Provenance: diag.ShadowProvenance{
			DeviceID:      0,
			DriverVersion: "575.57.08",
			KernelModule:  "nvidia-uvm.ko",
			Hook:          diag.HookBlockActivate,
			Sequence:      1,
			TimestampNano: 1000,
			TTL:           time.Second,
		},
		Domain:   diag.DomainEviction,
		Eviction: &diag.EvictionData{ChunkAddr: 0x1000},
	})
	if err != nil {
		fmt.Printf("eval 1 error: %v\n", err)
		return
	}

	// 2. Access chunk 0x1000
	snap2, err := eval.Evaluate(ctx, pol, diag.Input{
		Provenance: diag.ShadowProvenance{
			DeviceID:      0,
			DriverVersion: "575.57.08",
			KernelModule:  "nvidia-uvm.ko",
			Hook:          diag.HookBlockAccess,
			Sequence:      2,
			TimestampNano: 2000,
			TTL:           time.Second,
		},
		Domain:   diag.DomainEviction,
		Eviction: &diag.EvictionData{ChunkAddr: 0x1000},
	})
	if err != nil {
		fmt.Printf("eval 2 error: %v\n", err)
		return
	}

	// 3. Prepare eviction: FIFO targets oldest chunk (0x1000)
	snap3, err := eval.Evaluate(ctx, pol, diag.Input{
		Provenance: diag.ShadowProvenance{
			DeviceID:      0,
			DriverVersion: "575.57.08",
			KernelModule:  "nvidia-uvm.ko",
			Hook:          diag.HookEvictPrepare,
			Sequence:      3,
			TimestampNano: 3000,
			TTL:           time.Second,
		},
		Domain:   diag.DomainEviction,
		Eviction: &diag.EvictionData{},
	})
	if err != nil {
		fmt.Printf("eval 3 error: %v\n", err)
		return
	}

	fmt.Printf("activate decision: %s (status: %s)\n", snap1.Decision.Type, snap1.Status)
	fmt.Printf("access decision: %s (status: %s)\n", snap2.Decision.Type, snap2.Status)
	fmt.Printf("evict decision: %s on 0x%x (status: %s)\n",
		snap3.Decision.Type, snap3.Decision.Parameters["target_chunk"], snap3.Status)

}
Output:
activate decision: bypass (status: valid)
access decision: bypass (status: valid)
evict decision: evict on 0x1000 (status: valid)

func (*Evaluator) RecordOutcome

func (e *Evaluator) RecordOutcome(snapshotID string, outcome ObservedOutcome) error

RecordOutcome updates a previously recorded snapshot with the observed outcome from baseline execution.

func (*Evaluator) Replay

func (e *Evaluator) Replay(ctx context.Context, pol Policy, history []Snapshot) ([]Snapshot, error)

Replay re-evaluates a sequence of recorded snapshots against the policy, asserting deterministic reproduction of decisions.

Like WriteHistory, Replay refuses a history with more than 4096 snapshots, an invalid snapshot, or a compact encoding over 16 MiB before it copies any snapshot or calls the policy. Because every snapshot is validated first, an invalid snapshot is reported ahead of a cancellation, policy identity mismatch, ordering error or evaluation failure at any step. A policy error takes precedence over cancellation during that call. If the policy succeeds, cancellation is checked before accepting its decision. Returned snapshots are independent of both history and policy result maps.

func (*Evaluator) SetClock

func (e *Evaluator) SetClock(fn func() int64)

SetClock sets a custom clock in the same domain as input timestamps. The default clock and TimestampNano use Unix nanoseconds.

func (*Evaluator) Snapshots

func (e *Evaluator) Snapshots() []Snapshot

Snapshots returns an ordered slice of all currently buffered snapshots.

func (*Evaluator) TotalEvaluated

func (e *Evaluator) TotalEvaluated() uint64

TotalEvaluated returns the cumulative count of evaluated inputs.

type Event

type Event = re_obsprobe.Event

type EvictionData

type EvictionData struct {
	PID         int    `json:"pid"`
	ChunkAddr   uint64 `json:"chunk_addr"`
	ChunkSize   uint64 `json:"chunk_size"`
	VABlockAddr uint64 `json:"va_block_addr"`
	AccessCount uint64 `json:"access_count"`
}

EvictionData holds UVM chunk access/eviction input parameters.

type EvidenceAcceptance

type EvidenceAcceptance interface {
	Check(context.Context, EvidenceRequest) (EvidenceDecision, error)
}

EvidenceAcceptance is caller-configured independent acceptance policy. Receipt content cannot choose this provider. Implementations own their blocking behavior; returned Record ownership transfers even on an error.

type EvidenceAuthority

type EvidenceAuthority struct {
	AuthorityID           string   `json:"authority_id"`
	AuthorityPolicyDigest string   `json:"authority_policy_digest"`
	AuthorityConfigDigest string   `json:"authority_config_digest"`
	AllowedProfiles       []string `json:"allowed_profiles"`
}

EvidenceAuthority retains explicit bounded evidence identities, not acquisition authority.

type EvidenceBinding

type EvidenceBinding struct {
	Role           string                 `json:"role"`
	DecoderProfile string                 `json:"decoder_profile"`
	Artifacts      []RegistrationArtifact `json:"artifacts"`
	Scope          EvidenceScope          `json:"scope"`
	State          string                 `json:"state"`
	Reason         string                 `json:"reason"`
	Owner          string                 `json:"owner"`
	NextAction     string                 `json:"next_action"`
}

EvidenceBinding retains explicit bounded evidence identities, not acquisition authority.

type EvidenceDecision

type EvidenceDecision struct {
	Version                int             `json:"version"`
	RequestDigest          string          `json:"request_digest"`
	AuthorityID            string          `json:"authority_id"`
	AuthorityPolicyDigest  string          `json:"authority_policy_digest"`
	AuthorityConfigDigest  string          `json:"authority_config_digest"`
	AcceptanceRecordDigest string          `json:"acceptance_record_digest"`
	Disposition            string          `json:"disposition"`
	ScopedRoleDecisions    []ScopeDecision `json:"scoped_role_decisions"`
	Reason                 string          `json:"reason"`
	Owner                  string          `json:"owner"`
	NextAction             string          `json:"next_action"`
	Record                 io.ReadCloser   `json:"-"`
}

EvidenceDecision retains explicit bounded evidence identities, not acquisition authority.

type EvidenceIdentity

type EvidenceIdentity = re_obsmodel.EvidenceIdentity

type EvidenceJudgment

type EvidenceJudgment = re_obsmodel.EvidenceJudgment

type EvidenceOutcome

type EvidenceOutcome = re_obsmodel.EvidenceOutcome

type EvidenceRecord

type EvidenceRecord = re_obsmodel.EvidenceRecord

type EvidenceRequest

type EvidenceRequest struct {
	Version             int                    `json:"version"`
	RegistrationDigest  string                 `json:"registration_digest"`
	ProtocolDigest      string                 `json:"protocol_digest"`
	LedgerDigest        string                 `json:"ledger_digest"`
	PairDigest          string                 `json:"pair_digest"`
	CandidateRawDigest  string                 `json:"candidate_raw_digest"`
	ComparatorRawDigest string                 `json:"comparator_raw_digest"`
	Task                string                 `json:"task"`
	CandidateTool       ToolSpec               `json:"candidate_tool"`
	ComparatorTool      ToolSpec               `json:"comparator_tool"`
	Authority           EvidenceAuthority      `json:"authority"`
	SelectedCells       []SelectedCellIdentity `json:"selected_cells"`
	Roles               []EvidenceScope        `json:"roles"`
	ArmValues           []ArmValue             `json:"arm_values"`
	MatchedResults      []MatchedResult        `json:"matched_results"`
	RequestDigest       string                 `json:"request_digest"`
}

EvidenceRequest retains explicit bounded evidence identities, not acquisition authority.

type EvidenceRun

type EvidenceRun = re_obsmodel.EvidenceRun

type EvidenceScope

type EvidenceScope struct {
	ScopeID              string   `json:"scope_id"`
	Role                 string   `json:"role"`
	DecoderProfile       string   `json:"decoder_profile"`
	Arm                  string   `json:"arm"`
	TargetID             string   `json:"target_id"`
	CellID               string   `json:"cell_id"`
	CapabilityID         string   `json:"capability_id"`
	Gate                 string   `json:"gate"`
	ClosureDigest        string   `json:"closure_digest"`
	LatestReceiptDigest  string   `json:"latest_receipt_digest"`
	Property             string   `json:"property"`
	PopulationFamily     string   `json:"population_family"`
	Unit                 string   `json:"unit"`
	Denominator          uint64   `json:"denominator"`
	TimingFamily         string   `json:"timing_family"`
	ClockDomain          string   `json:"clock_domain"`
	ClockEpoch           string   `json:"clock_epoch"`
	RangeStart           int64    `json:"range_start"`
	RangeEnd             int64    `json:"range_end"`
	MethodArtifactDigest string   `json:"method_artifact_digest"`
	ArtifactDigests      []string `json:"artifact_digests"`
	DecodeStatus         string   `json:"decode_status"`
	ExperimentPhase      string   `json:"experiment_phase"`
}

EvidenceScope retains explicit bounded evidence identities, not acquisition authority.

type EvidenceSource

type EvidenceSource = re_obsmodel.EvidenceSource

type EvidenceValue

type EvidenceValue = re_obsmodel.EvidenceValue

func OccupancyValue

func OccupancyValue(k sass.KernelResource, source EvidenceSource, threads, dynamicShared int, resourcesKnown bool) (EvidenceValue, error)

OccupancyValue derives a theoretical occupancy ceiling from compiled resources and launch geometry. ResourcesKnown must describe all required resource metadata; absent metadata is not an observed zero allocation.

func PeakGPRValue

func PeakGPRValue(pressure map[string]map[uint64]sass.RegisterPressure, source EvidenceSource) (EvidenceValue, error)

PeakGPRValue derives peak live GPR count from sass.ParseLifeRangeCount output. Only the exact entry is admitted. A missing or empty map is unavailable; a present zero count remains a real derived zero. This is not an allocated register count or compiler spill proof.

type EvidenceVerdict

type EvidenceVerdict = re_obsmodel.EvidenceVerdict

type ExecutionReceipt

type ExecutionReceipt struct {
	ExecutionID         string            `json:"execution_id"`
	PlanID              string            `json:"plan_id"`
	PlanDigest          string            `json:"plan_digest"`
	ParentPlanDigest    string            `json:"parent_plan_digest,omitempty"`
	StartedAt           time.Time         `json:"started_at"`
	FinishedAt          time.Time         `json:"finished_at"`
	EnvironmentObserved Environment       `json:"environment_observed"`
	WarmupRunsCompleted int               `json:"warmup_runs_completed"`
	RoundsCompleted     int               `json:"rounds_completed"`
	ArmReceipts         []timing.Receipt  `json:"arm_receipts"`
	NullControlReceipts []timing.Receipt  `json:"null_control_receipts"`
	NullDrift           time.Duration     `json:"null_drift"`
	OutputsVerified     bool              `json:"outputs_verified"`
	OutputDigests       map[string]string `json:"output_digests"`
	Partial             bool              `json:"partial"`
	HaltReason          string            `json:"halt_reason,omitempty"`
}

ExecutionReceipt certifies the execution of an ExperimentPlan across rounds.

ParentPlanDigest is copied from the executed plan as claimed. It is authenticated when Replay derives the plan itself on environment drift, but not when the caller supplies an already derived plan; use VerifyDerivation to check such a plan against its parent.

type ExecutionSpec

type ExecutionSpec struct {
	Version          int               `json:"version"`
	PlanID           string            `json:"plan_id"`
	PlanDigest       string            `json:"plan_digest"`
	SpecDigest       string            `json:"spec_digest"`
	Mode             string            `json:"mode"`
	WorkingDirectory string            `json:"working_directory"`
	Environment      map[string]string `json:"environment"`
	TimeoutNanos     int64             `json:"timeout_nanos"`
	MaxOutputBytes   int               `json:"max_output_bytes"`
	Baseline         CommandArm        `json:"baseline"`
	Candidate        CommandArm        `json:"candidate"`
	Inputs           []CommandArtifact `json:"inputs"`
	Libraries        []CommandArtifact `json:"libraries"`
}

ExecutionSpec fully declares the executable, input closure, and child environment for a replay. Its digest is SHA-256 of its canonical JSON with SpecDigest empty.

func ReadExecutionSpec

func ReadExecutionSpec(r io.Reader) (ExecutionSpec, error)

ReadExecutionSpec reads one bounded, exact-schema JSON spec.

type ExperimentPlan

type ExperimentPlan struct {
	Version             int                          `json:"version"`
	PlanID              string                       `json:"plan_id"`
	PlanDigest          string                       `json:"plan_digest"`
	ParentPlanDigest    string                       `json:"parent_plan_digest,omitempty"`
	DerivationRationale string                       `json:"derivation_rationale,omitempty"`
	IncidentID          string                       `json:"incident_id"`
	IncidentDigest      string                       `json:"incident_digest"`
	Workload            obsworkload.WorkloadIdentity `json:"workload"`
	SourceArtifacts     []ArtifactRef                `json:"source_artifacts"`
	BinaryArtifacts     []ArtifactRef                `json:"binary_artifacts"`
	LibraryClosure      []LibraryRef                 `json:"library_closure"`
	Inputs              []InputRef                   `json:"inputs"`
	CorrectnessOracle   CorrectnessOracle            `json:"correctness_oracle"`
	TimingScope         TimingScope                  `json:"timing_scope"`
	DeviceConfig        DeviceConfig                 `json:"device_config"`
	CaptureConfig       CaptureConfig                `json:"capture_config"`
	ExecutionOrder      string                       `json:"execution_order"` // "ABBA"
	WarmupRuns          int                          `json:"warmup_runs"`
	Rounds              int                          `json:"rounds"`
	NullControls        NullControlConfig            `json:"null_controls"`
	StoppingRules       RegressStoppingRules         `json:"stopping_rules"`
}

ExperimentPlan is a bounded, fully specified, replayable experiment.

A root plan, made by NewPlanFromIncident, has empty ParentPlanDigest and DerivationRationale. A plan made by DerivePlan has both set. Both fields are covered by PlanDigest; they are omitted from the digest input when empty, so the digest of a root plan is unchanged by their presence.

ValidatePlan checks only the shape of the lineage fields: both or neither set, and a well-formed parent digest. It cannot tell whether the named parent exists or whether this plan was derived from it; only VerifyDerivation, given the parent, authenticates the lineage.

func DerivePlan

func DerivePlan(parent *ExperimentPlan, newEnv Environment, rationale string) (*ExperimentPlan, error)

DerivePlan returns a new plan that differs from parent only in the device fields taken from newEnv and in its lineage: the derived plan records parent's PlanDigest as ParentPlanDigest and rationale as DerivationRationale. It is used to rerun an experiment under an intentional environment change, such as a different GPU model.

DerivePlan refuses a parent that fails ValidatePlan and an empty rationale. The derived plan shares no memory with parent. Its PlanID is computed from parent's PlanID and PlanDigest, the rationale, and the new device fields, so deriving twice from the same inputs yields the same plan.

type ExportOptions

type ExportOptions struct {
	// RunnerPath names a source-reviewed executable implementing the request and
	// response protocol in the exported reproducer_test.go. It receives preserved
	// Case and kernel bytes on stdin; no shell or inferred CUDA ABI is used.
	// Its receipt assertions do not establish native qualification.
	RunnerPath     string
	RunnerSHA256   string        // SHA-256 of the exact caller-supplied executable.
	AttemptTimeout time.Duration // Per-process deadline; zero uses 30 seconds.

	PackageName          string  // Package name for generated test files (defaults to "reproducer").
	Repeats              int     // Declared baseline replay count R.
	DetectionProbability float64 // Target detection probability for nondeterministic findings (e.g. 0.99).
	MaxAttempts          int     // Bound on test attempts.
	OracleRequired       bool    // Require lane 52 memory/access violation oracle.
	OraclePatch          string  // Oracle identifier or patch name (e.g. "lane52-memcheck").
}

ExportOptions configures standalone Go test package export.

type ExportResult

type ExportResult struct {
	OutputDir   string
	PackageName string
	TestName    string
	Case        Case
	Reduction   Reduction
	Finding     cudaschedule.SeedResult
	Reproducer  *iket.Reproducer
}

ExportResult records the outcome of an escalation export.

func EscalateBundle

func EscalateBundle(ctx context.Context, bundle *iket.Bundle, opts EscalateOptions) (*ExportResult, error)

EscalateBundle validates the bundle's reproducer manifest and exports a reproducer package.

func EscalateDeviceRingStep

func EscalateDeviceRingStep(ctx context.Context, ring *iket.DeviceRing, step int, name string, startNs, endNs int64, opts EscalateOptions) (*ExportResult, error)

EscalateDeviceRingStep records step [startNs, endNs] on ring, and if StepLatencyThreshold is exceeded, captures a snapshot bundle and exports a reproducer package to opts.OutputDir.

func EscalateFlightRingSnapshot

func EscalateFlightRingSnapshot(ctx context.Context, s *iket.FlightRingSnapshot, opts EscalateOptions) (*ExportResult, error)

EscalateFlightRingSnapshot validates a decoded flight ring snapshot and exports a reproducer package.

func EscalateIKETIncident

func EscalateIKETIncident(ctx context.Context, inc *iket.IKETIncident, opts EscalateOptions) (*ExportResult, error)

EscalateIKETIncident validates an IKET escalation incident and exports a reproducer package.

func EscalateStuckSegment

func EscalateStuckSegment(ctx context.Context, err *iket.StuckSegmentError, opts EscalateOptions) (*ExportResult, error)

EscalateStuckSegment translates a live deadlock StuckSegmentError into launch geometry and exports a reproducer package.

func EscalateToReproducer

func EscalateToReproducer(ctx context.Context, incident any, opts EscalateOptions) (*ExportResult, error)

EscalateToReproducer captures state from iket.DeviceRing, IKET incident, or StuckSegmentError, validates the reproducer manifest, and invokes ExportPackage to emit a standalone compilable failing go test package.

type ExternalAttestation

type ExternalAttestation struct {
	Version               int                    `json:"version"`
	RegistrationDigest    string                 `json:"registration_digest"`
	ProtocolDigest        string                 `json:"protocol_digest"`
	Scope                 EvidenceScope          `json:"scope"`
	AuthorityID           string                 `json:"authority_id"`
	AuthorityPolicyDigest string                 `json:"authority_policy_digest"`
	Disposition           string                 `json:"disposition"`
	MethodArtifact        RegistrationArtifact   `json:"method_artifact"`
	EvidenceArtifacts     []RegistrationArtifact `json:"evidence_artifacts"`
	Preregistration       *PreregistrationCheck  `json:"preregistration"`
	Quality               *QualityCheck          `json:"quality"`
	Analysis              *AnalysisCheck         `json:"analysis"`
	Uncertainty           *UncertaintyCheck      `json:"uncertainty"`
	Environment           *EnvironmentCheck      `json:"environment"`
	Reason                string                 `json:"reason"`
	Owner                 string                 `json:"owner"`
	NextAction            string                 `json:"next_action"`
}

ExternalAttestation retains explicit bounded evidence identities, not acquisition authority.

type FamilyClassifier

type FamilyClassifier struct {
	Demangler *sass.Demangler
}

FamilyClassifier normalizes kernel symbols and assigns them to architectural families.

func NewFamilyClassifier

func NewFamilyClassifier(d *sass.Demangler) *FamilyClassifier

NewFamilyClassifier creates a FamilyClassifier. If d is nil, pure-Go symbol normalization is used.

func (*FamilyClassifier) Classify

func (fc *FamilyClassifier) Classify(symbol string) string

Classify categorizes a kernel symbol into an architectural family.

Example
package main

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

func main() {
	fc := diag.DefaultFamilyClassifier

	symbols := []string{
		"void <unnamed>::gateup_iq2_swiglu_q8_d2r_kernel<(int)32, (int)32>",
		"mul_mat_q",
		"attention_tokentile",
		"rms_norm_small",
		"repack_weights_aligned_kernel",
	}

	for _, sym := range symbols {
		fmt.Printf("%-30s -> %s\n", fc.Normalize(sym), fc.Classify(sym))
	}

}
Output:
gateup_iq2_swiglu_q8_d2r_kernel -> experts
mul_mat_q                      -> dense_q8
attention_tokentile            -> attention
rms_norm_small                 -> norm_prep
repack_weights_aligned_kernel  -> model_prep

func (*FamilyClassifier) Demangle

func (fc *FamilyClassifier) Demangle(ctx context.Context, symbols []string) ([]string, error)

Demangle resolves mangled symbols using the configured demangler, or returns symbols as-is if no demangler is configured.

func (*FamilyClassifier) Normalize

func (fc *FamilyClassifier) Normalize(symbol string) string

Normalize reduces a mangled symbol or demangled C++ function signature down to its canonical base function identifier.

type FamilyRule

type FamilyRule = re_obsmodel.FamilyRule

type FamilySummary

type FamilySummary = re_obsmodel.FamilySummary

type FaultLabel

type FaultLabel string

FaultLabel identifies an injected or held-out fault mechanism.

const (
	// FaultNone indicates normal nominal execution with no induced defect.
	FaultNone FaultLabel = "none"

	// FaultHostSubmissionDelay indicates OS scheduling or runtime preemption
	// delay on the host submission thread before CUDA driver API entry.
	FaultHostSubmissionDelay FaultLabel = "host_submission_delay"

	// FaultDeviceBottleneck indicates kernel or device resource saturation.
	FaultDeviceBottleneck FaultLabel = "device_bottleneck"

	// FaultSyncStall indicates excessive host-device synchronization stalls.
	FaultSyncStall FaultLabel = "synchronization_stall"

	// FaultCollectiveDelay indicates a delayed peer in multi-GPU communication.
	FaultCollectiveDelay FaultLabel = "collective_peer_delay"
)

type Finding

type Finding struct {
	Headline string   // first line of the block, with the log prefix removed
	Detail   []string // remaining lines of the block, with the log prefix removed
}

Finding is one report block from a compute-sanitizer log: a headline such as "Invalid __global__ write of size 4 bytes" followed by its indented detail lines.

func (Finding) MemoryAccess

func (f Finding) MemoryAccess() (Access, bool)

MemoryAccess decodes supported memcheck global-access reports. It returns false if the address or access size cannot be established without guessing.

Example
finding := Finding{Headline: "Invalid __global__ write of size 4 bytes", Detail: []string{"Address 0x1010 is out of bounds"}}
access, ok := finding.MemoryAccess()
fmt.Printf("parsed=%t address=%#x bytes=%d write=%t\n", ok, access.Address, access.Bytes, access.Write)
Output:
parsed=true address=0x1010 bytes=4 write=true

func (Finding) String

func (f Finding) String() string

String returns the finding's headline and detail as the tool printed them, without the log prefix.

type FixtureOption

type FixtureOption func(*ServiceFixture)

FixtureOption configures a ServiceFixture.

func WithProcess

func WithProcess(proc obsworkload.ProcessGenID) FixtureOption

WithProcess sets the process generation ID.

func WithWeightBias

func WithWeightBias(w, b float64) FixtureOption

WithWeightBias sets custom weights and biases for the numerical transform.

type FixtureRunResult

type FixtureRunResult struct {
	GroundTruth      []GroundTruthRecord
	HostSubmissions  []obsworkload.HostSubmission
	DeviceActivities []obsworkload.DeviceActivity
	DiagnosticInputs map[string]DiagnosticInput
	DroppedRecords   uint64
	TotalSubmissions uint64
	ElapsedDuration  time.Duration
}

FixtureRunResult holds ground truth and emitted telemetry from an evaluation run.

DroppedRecords counts the device activity records dropped over the whole run and TotalSubmissions the requests executed. Each diagnostic input's receipt instead reports the loss of its own case: its "activity" and "sched" LostRecords have Total 1, and the activity Dropped is 1 only if that case's activity record was dropped. A late attach case instead reports unknown activity loss. The per-case activity drops sum to DroppedRecords.

A process restart case submits its host operation under the next process generation and records that generation in its scheduler evidence; its device activity keeps the original generation. A late attach case records its device activity without correlation IDs and declares the attach gap in its receipt.

type FloorBasis

type FloorBasis = re_obsmodel.FloorBasis

type GEMMReductionRound

type GEMMReductionRound = re_obsmodel.GEMMReductionRound

type GEMMSpatialProfile

type GEMMSpatialProfile = re_obsmodel.GEMMSpatialProfile

type GEMMSplitKMovement

type GEMMSplitKMovement = re_obsmodel.GEMMSplitKMovement

type GPMSampler

type GPMSampler = re_obsmodel.GPMSampler

type Gap

type Gap struct {
	StreamID        int64
	StartNs         int64
	EndNs           int64
	GapNs           int64
	PrecedingKernel string
	FollowingKernel string
	MissingEvidence []string
}

Gap records an observed execution gap between consecutive kernel launches on the same stream.

type GatedRunResult

type GatedRunResult struct {
	// TrialName is the name of the evaluated trial.
	TrialName string

	// Novel reports whether the execution trace was admitted by the gating policy.
	Novel bool

	// SanitizerDispatched reports whether compute-sanitizer was launched.
	SanitizerDispatched bool

	// TraceDigest is the SHA-256 hash of the evaluated raw trace.
	TraceDigest [32]byte

	// Result is the compute-sanitizer result if dispatched, or nil if bypassed.
	Result *Result

	// FastErr is any error returned by FastRun.
	FastErr error
}

GatedRunResult records the outcome of a gated trial execution.

type GatedRunner

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

GatedRunner decouples heavy sanitizer checks from the execution loop by evaluating un-instrumented trace novelty and only triggering compute-sanitizer when gating criteria are satisfied.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	cfg := diag.Config{
		Tool:        diag.Memcheck,
		MissingTool: diag.MissingToolSkip,
		Gating:      diag.GatingCoverageIncrease,
	}

	runner, err := diag.NewGatedRunner(cfg, 32, 100)
	if err != nil {
		panic(err)
	}

	trace1 := make([]byte, 32)
	trace1[16] = 1

	trial1 := diag.GatedTrial{
		Name:  "kernel_variant_a",
		Trace: trace1,
		SanitizeRun: func(ctx context.Context) (*diag.Result, error) {
			return &diag.Result{Outcome: diag.OutcomeClean}, nil
		},
	}

	res1, _ := runner.RunTrial(context.Background(), trial1)
	fmt.Printf("Trial 1 novel: %v, dispatched: %v\n", res1.Novel, res1.SanitizerDispatched)

	// Repeating same trace bypasses compute-sanitizer
	res2, _ := runner.RunTrial(context.Background(), trial1)
	fmt.Printf("Trial 2 novel: %v, dispatched: %v\n", res2.Novel, res2.SanitizerDispatched)

}
Output:
Trial 1 novel: true, dispatched: true
Trial 2 novel: false, dispatched: false

func NewGatedRunner

func NewGatedRunner(cfg Config, mapSize, maxTraces int) (*GatedRunner, error)

NewGatedRunner constructs a GatedRunner with the given config, map size, and max traces limit. If config.Gating is unset, it defaults to GatingCoverageIncrease.

func (*GatedRunner) Config

func (r *GatedRunner) Config() Config

Config returns the runner's configuration.

func (*GatedRunner) Novelty

func (r *GatedRunner) Novelty() *TraceNovelty

Novelty returns the runner's TraceNovelty filter.

func (*GatedRunner) RunTrial

func (r *GatedRunner) RunTrial(ctx context.Context, trial GatedTrial) (*GatedRunResult, error)

RunTrial executes trial on the fast path, evaluates trace novelty, and conditionally dispatches compute-sanitizer if novel.

type GatedTrial

type GatedTrial struct {
	// Name identifies the trial.
	Name string

	// Prog and AppArgs define the program executed under compute-sanitizer
	// when gating criteria pass.
	Prog    string
	AppArgs []string

	// FastRun executes the un-instrumented trial and returns its raw edge coverage trace.
	// Either FastRun or Trace must be non-empty/non-nil.
	FastRun func(ctx context.Context) ([]byte, error)

	// Trace is a precomputed raw coverage trace. Used when FastRun is nil.
	Trace []byte

	// SanitizeRun optionally overrides default compute-sanitizer execution (e.g. for testing).
	// If nil, [Run] is invoked with the runner's Config, Prog, and AppArgs.
	SanitizeRun func(ctx context.Context) (*Result, error)
}

GatedTrial defines one execution trial to be evaluated by GatedRunner.

type Granularity

type Granularity = re_obsmodel.Granularity

type Graph

type Graph = re_obsprobe.Graph

type GraphReplayGeneration

type GraphReplayGeneration = re_obsworkload.GraphReplayGeneration

type GroundTruthFixture

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

GroundTruthFixture provides an independent, known-answer execution simulator for attributing workloads and qualifying diagnostic utility under induced faults.

func NewGroundTruthFixture

func NewGroundTruthFixture() *GroundTruthFixture

NewGroundTruthFixture constructs a new independent ground-truth evaluation fixture.

func (*GroundTruthFixture) Execute

Execute processes a batch of requests, simulating concurrency, telemetry emission, and held-out fault mechanisms while recording exact ground truth. It refuses a request with a resilience mode other than ResilienceNormal whose process generation or correlation ID is incomplete, and a restart whose next generation would wrap.

type GroundTruthLog

type GroundTruthLog struct {
	RequestID       string                       `json:"request_id"`
	WorkloadName    string                       `json:"workload_name"`
	OpID            obsworkload.OpID             `json:"op_id"`
	ProcessGen      obsworkload.ProcessGenID     `json:"process_gen"`
	Workload        obsworkload.WorkloadIdentity `json:"workload"`
	TID             uint64                       `json:"tid"`
	Mode            Mode                         `json:"mode"`
	HostPrepDelay   time.Duration                `json:"host_prep_delay"`
	HostAPIDuration time.Duration                `json:"host_api_duration"`
	KernelDuration  time.Duration                `json:"kernel_duration"`
	TotalDuration   time.Duration                `json:"total_duration"`
	OutputChecksum  string                       `json:"output_checksum"`
}

GroundTruthLog records request identity and controls separately from diagnostic input. Its timing copies are for audit, not the source of a finding.

type GroundTruthRecord

type GroundTruthRecord struct {
	RequestID       string                   `json:"request_id"`
	WorkloadName    string                   `json:"workload_name"`
	ProcessGen      obsworkload.ProcessGenID `json:"process_gen"`
	TID             uint64                   `json:"tid"`
	StreamID        uint32                   `json:"stream_id"`
	CorrelationID   uint32                   `json:"correlation_id"`
	Fault           FaultLabel               `json:"fault"`
	Resilience      ResilienceMode           `json:"resilience"`
	HostPrepDelay   time.Duration            `json:"host_prep_delay"`
	HostAPIDuration time.Duration            `json:"host_api_duration"`
	KernelDuration  time.Duration            `json:"kernel_duration"`
	TotalDuration   time.Duration            `json:"total_duration"`
	OutputHash      string                   `json:"output_hash"`
}

GroundTruthRecord holds known-answer state for an individual request.

type GroundTruthRequest

type GroundTruthRequest struct {
	ID            string
	WorkloadName  string
	ProcessGen    obsworkload.ProcessGenID
	TID           uint64
	StreamID      uint32
	CorrelationID uint32
	Fault         FaultLabel
	Resilience    ResilienceMode
	Data          []float64
	DelayDuration time.Duration
}

GroundTruthRequest describes a workload item submitted to the evaluation fixture.

type HardwareCalibration

type HardwareCalibration = re_obsmodel.HardwareCalibration

type HardwareClosure

type HardwareClosure struct {
	GPUModel      string `json:"gpu_model"`
	GPUUUID       string `json:"gpu_uuid"`
	Architecture  string `json:"architecture"`
	SMCount       int    `json:"sm_count"`
	DriverVersion string `json:"driver_version"`
	CUDAVersion   string `json:"cuda_version"`
	HostOS        string `json:"host_os"`
	HostArch      string `json:"host_arch"`
	KernelRelease string `json:"kernel_release"`
	MIGMode       string `json:"mig_mode"`
	ClocksLocked  bool   `json:"clocks_locked"`
	PowerLimitW   int    `json:"power_limit_w"`
}

HardwareClosure records the precise hardware and environment state.

func DefaultHardwareClosure

func DefaultHardwareClosure() HardwareClosure

DefaultHardwareClosure returns default host hardware metadata for test environment.

type HardwareProbe

type HardwareProbe = re_obsmodel.HardwareProbe

type HardwareStatus

type HardwareStatus = timing.HardwareStatus

HardwareStatus indicates whether genuine physical GPU hardware is available.

func CheckHardwareStatus

func CheckHardwareStatus() HardwareStatus

CheckHardwareStatus inspects the host environment for qualified physical GPU hardware. When no physical GPU is present, it explicitly reports StatusPendingHardware.

type HardwareVerificationStatus

type HardwareVerificationStatus = re_obsmodel.HardwareVerificationStatus

type HealthCapacityArtifactRef

type HealthCapacityArtifactRef struct {
	Kind   string `json:"kind"` // request, authorization, result, action, post_action
	ID     string `json:"id"`
	SHA256 string `json:"sha256"`
	State  string `json:"state"`
}

HealthCapacityArtifactRef identifies an opaque artifact owned by an external validation or recovery consumer. It does not import, authenticate, or authorize the referenced record.

type HealthCapacityIncident

type HealthCapacityIncident struct {
	Version         int                            `json:"version"`
	HealthSHA256    string                         `json:"health_sha256"`
	TelemetrySHA256 string                         `json:"telemetry_sha256"`
	ReceiptSHA256   string                         `json:"receipt_sha256,omitempty"`
	Receipt         *tracecontract.Receipt         `json:"receipt,omitempty"`
	Health          obs_telemetry.HealthSnapshot   `json:"health"`
	HealthFindings  []tracecontract.Finding        `json:"health_findings,omitempty"`
	Diagnosis       TelemetryDiagnosis             `json:"diagnosis"`
	Assignment      obs_telemetry.EntityAssignment `json:"assignment"`
	Workload        obsworkload.WorkloadIdentity   `json:"workload"`
	Work            []obs_telemetry.AccountingWork `json:"work,omitempty"`
	Impact          tracecontract.Admission        `json:"impact"`
	ImpactClass     tracecontract.FindingClass     `json:"impact_class"`
	WithheldReason  string                         `json:"withheld_reason,omitempty"`
	ExternalRefs    []HealthCapacityArtifactRef    `json:"external_refs,omitempty"`
}

HealthCapacityIncident retains source observations, rule findings and workload diagnosis as separate records. Impact is only a temporal association between admitted evidence; it never establishes health causality or usable capacity.

func ComposeHealthCapacity

func ComposeHealthCapacity(ctx context.Context, in HealthCapacityInput, limits HealthCapacityLimits) (HealthCapacityIncident, error)

ComposeHealthCapacity reads the existing versioned health and canonical telemetry formats, then composes only their admitted evidence. Health JSON and telemetry JSONL are hashed as exact input bytes. The supplied trace receipt remains independent from the stream manifest. An admitted impact requires receipt gates named health_identity_binding and health_freshness, both passed, and receipt options binding the exact health and assignment digests, health node/topology/clock, assignment node/boot/device/MIG/allocation identity, workload run, and impact interval. Those caller-supplied values are structural linkage, not producer authentication. No hardware, tests, scheduler, or remediation action is invoked.

Example
in, limits, err := healthCapacityFixture(diag.InjectionHostDelay)
if err != nil {
	fmt.Println("fixture error")
	return
}
incident, err := diag.ComposeHealthCapacity(context.Background(), in, limits)
if err != nil {
	fmt.Println("composition error")
	return
}
fmt.Println(incident.Impact.Status, incident.ImpactClass)
Output:
admitted associated
Example (WithheldWorkloadLabels)
in, limits, err := healthCapacityFixture(diag.InjectionHostDelay)
if err != nil {
	fmt.Println("fixture error")
	return
}
in.Telemetry.Workload.Labels = map[string]string{"review": "before"}
incident, err := diag.ComposeHealthCapacity(context.Background(), in, limits)
if err != nil {
	fmt.Println("composition error")
	return
}
in.Telemetry.Workload.Labels["review"] = "after"
fmt.Println(incident.Diagnosis.Diagnosis.Workload.Labels["review"])
Output:
before

type HealthCapacityInput

type HealthCapacityInput struct {
	HealthJSON     []byte                         `json:"health_json"`
	HealthLimits   obs_telemetry.HealthLimits     `json:"health_limits"`
	TelemetryJSONL []byte                         `json:"telemetry_jsonl"`
	Telemetry      TelemetryOptions               `json:"-"`
	HealthFindings []tracecontract.Finding        `json:"health_findings,omitempty"`
	Work           []obs_telemetry.AccountingWork `json:"work,omitempty"`
	ExternalRefs   []HealthCapacityArtifactRef    `json:"external_refs,omitempty"`
}

HealthCapacityInput contains bounded source bytes and independently supplied workload and rule evidence. The caller must not mutate the input during the call. Receipt gates and artifact hashes are structural linkage, not proof of producer authenticity or authorization.

type HealthCapacityLimits

type HealthCapacityLimits struct {
	MaxBytes        int64
	MaxFindings     int
	MaxWork         int
	MaxExternalRefs int
}

HealthCapacityLimits bounds source bytes and record collections. Every field must be positive and within its hard cap.

type HierarchyLevel

type HierarchyLevel = re_obsmodel.HierarchyLevel

type HierarchyMovement

type HierarchyMovement = re_obsmodel.HierarchyMovement

type HistoryLinkOptions

type HistoryLinkOptions struct {
	CompilerInputKey string
	Compiler         nvrtc.CacheCompilerIdentity
	Workload         nvrtc.WorkloadIdentity
	Entry            string
	Artifact         *kernel.Artifact
	Qualified        bool
}

type Hook

type Hook string

Hook identifies the driver struct_ops or runtime entrypoint.

const (
	// HookBlockActivate corresponds to UVM gpu_block_activate.
	HookBlockActivate Hook = "gpu_block_activate"
	// HookBlockAccess corresponds to UVM gpu_block_access.
	HookBlockAccess Hook = "gpu_block_access"
	// HookEvictPrepare corresponds to UVM gpu_evict_prepare.
	HookEvictPrepare Hook = "gpu_evict_prepare"
	// HookPagePrefetch corresponds to UVM gpu_page_prefetch.
	HookPagePrefetch Hook = "gpu_page_prefetch"
	// HookPagePrefetchIter corresponds to UVM gpu_page_prefetch_iter.
	HookPagePrefetchIter Hook = "gpu_page_prefetch_iter"
	// HookSchedTimeslice corresponds to GPU scheduler timeslice assignment.
	HookSchedTimeslice Hook = "gpu_sched_timeslice"
	// HookDescribeLaunch identifies a host artifact description, not a live hook.
	HookDescribeLaunch Hook = "cudabpfdev_describe_launch"
	// HookPTXInstrument corresponds to bpftime PTX attach interception.
	HookPTXInstrument Hook = "bpftime_ptx_attach"
)

type HostCallEvent

type HostCallEvent struct {
	Span      tracecontract.Interval `json:"span"`
	Name      string                 `json:"name"`
	HasReturn bool                   `json:"has_return"`
}

type HostEvidence

type HostEvidence struct {
	// StopStats preserves the collector's final counters. StopError makes any
	// partial/failed counter acquisition explicit; ring counters do not establish
	// complete call, scheduler or thread coverage.
	StopStats    *bpf.StopStats `json:",omitempty"`
	StopError    string         `json:",omitempty"`
	CleanupError string         `json:",omitempty"`
	Manifest     bpf.Manifest
	Process      obsworkload.ProcessGenID
	TID          uint64
	RawSHA256    string
	Records      int
	HostCalls    []HostCallEvent
	Scheduler    SchedEvidence
	Receipt      tracecontract.Receipt
	Findings     []tracecontract.Finding
}

HostEvidence retains an actual collector's host observations. Receipt.Partial remains true: late attachment and unquantified tracefs transport loss prevent exact totals and causal GPU attribution. HostCalls are API intervals, never GPU execution intervals. RawSHA256 hashes the JSON lines written to the sink. Records counts serialized results, including coverage attempts. Final manifest and counter metadata are returned in this envelope; the raw stream remains Result JSONL.

func CollectHostEvidence

func CollectHostEvidence(ctx context.Context, cfg bpf.TraceHostConfig, tid uint64, maxRecords int, raw io.Writer, recorder *iket.Recorder) (out HostEvidence, err error)

CollectHostEvidence attaches real CUDA API and scheduler probes for cfg.PID. A finite context deadline is required. Raw bytes are capped at 64 MiB. The optional running flight recorder receives decoded host observations with explicit raw clock labels; it does not receive fabricated kernel names or GPU durations. Library permissions/ABI failures are returned, never replaced by fixtures.

Example
_, err := CollectHostEvidence(context.Background(), bpf.TraceHostConfig{}, 0, 0, io.Discard, nil)
fmt.Println(err != nil)
Output:
true

type HostSubmission

type HostSubmission = re_obsworkload.HostSubmission

type IKETComparison

type IKETComparison struct {
	Kernel              string           `json:"kernel"`
	BaselineTotalNs     uint64           `json:"baseline_total_ns"`
	CandidateTotalNs    uint64           `json:"candidate_total_ns"`
	DeltaTotalNs        int64            `json:"delta_total_ns"`
	OverallSpeedup      float64          `json:"overall_speedup"`
	Regions             []IKETRegionDiff `json:"regions"`
	Edges               []IKETEdgeDiff   `json:"edges,omitempty"`
	BaselineViolations  int              `json:"baseline_violations"`
	CandidateViolations int              `json:"candidate_violations"`
	Validity            any              `json:"validity,omitempty"`
}

IKETComparison holds the differential sub-kernel region and DAG-edge analysis between a baseline and a candidate iket.Trace.

func CompareIKET

func CompareIKET(baseline, candidate *iket.Trace, dag *iket.DAG) (*IKETComparison, error)

CompareIKET computes a region-by-region and optional DAG-edge differential comparison between baseline and candidate IKET traces.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"github.com/tmc/lib/nvidia/x/obs/iket"
)

func main() {
	names := map[uint16]string{1: "load_gmem", 2: "mma_main"}
	baseTr := &iket.RingTrace{
		Config: iket.RingConfig{Rings: 1, Capacity: 4},
		Events: []iket.Event{
			{Start: 1000, End: 1400, Block: 0, Warp: 0, ID: 1},
			{Start: 1450, End: 2050, Block: 0, Warp: 0, ID: 2},
		},
	}
	candTr := &iket.RingTrace{
		Config: iket.RingConfig{Rings: 1, Capacity: 4},
		Events: []iket.Event{
			{Start: 1000, End: 1200, Block: 0, Warp: 0, ID: 1},
			{Start: 1250, End: 1550, Block: 0, Warp: 0, ID: 2},
		},
	}
	baseIKET, _ := iket.FromSpanTrace(baseTr, "sm100_gemm", [3]int{1, 1, 1}, [3]int{128, 1, 1}, names)
	candIKET, _ := iket.FromSpanTrace(candTr, "sm100_gemm", [3]int{1, 1, 1}, [3]int{128, 1, 1}, names)

	dag, _ := iket.NewDAG("gemm_pipeline")
	_ = dag.AddEdge("load_gmem", "mma_main", "smem_a", "mbarrier")

	comp, err := diag.CompareIKET(baseIKET, candIKET, dag)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("kernel=%s speedup=%.2fx violations=%d->%d\n",
		comp.Kernel, comp.OverallSpeedup, comp.BaselineViolations, comp.CandidateViolations)
	for _, r := range comp.Regions {
		fmt.Printf("%s: %dns -> %dns (%.2fx, regressed=%v)\n",
			r.Name, r.BaselineTotalNs, r.CandidateTotalNs, r.Speedup, r.Regressed)
	}
}
Output:
kernel=sm100_gemm speedup=2.00x violations=0->0
load_gmem: 400ns -> 200ns (2.00x, regressed=false)
mma_main: 600ns -> 300ns (2.00x, regressed=false)

type IKETEdgeDiff

type IKETEdgeDiff struct {
	Source              string `json:"source"`
	Target              string `json:"target"`
	Tensor              string `json:"tensor,omitempty"`
	SyncKind            string `json:"sync_kind,omitempty"`
	BaselinePairs       int    `json:"baseline_pairs"`
	CandidatePairs      int    `json:"candidate_pairs"`
	BaselineViolations  int    `json:"baseline_violations"`
	CandidateViolations int    `json:"candidate_violations"`
	BaselineMinGapNs    int64  `json:"baseline_min_gap_ns"`
	CandidateMinGapNs   int64  `json:"candidate_min_gap_ns"`
	BaselineMaxGapNs    int64  `json:"baseline_max_gap_ns"`
	CandidateMaxGapNs   int64  `json:"candidate_max_gap_ns"`
	DeltaMinGapNs       int64  `json:"delta_min_gap_ns"`
	NewViolations       bool   `json:"new_violations"`
}

IKETEdgeDiff compares one compile-time iket.DAG dependency edge across a baseline and a candidate IKET trace.

type IKETRegionDiff

type IKETRegionDiff struct {
	Name             string  `json:"name"`
	BaselineCount    int     `json:"baseline_count"`
	CandidateCount   int     `json:"candidate_count"`
	BaselineTotalNs  uint64  `json:"baseline_total_ns"`
	CandidateTotalNs uint64  `json:"candidate_total_ns"`
	BaselineMeanNs   float64 `json:"baseline_mean_ns"`
	CandidateMeanNs  float64 `json:"candidate_mean_ns"`
	BaselineP99Ns    uint64  `json:"baseline_p99_ns"`
	CandidateP99Ns   uint64  `json:"candidate_p99_ns"`
	DeltaTotalNs     int64   `json:"delta_total_ns"`
	Speedup          float64 `json:"speedup"`
	Regressed        bool    `json:"regressed"`
}

IKETRegionDiff compares the latency distribution of one named IKET region between a baseline and a candidate trace.

type IKETRegionPoint

type IKETRegionPoint = re_obsmodel.IKETRegionPoint

type Incident

type Incident struct {
	ID                  string                       `json:"id"`
	Admitted            bool                         `json:"admitted"`
	WithheldReason      string                       `json:"withheld_reason,omitempty"`
	Diagnosis           DiagnosisResult              `json:"diagnosis"`
	PrimaryFinding      tracecontract.Finding        `json:"primary_finding"`
	Workload            obsworkload.WorkloadIdentity `json:"workload"`
	CaptureReceiptRef   ArtifactRef                  `json:"capture_receipt_ref"`
	ObservedEnvironment Environment                  `json:"observed_environment"`
	CreatedAt           time.Time                    `json:"created_at"`
}

Incident encapsulates an admitted diagnostic incident and its supporting evidence.

type InjectionType

type InjectionType string
const (
	// InjectionNone represents an unperturbed baseline control run.
	InjectionNone InjectionType = "none"
	// InjectionHostDelay injects host submission delay / CPU scheduling starvation.
	InjectionHostDelay InjectionType = "host_delay"
	// InjectionDeviceBottleneck injects competing device kernel contention.
	InjectionDeviceBottleneck InjectionType = "device_bottleneck"
	// InjectionAmbiguousSimultaneous injects both host delay and device bottleneck concurrently.
	InjectionAmbiguousSimultaneous InjectionType = "ambiguous_simultaneous"
	// InjectionMissingReturn injects an unreturned host runtime/uprobe call.
	InjectionMissingReturn InjectionType = "missing_return"
	// InjectionMissingScheduler injects missing scheduler probe evidence.
	InjectionMissingScheduler InjectionType = "missing_scheduler"
	// InjectionClockUncertainty injects cross-domain clock uncertainty exceeding threshold.
	InjectionClockUncertainty InjectionType = "clock_uncertainty"
	// InjectionRecordLoss injects trace record loss exceeding threshold.
	InjectionRecordLoss InjectionType = "record_loss"
)

type Input

type Input struct {
	Provenance ShadowProvenance `json:"provenance"`
	Domain     Domain           `json:"domain"`
	Eviction   *EvictionData    `json:"eviction,omitempty"`
	Prefetch   *PrefetchData    `json:"prefetch,omitempty"`
	Scheduling *SchedulingData  `json:"scheduling,omitempty"`
	PTX        *PTXData         `json:"ptx,omitempty"`
}

Input represents an observed policy input payload.

func (Input) Validate

func (in Input) Validate() error

Validate verifies consistency between domain and payload.

type InputRef

type InputRef struct {
	Name          string  `json:"name"`
	Path          string  `json:"path"`
	Digest        string  `json:"sha256"`
	Seed          int64   `json:"seed,omitempty"`
	ShapeDims     []int64 `json:"shape_dims,omitempty"`
	NumericalMode string  `json:"numerical_mode,omitempty"`
}

InputRef captures an input dataset or tensor specification.

type InputStatus

type InputStatus string

InputStatus indicates whether an observed input was valid, stale, or unsupported.

const (
	// StatusValid represents an input that passed freshness and capability validation.
	StatusValid InputStatus = "valid"
	// StatusStale represents an input whose timestamp expired or whose sequence arrived out-of-order.
	StatusStale InputStatus = "stale"
	// StatusUnsupported represents an input targeting an unrecognized hook, domain, or unsupported device.
	StatusUnsupported InputStatus = "unsupported"
)

type Inputs

type Inputs = re_obsmodel.Inputs

type InstructionMix

type InstructionMix = re_obsmodel.InstructionMix

type Interposition

type Interposition = re_obsprobe.Interposition

type Interval

type Interval struct {
	StartNs int64
	EndNs   int64
}

Interval represents a half-open time interval [StartNs, EndNs).

func (Interval) Duration

func (i Interval) Duration() int64

Duration returns the length of the interval.

type InterventionPlan

type InterventionPlan struct {
	HypothesisID   string                       `json:"hypothesis_id"`
	TargetWorkload obsworkload.WorkloadIdentity `json:"target_workload"`
	// ReferenceOutput contains independently computed expected values for both arms.
	ReferenceOutput   []float64         `json:"reference_output"`
	CorrectnessOracle string            `json:"correctness_oracle"`
	InterventionType  string            `json:"intervention_type"`
	Ordering          string            `json:"ordering"`
	DeviceSettings    map[string]string `json:"device_settings,omitempty"`
	CollectorSettings map[string]string `json:"collector_settings,omitempty"`
	StoppingRules     StoppingRules     `json:"stopping_rules"`
}

InterventionPlan defines a paired intervention to verify a hypothesized bottleneck mechanism.

func (InterventionPlan) Validate

func (p InterventionPlan) Validate() error

Validate checks the structural completeness of the intervention plan.

type InvocationObservationReader

type InvocationObservationReader interface {
	ReadObservation() (bpf.InvocationObservation, error)
}

type JoinConfig

type JoinConfig = re_obsworkload.JoinConfig

type JoinEngine

type JoinEngine = obsworkload.Joiner

JoinEngine is a type alias for the evidence-preserving workload joiner.

type JoinMetrics

type JoinMetrics = re_obsworkload.JoinMetrics

type JoinResult

type JoinResult = re_obsworkload.JoinResult

type Joiner

type Joiner = re_obsworkload.Joiner

type Judgment

type Judgment = re_obsmodel.Judgment

type KernelEvent

type KernelEvent struct {
	Span      tracecontract.Interval `json:"span"`
	Name      string                 `json:"name"`
	StreamID  uint64                 `json:"stream_id"`
	ContextID uint64                 `json:"context_id"`
	DeviceID  uint32                 `json:"device_id"`
}

KernelEvent represents a GPU device kernel execution.

type KernelIdentity

type KernelIdentity = re_obsprobe.KernelIdentity

type KernelMetric

type KernelMetric struct {
	Name       string
	Family     string
	Launches   int
	Timing     LatencyDecomposition
	BytesMoved uint64
	FLOPs      uint64
	Residency  obsmodel.Residency
}

KernelMetric stores aggregated metrics for a single kernel or family.

func (KernelMetric) Duration

func (k KernelMetric) Duration() time.Duration

Duration returns the total device execution duration for this kernel or family.

type KernelPoint

type KernelPoint = re_obsmodel.KernelPoint

type LatencyDecomposition

type LatencyDecomposition struct {
	HostLaunchNs uint64 // Duration of host cuLaunchKernel driver API call
	QueueNs      uint64 // Interval between enqueue and submission to GPU queue
	WaitNs       uint64 // Interval between queue submission and device execution start
	DeviceNs     uint64 // Active execution duration on streaming multiprocessors (End - Start)
}

LatencyDecomposition separates launch overhead from device kernel execution.

type LaunchObservationOptions

type LaunchObservationOptions struct {
	Source   string
	Sequence uint64
	TTL      time.Duration
	Policy   PolicyInfo
}

LaunchObservationOptions identifies the adapter epoch, receipt order and fixed PTX policy configuration. Source must change when the adapter epoch changes. Sequence is host receipt order; TTL uses host Unix nanoseconds.

type LibraryRef

type LibraryRef struct {
	Name    string `json:"name"`
	Path    string `json:"path"`
	Version string `json:"version,omitempty"`
	Digest  string `json:"sha256,omitempty"`
}

LibraryRef captures one dynamic or runtime library in the closure.

type LimitingAxis

type LimitingAxis = re_obsmodel.LimitingAxis

type Log

type Log struct {
	// Text is the report as written by the tool.
	Text string

	// SummaryFound reports whether the report ended with a summary line.
	// Its absence means the tool did not reach the end of a run, so the
	// report carries no verdict at all.
	SummaryFound bool

	// Errors is the count from "ERROR SUMMARY: N errors", or from
	// racecheck's error count when only a RACECHECK SUMMARY was printed. It
	// is meaningful only when SummaryFound is true.
	//
	// A report can carry more than one summary: compute-sanitizer prints one
	// per process, so a run that forks, or two runs concatenated into one
	// file, ends with several. Every count in the text is added in. Taking
	// only the last would let a second process's clean summary erase the
	// first's errors, which is the one direction this type must never get
	// wrong.
	Errors int

	// Summaries is the number of summary lines the report contained. It is
	// 1 for an ordinary single-process run; more means Errors is a total
	// over several, and callers reporting a per-run figure should say so.
	Summaries int

	// RaceErrors preserves the error count across all RACECHECK SUMMARY lines,
	// including when ERROR SUMMARY lines are also present. The two families
	// may overlap, so callers must not add RaceErrors to Errors.
	RaceErrors int

	// Hazards and Warnings come from racecheck's
	// "RACECHECK SUMMARY: N hazards displayed (E errors, W warnings)".
	Hazards  int
	Warnings int

	// LeakedBytes and LeakedAllocations come from memcheck's
	// "LEAK SUMMARY: N bytes leaked in M allocations", printed under
	// --leak-check full. Leaks also count toward Errors.
	LeakedBytes       int64
	LeakedAllocations int

	// Findings are the individual report blocks, in the order printed.
	Findings []Finding
}

Log is a parsed compute-sanitizer report.

The zero Log means "no report was read", which is not the same as a report of zero errors: see Log.SummaryFound.

func ParseLog

func ParseLog(text string) *Log

ParseLog parses a compute-sanitizer report.

It reads only lines carrying the tool's "=========" prefix, so text interleaved from the application under test is ignored and a combined stream can be passed in directly. Blocks are delimited by the bare prefix lines the tool prints between them.

Counts saturate at the largest representable integer instead of wrapping. Counts accumulate across every summary in the text rather than being replaced by the last one; see Log.Errors.

ParseLog never fails: text it does not recognize simply does not populate a field. Callers must therefore check Log.SummaryFound before reading Log.Errors, since an unparsed report and a clean report both leave Errors at zero.

Example

ParseLog reads a verdict out of the tool's report. Only lines carrying the tool's own "=========" prefix are read, so output from the program under test cannot forge a summary.

package main

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

func main() {
	const report = `========= COMPUTE-SANITIZER
vector add ok
========= Invalid __global__ write of size 4 bytes
=========     at 0x70 in vectorAdd(int *, int *, int *, int)
=========     Address 0x7f8a00000400 is out of bounds
=========
========= ERROR SUMMARY: 1 error
`
	log := diag.ParseLog(report)
	fmt.Println("summary found:", log.SummaryFound)
	fmt.Println("errors:", log.Errors)
	fmt.Println("first finding:", log.Findings[0].Headline)
}
Output:
summary found: true
errors: 1
first finding: Invalid __global__ write of size 4 bytes
Example (NoVerdict)

A report with errors and an exit status of 0 is the case a naive runner gets wrong. The verdict comes from the report, so the absence of a summary is not silence but a missing verdict.

package main

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

func main() {
	truncated := diag.ParseLog("========= COMPUTE-SANITIZER\n")
	fmt.Println("summary found:", truncated.SummaryFound, "errors:", truncated.Errors)

	clean := diag.ParseLog("========= ERROR SUMMARY: 0 errors\n")
	fmt.Println("summary found:", clean.SummaryFound, "errors:", clean.Errors)
}
Output:
summary found: false errors: 0
summary found: true errors: 0

type Loss

type Loss = re_obsmodel.Loss

type Manifest

type Manifest struct {
	PlanID               string        `json:"plan_id"`
	PlanDigest           string        `json:"plan_digest"`
	IncidentID           string        `json:"incident_id"`
	TargetArchitecture   string        `json:"target_architecture"`
	Artifacts            []ArtifactRef `json:"artifacts"`
	ArtifactClosureValid bool          `json:"artifact_closure_valid"`
	Reconstructable      bool          `json:"reconstructable"`
	Blockers             []string      `json:"blockers,omitempty"`
}

Manifest describes the artifact closure and verification status for reproduction.

type Match

type Match struct {
	LaunchID          string
	Argument          string
	CallSite          string
	ArtifactDigest    string
	OutsideSlice      bool
	NearestAllocation bool
}

Match is a candidate argument associated with a reported memory access. Multiple candidates are retained for aliased arguments and reused addresses. No candidate establishes launch identity by itself; callers must restrict records to the failing process and execution scope using independent evidence.

func Attribute

func Attribute(f Finding, launches ...*ReproLaunch) []Match

Attribute returns candidate arguments whose captured allocation contains the access or equals the nearest allocation identified by the sanitizer. It does not guess using kernel names or choose one of several concurrent launches.

Example
fmt.Println(len(Attribute(Finding{Headline: "unrecognized report"})))
Output:
0

type MatchedResult

type MatchedResult struct {
	Property         string  `json:"property"`
	Unit             string  `json:"unit"`
	Denominator      uint64  `json:"denominator"`
	CandidateDigest  string  `json:"candidate_digest"`
	ComparatorDigest string  `json:"comparator_digest"`
	Status           string  `json:"status"`
	Effect           float64 `json:"effect"`
	Uncertainty      float64 `json:"uncertainty"`
	Reason           string  `json:"reason,omitempty"`
}

MatchedResult records an observed difference between two independently retained artifacts. Effect is comparator minus candidate. Uncertainty is the sum of the supplied absolute error bounds, not an inferred confidence interval. Unknown inputs remain withheld; overlapping bounds report overlap.

func CompareTools

func CompareTools(p Protocol, candidate, comparator ToolReceipt, candidateRaw, comparatorRaw io.Reader) ([]MatchedResult, error)

CompareTools verifies both bounded raw receipts against a frozen task, tool matrix, units and denominators. It refuses synthetic arms and missing absolute uncertainty bounds. This validates receipt consistency; the caller remains responsible for authentic acquisition and the stated uncertainty method.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	p := diag.DefaultProtocol(diag.PhaseQualification)
	// A property-only protocol cannot compare tools without frozen arm scope.
	_, err := diag.CompareTools(p, diag.ToolReceipt{}, diag.ToolReceipt{}, nil, nil)
	fmt.Println(err != nil)
}
Output:
true

type Measurement

type Measurement struct {
	Reproductions int
	Runs          []ptx.RunRecord
}

Measurement retains every replay and its observed reproduction count. It describes an empirical frequency, not a confidence interval.

func Measure

func Measure(ctx context.Context, identity ReproIdentity, repeats int, replay func(context.Context) (ptx.RunRecord, error)) (Measurement, error)

Measure replays a finding exactly repeats times unless cancellation, a runner error, or invalid evidence stops it. replay must invoke the existing campaign runner in a fresh process for candidates that can fault. Returned partial measurements retain completed bounded records, including records with invalid classification evidence. Cyclic or excessive comparison graphs are rejected before retention.

Example
// A host fixture supplies classified records; native callers use the
// existing campaign runner and retain its actual execution receipts.
m, err := Measure(context.Background(), ReproIdentity{Policy: "exact-uint64"}, 3,
	func(context.Context) (ptx.RunRecord, error) {
		return mismatchRecord(0), nil
	})
fmt.Println(m.Reproductions, len(m.Runs), err)
Output:
3 3 <nil>

func (Measurement) DetectionAttempts

func (m Measurement) DetectionAttempts(identity ReproIdentity, targetProbability float64, maxAttempts int) (int, error)

DetectionAttempts calculates the number of attempts needed to achieve targetProbability, bounded by maxAttempts, verifying that m matches identity.

func (Measurement) DetectionProbability

func (m Measurement) DetectionProbability(attempts int) (float64, error)

DetectionProbability calculates the detection probability for the given number of attempts under the assumption of independent attempts with rate m.Reproductions / len(m.Runs).

func (Measurement) OneOff

func (m Measurement) OneOff() bool

OneOff reports whether exactly one attempt reproduced the failure.

Example
m := Measurement{Reproductions: 1, Runs: []ptx.RunRecord{mismatchRecord(0)}}
fmt.Println(m.OneOff())
Output:
true

type MeasurementScope

type MeasurementScope struct {
	Unit        string `json:"unit"`
	Denominator uint64 `json:"denominator"`
}

MeasurementScope freezes the unit and useful-work denominator for a property.

type MechanismType

type MechanismType string
const (
	// MechanismNone indicates no mechanism was diagnosed.
	MechanismNone MechanismType = "none"
	// MechanismNoFault indicates nominal execution within baseline expectations.
	MechanismNoFault MechanismType = "no_fault"
	// MechanismHostSubmissionDelay indicates host launch submission latency or CPU starvation.
	MechanismHostSubmissionDelay MechanismType = "host_submission_delay"
	// MechanismDeviceBottleneck indicates device timing exceeding the baseline.
	// The historical name alone does not establish competition or saturation.
	MechanismDeviceBottleneck MechanismType = "competing_device_bottleneck"
	// MechanismAmbiguousSimultaneous indicates multiple concurrent bottleneck mechanisms.
	MechanismAmbiguousSimultaneous MechanismType = "ambiguous_simultaneous"
	// MechanismWithheld indicates diagnosis was withheld due to incomplete or disqualified evidence.
	MechanismWithheld MechanismType = "withheld"
)

type Method

type Method = re_obsmodel.Method

type MinimalBundle

type MinimalBundle struct {
	Finding   isa_ptx.SeedResult `json:"finding"`
	Reduction Reduction          `json:"reduction"`
	Options   ExportOptions      `json:"options"`
	Files     map[string][]byte  `json:"files"`
}

MinimalBundle contains the preserved in-memory artifact files and metadata representing a reduced reproducer package.

func BuildFlightRingMinimalBundle

func BuildFlightRingMinimalBundle(s *iket.FlightRingSnapshot, opts ReproducerBundleOptions) (*MinimalBundle, error)

BuildFlightRingMinimalBundle generates a standalone minimal reproducer bundle directly from a decoded flight ring snapshot.

func BuildMinimalBundle

func BuildMinimalBundle(finding isa_ptx.SeedResult, reduction Reduction, opts ExportOptions) (*MinimalBundle, error)

BuildMinimalBundle generates the in-memory artifact files for finding and reduction without writing them to disk.

Example
finding, source := findingRecord()
c := Case{
	Source: string(source),
	Inputs: []uint64{1, 2, 3},
	Grid:   [3]uint32{1, 1, 1},
	Block:  [3]uint32{32, 1, 1},
}
red := Reduction{
	Original: c,
	Reduced:  c,
	Baseline: Measurement{
		Reproductions: 2,
		Runs:          finding.Confirmation.Runs,
	},
}
opts := ExportOptions{
	PackageName:          "example_repro",
	Repeats:              2,
	DetectionProbability: 0.99,
	MaxAttempts:          5,
}

bundle, err := BuildMinimalBundle(finding, red, opts)
if err != nil {
	fmt.Printf("err: %v\n", err)
	return
}
fmt.Printf("bundle files: %d\n", len(bundle.Files))
Output:
bundle files: 8

type MissingToolPolicy

type MissingToolPolicy int

MissingToolPolicy says what a caller wants to happen when compute-sanitizer is not installed.

There is deliberately no default. Quietly reporting success for validation that never ran is the failure this package exists to prevent, so the choice between required validation and optional validation is made explicitly, in the caller's source, where a reader can see it.

const (
	// MissingToolUnset is the zero value and is not a usable policy. [Run]
	// and [Main] reject a Config that leaves it unset.
	MissingToolUnset MissingToolPolicy = iota

	// MissingToolFail treats an absent compute-sanitizer as a failure:
	// [Result.Report] calls Fatal and [Main] returns a nonzero exit code.
	// Use it where sanitizer validation is a requirement of the run.
	MissingToolFail

	// MissingToolSkip treats an absent compute-sanitizer as a skip:
	// [Result.Report] calls Skip and [Main] runs the tests uninstrumented
	// after announcing on stderr that no sanitizer validation happened.
	// The outcome is still [OutcomeToolFailure]; the policy changes the
	// reaction, not the classification.
	MissingToolSkip
)

Missing-tool policies.

func (MissingToolPolicy) String

func (p MissingToolPolicy) String() string

type Mode

type Mode string

Mode identifies the execution mode for the service fixture.

const (
	// ModeBaseline represents ordinary baseline execution with nominal host and device timings.
	ModeBaseline Mode = "baseline"
	// ModeHostSubmissionDelay injects controlled delay before native API entry.
	ModeHostSubmissionDelay Mode = "host_submission_delay"
	// ModeDeviceBottleneck models a long synthetic device interval while keeping
	// host API work unchanged. It does not execute physical competing work.
	ModeDeviceBottleneck Mode = "device_bottleneck"
)

type Model

type Model = re_obsmodel.Model

type MovementFamily

type MovementFamily struct {
	Family    string `json:"family"`
	Total     uint64 `json:"total"`
	Completed uint64 `json:"completed"`
	Failed    uint64 `json:"failed"`
	Cancelled uint64 `json:"cancelled"`
	Pending   uint64 `json:"pending"`
	Qualified bool   `json:"qualified"`
	Reason    string `json:"reason"`
}

MovementFamily counts supplied transfer states in one loss family. Qualified reports known zero loss; otherwise absent transfers and completions in the family are unassessed rather than known not to exist.

type MovementInput

type MovementInput struct {
	Movement    io.Reader
	Source      telemetry.WorkloadSource
	Limits      telemetry.WorkloadLimits
	Activities  io.Reader
	Batch       obsworkload.ActivityBatch
	Annotations []obsworkload.HostSubmission
	Receipt     tracecontract.Receipt

	Health       io.Reader
	HealthLimits telemetry.HealthLimits

	Telemetry        io.Reader
	TelemetryOptions TelemetryOptions

	Artifacts map[string][]byte
	// MaxUncertaintyNS bounds transfer clock uncertainty for duration and
	// symptom claims. Zero means 50.
	MaxUncertaintyNS int64
}

type MovementSummary

type MovementSummary struct {
	Version       int                       `json:"version"`
	ContextSHA256 string                    `json:"context_sha256"`
	Source        telemetry.WorkloadSource  `json:"source"`
	Context       telemetry.MovementContext `json:"context"`
	Activities    ActivityAnalysis          `json:"activities"`
	Telemetry     *TelemetryDiagnosis       `json:"telemetry,omitempty"`
	TopologyEpoch string                    `json:"topology_epoch,omitempty"`
	Transfers     []MovementTransferSummary `json:"transfers"`
	Families      []MovementFamily          `json:"families"`
	Limits        []string                  `json:"limits"`
}

MovementSummary is a versioned movement incident summary. It retains the activity analysis and optional telemetry diagnosis it consumed. Each transfer claim is observed, associated or withheld independently, so missing evidence for one claim does not discard the others.

func SummarizeMovement

func SummarizeMovement(ctx context.Context, in MovementInput) (MovementSummary, error)

SummarizeMovement reads a movement context, runs the existing activity analysis and, when supplied, the health topology reader and telemetry diagnosis, and evaluates each transfer's claims. Path claims require retained evidence. An NVLink claim also requires an available nvlink_remote_pci edge from source to destination, valid over the transfer widened by its clock uncertainty, in the same topology epoch and clock; PCIe and NVSwitch topology is not supported and stays withheld. Storage, staged and RDMA modes require an independent mechanism artifact. Activity links require the same run, one copy and matching bytes, kinds and direction. CUDA activity never establishes a transfer path. No throughput, rate or reset-crossing delta is computed, and no congestion rule is defined: latency, bytes and symptoms never admit congestion.

Example
m := newMovementCase()
// Swap the destination peer: the path claim loses its topology edge.
// The peer copy has no supplied operation, so no activity link is made.
m.context.Transfers[0].Destination.Entity = "GPU-2"
in, err := m.build()
if err != nil {
	fmt.Println(err)
	return
}
s, err := diag.SummarizeMovement(context.Background(), in)
if err != nil {
	fmt.Println(err)
	return
}
for _, f := range s.Transfers[0].Findings {
	fmt.Println(f.Rule, f.Class)
}
fmt.Println(*s.Transfers[0].Bytes)
Output:
movement_bytes associated
movement_direction associated
movement_completion associated
movement_duration associated
movement_path unavailable
movement_activity_link unavailable
movement_attempt_link associated
movement_congestion unavailable
9007199254740993

type MovementTransferSummary

type MovementTransferSummary 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"`
	Bytes         *uint64                 `json:"bytes,omitempty"`
	ActivityIndex *int                    `json:"activity_index,omitempty"`
	Symptoms      []string                `json:"symptoms"`
	Findings      []tracecontract.Finding `json:"findings"`
}

MovementTransferSummary is the evaluated evidence for one supplied transfer. Bytes is the exact supplied count, present only when the bytes claim is admitted. ActivityIndex indexes the exactly linked activity join. Symptoms lists admitted telemetry finding IDs on a transfer endpoint during the transfer; a symptom is not a cause.

type MutationCall

type MutationCall struct {
	Method string
	Target string
	Args   string
}

MutationCall records an illegal invocation of an active GPU or driver mutation method.

type Name

type Name = re_obsprobe.Name

type NativeActivitySource

type NativeActivitySource struct {
	Ref    ArtifactRef
	Reader io.Reader
	Batch  obsworkload.ActivityBatch
}

NativeActivitySource is one caller-retained raw activity export in the only supported format: cuptiactivity.Record JSON lines, as RunNative writes activity.jsonl. Ref declares the exact bytes with Role "trace"; Reader supplies them and remains caller-owned. Neither Ref.Path nor any payload string is opened. Batch declares the producer session, run, clock epoch and process, with ExternalKind cupti.ExternalCorrelationKindCustom0. Its Records must be empty and its EvidenceRef empty or Ref.Digest; MaxRecords keeps the reader's meaning. The result's Annotations are joined to the records.

Composition reads Reader synchronously, checking its context before each Read; it cannot interrupt a blocking Read. A matching length and SHA-256 show only that these are the bytes read, not their provenance or authenticity.

Example
// Constructed bytes in the activity.jsonl encoding, a synthetic host
// contract rather than a native capture: one annotated launch and one
// unannotated kernel. Binding them admits no diagnosis.
process := obsworkload.ProcessGenID{PID: 4242, Generation: 1}
workload := obsworkload.WorkloadIdentity{Process: process, WorkloadName: "transform", RunID: "run-1"}
result := &NativeResult{
	Synthetic:   true,
	Requests:    []NativeRequestLog{{Attempt: "a", Complete: true, GroundTruth: GroundTruthLog{RequestID: "request-1", WorkloadName: "transform", OpID: 7, ProcessGen: process, Workload: workload, TID: 11}}},
	Annotations: []obsworkload.HostSubmission{{Process: process, OpID: 7, Workload: workload, Provenance: obsworkload.ProvenanceCUPTI, TID: 11, Symbol: "cuLaunchKernel", EvidenceRef: "example"}},
}
var raw bytes.Buffer
encoder := json.NewEncoder(&raw)
for _, record := range []cuptix.ActivityRecord{
	{Kind: cupti.ActivityKindExternalCorrelation, ExternalKind: cupti.ExternalCorrelationKindCustom0, CorrelationID: 1, ExternalID: 7},
	{Kind: cupti.ActivityKindDriver, Name: "cuLaunchKernel", CorrelationID: 1, Start: 10, End: 20, Complete: true},
	{Kind: cupti.ActivityKindConcurrentKernel, Name: "transform", CorrelationID: 2, Start: 30, End: 50, Complete: true},
} {
	if err := encoder.Encode(record); err != nil {
		fmt.Println(err)
		return
	}
}
sum := sha256.Sum256(raw.Bytes())
source := NativeActivitySource{
	Ref:    ArtifactRef{Name: "activity.jsonl", Digest: hex.EncodeToString(sum[:]), SizeBytes: int64(raw.Len()), Role: "trace"},
	Reader: &raw,
	Batch:  obsworkload.ActivityBatch{Session: "run-1", Run: "run-1", ClockEpoch: "run-1", Process: process, ExternalKind: cupti.ExternalCorrelationKindCustom0},
}
out, err := ComposeNativeEvidence(context.Background(), result, NativeCompositionOptions{Activity: &source})
if err != nil {
	fmt.Println(err)
	return
}
for _, join := range out.ActivityAnalysis.Joins {
	fmt.Println(join.Record.Name, join.Join.Outcome, uint64(join.Join.OpID))
}
fmt.Println(out.Requests[0].Diagnosis.Admitted)
Output:
cuLaunchKernel exact 7
transform missing 0
false

type NativeCall

type NativeCall struct {
	Name    string        `json:"name"`
	StartNS int64         `json:"start_ns"`
	EndNS   int64         `json:"end_ns"`
	Error   string        `json:"error,omitempty"`
	Before  *NativeSample `json:"before,omitempty"`
	After   *NativeSample `json:"after,omitempty"`
}

NativeCall is a directly measured host wrapper interval in the process-local monotonic epoch, taken immediately before and after the wrapped call. These intervals are not kernel durations, CUDA API entry times or scheduler evidence. With a CUPTI timestamp source, Before and After are raw samples taken just outside the interval; a failed sample never changes Error, the call's own failure.

type NativeComposition

type NativeComposition struct {
	Synthetic        bool                     `json:"synthetic"`
	Qualification    string                   `json:"qualification"`
	EvidenceSHA256   string                   `json:"evidence_sha256,omitempty"`
	ActivitySource   *ArtifactRef             `json:"activity_source,omitempty"`
	ActivityAnalysis *ActivityAnalysis        `json:"activity_analysis,omitempty"`
	Requests         []NativeRequestDiagnosis `json:"requests"`
	Incident         *Incident                `json:"incident,omitempty"`
	Plan             *ExperimentPlan          `json:"plan,omitempty"`
	PlanReceipt      *PlanReceipt             `json:"plan_receipt,omitempty"`
	Execution        *ExecutionReceipt        `json:"execution,omitempty"`
	Comparison       *ComparisonReceipt       `json:"comparison,omitempty"`
	ReplayRefusal    string                   `json:"replay_refusal,omitempty"`
}

NativeComposition retains actual diagnosis -> incident -> plan -> replay results. Synthetic host composition remains distinct from native qualification. EvidenceSHA256 binds the supplied envelope, not authenticity of its assertions. ActivitySource is the verified raw activity reference and ActivityAnalysis the existing reader's complete joins of those bytes, in the producer clock; neither changes a request diagnosis or qualification.

func ComposeNativeEvidence

func ComposeNativeEvidence(ctx context.Context, r *NativeResult, o NativeCompositionOptions) (NativeComposition, error)

ComposeNativeEvidence joins supplied observations to independently logged request/attempt/operation identities, invokes the real public diagnoser, and optionally calls FormulatePlan and ExecuteReplay. Ground truth never supplies a missing diagnostic gate or measurement. Current RunNative capture is partial: this consumer cannot turn it into admitted native evidence or replay.

Example
// An actual incomplete native request stays visible. There is no supplied
// host/device mapping or scheduler/loss proof to manufacture admission.
result := &NativeResult{Qualification: "partial", Requests: []NativeRequestLog{{Attempt: "baseline", GroundTruth: GroundTruthLog{RequestID: "request-1", WorkloadName: "transform"}}}}
summary, err := ComposeNativeEvidence(context.Background(), result, NativeCompositionOptions{})
fmt.Println(summary.Synthetic, len(summary.Requests), summary.Requests[0].Diagnosis.Admitted, err)
Output:
false 1 false <nil>

type NativeCompositionOptions

type NativeCompositionOptions struct {
	Evidence    io.Reader
	Activity    *NativeActivitySource
	Replay      *NativeReplay
	MaxBytes    int64
	MaxRequests int
}

NativeCompositionOptions supplies original evidence and optional existing replay closure. Zero limits mean 16MiB and 512 requests; hard caps are 32MiB and 4096 requests. MaxBytes bounds the envelope and raw activity together. Evidence nil preserves missing observations as withheld. Activity optionally binds one raw activity export; a selected Replay must then list its exact Ref in PlanOptions.Sources. Readers and replay resources remain caller-owned; cancellation cannot interrupt a caller's blocking Read. RunNative invokes this composition after cleanup.

type NativeConfig

type NativeConfig struct {
	Device    int
	Elements  int
	Rounds    int
	HostDelay time.Duration
	LockDir   string
	OutputDir string
	// DeviceIterations repeats the same kernel in the device-negative arm. Zero means 16; otherwise 2 through 1024.
	DeviceIterations int
	Concurrency      int
	Composition      NativeCompositionOptions
}

NativeConfig selects bounded physical CUDA trials. LockDir defaults to the canonical cudalock location. The caller must own CUPTI registration in this process. Native capture failures are retained as partial qualification.

Each round plans baseline, candidate and device request attempts, which all upload the same round input to their own buffers; see NativeResult.Recipe. Every planned wrapper observation, Rounds*(DeviceIterations+11), must be at most 65536; launches are never dropped to fit. Concurrency bounds the request workers: zero means 4, 1 runs attempts serially in plan order, and the maximum is 8. Each attempt owns its stream and input and output buffers, so the workers that can run at once (at most 3*Rounds) must keep 8*Elements bytes each within 32 MiB of device buffers.

A nonempty OutputDir retains each attempt's input, CPU reference and downloaded output vectors there; see NativeNumerics. Their worst case, 36*Rounds*Elements bytes, must be at most 64 MiB. An empty OutputDir retains no files.

type NativeEvidence

type NativeEvidence struct {
	Version   int                    `json:"version"`
	Synthetic bool                   `json:"synthetic"`
	Records   []NativeEvidenceRecord `json:"records"`
}

NativeEvidence is the bounded version 1 composition envelope. Synthetic is explicit, must match the request producer, and cannot qualify native work.

type NativeEvidenceRecord

type NativeEvidenceRecord struct {
	RequestID string           `json:"request_id"`
	Attempt   string           `json:"attempt"`
	OpID      obsworkload.OpID `json:"op_id"`
	Phase     string           `json:"phase"`
	Input     DiagnosticInput  `json:"input"`
}

NativeEvidenceRecord associates supplied diagnostic observations with one independently logged operation. Phase is pre_entry or api_scheduler and must agree with Input; it does not come from an injected ground-truth mode. Input retains existing receipt, raw artifact, clock, host/device and scheduler contracts. Its raw source artifacts must remain separately retained.

type NativeNumerics

type NativeNumerics struct {
	Retention    string          `json:"retention"`
	Operation    string          `json:"operation"`
	Encoding     string          `json:"encoding"`
	PlannedBytes int64           `json:"planned_bytes,omitempty"`
	Vectors      []NativeVectors `json:"vectors,omitempty"`
	Error        string          `json:"error,omitempty"`
}

NativeNumerics describes the numerical vectors RunNative retains.

With an empty OutputDir, Retention says that no vector files are retained; the trial digests are then the only numerical record. Otherwise PlannedBytes is the checked worst-case total of input, reference and output bytes for every planned attempt, at most 64 MiB, and Vectors lists, in plan order, each dispatched attempt that constructed its input.

Retention is "retained" when every constructed vector was written to a new file and closed, and "incomplete" otherwise, with the failures in Error. It describes the files, not numerical correctness. Files are never removed or rewritten, including partially written ones.

Example
// Host fakes stand in for the device streams; the executor, encoding
// and export are RunNative's with an OutputDir. This is not native
// execution. Every arm of a round uploads the same input to its own
// buffers.
dir, err := os.MkdirTemp("", "cudadiagdemo-numerics-")
if err != nil {
	fmt.Println(err)
	return
}
defer os.RemoveAll(dir)
e := (&fakeNative{}).executor()
e.retain = true
attempts, err := e.run(context.Background(), 1, planNativeRequests(1, 2), &nativeCleanup{})
if err != nil {
	fmt.Println(err)
	return
}
result := &NativeResult{}
result.recordAttempts(attempts)
if err := exportNative(dir, result, nil); err != nil {
	fmt.Println(err)
	return
}

// Verify the retained bytes from the receipt alone.
data, err := os.ReadFile(filepath.Join(dir, "native-receipt.json"))
if err != nil {
	fmt.Println(err)
	return
}
var receipt struct {
	Numerics NativeNumerics `json:"numerics"`
}
if err := json.Unmarshal(data, &receipt); err != nil {
	fmt.Println(err)
	return
}
decode := func(ref *ArtifactRef) []float32 {
	b, err := os.ReadFile(ref.Path)
	if err != nil || fmt.Sprintf("%x", sha256.Sum256(b)) != ref.Digest || int64(len(b)) != ref.SizeBytes {
		return nil
	}
	values := make([]float32, len(b)/4)
	if err := binary.Read(bytes.NewReader(b), binary.LittleEndian, values); err != nil {
		return nil
	}
	return values
}
fmt.Println(receipt.Numerics.Retention)
for _, v := range receipt.Numerics.Vectors {
	in, ref, out := decode(v.Input), decode(v.Reference), decode(v.Output)
	ok := len(in) > 0 && len(ref) == len(in) && len(out) == len(in)
	for i, x := range in {
		ok = ok && ref[i] == 2*x+1 && out[i] == ref[i]
	}
	if !ok {
		fmt.Printf("%s/%s: unverified\n", v.RequestID, v.Attempt)
		continue
	}
	fmt.Printf("%s/%s: %v -> %v verified\n", v.RequestID, v.Attempt, in[:2], out[:2])
}
Output:
retained
request-1/baseline: [0 1] -> [1 3] verified
request-1/candidate: [0 1] -> [1 3] verified
request-1/device: [0 1] -> [1 3] verified

type NativeReady

type NativeReady struct {
	HostNS int64         `json:"host_ns"`
	CUPTI  *NativeSample `json:"cupti,omitempty"`
}

NativeReady is an attempt's host launch-ready observation: its input is constructed, its stream and buffers exist and its upload is enqueued on that stream, so its next application step is the first targeted launch, after the baseline's intentional wait. It does not mean the upload has completed on the device. HostNS is in the process monotonic epoch; CUPTI is a raw sample taken after it when a timestamp source exists.

type NativeReplay

type NativeReplay struct {
	RequestID, Attempt string
	Capture            ArtifactRef
	Environment        Environment
	PlanOptions        PlanOptions
	Runner             ReplayRunner
	ReplayOptions      ReplayOptions
}

NativeReplay selects one admitted host-delay request for the existing plan and replay protocol. The caller owns the runner and immutable artifact closure; no alternate runner, training workload or device collector is constructed.

type NativeRequestDiagnosis

type NativeRequestDiagnosis struct {
	RequestID    string           `json:"request_id"`
	Attempt      string           `json:"attempt"`
	OpID         obsworkload.OpID `json:"op_id"`
	Observations DiagnosticInput  `json:"observations"`
	Diagnosis    DiagnosisResult  `json:"diagnosis"`
	Refusal      string           `json:"refusal,omitempty"`
}

NativeRequestDiagnosis retains one logged attempt and its independent finding. Evidence absence/refusal cannot remove that attempt from the population. Observations are the supplied inputs, including their thresholds. For an api_scheduler record with a zero TargetTID, composition diagnoses with the separately validated request GroundTruth.TID instead; reproduce Diagnosis by replaying the composition with that request log, not by diagnosing the unbound Observations alone.

type NativeRequestLog

type NativeRequestLog struct {
	Attempt     string         `json:"attempt"`
	StartedNS   int64          `json:"started_ns"`
	FinishedNS  int64          `json:"finished_ns"`
	Complete    bool           `json:"complete"`
	GroundTruth GroundTruthLog `json:"ground_truth"`
}

NativeRequestLog records application request controls independently of the diagnostic observations. Attempt distinguishes repetitions of a request ID. GroundTruth uses the existing service log format; its mode and durations do not generate diagnostic intervals, gates, clock maps or scheduler states. Incomplete requests remain in the population, including failed/cancelled work.

type NativeResult

type NativeResult struct {
	Requests        []NativeRequestLog `json:"requests"`
	PlannedRequests int                `json:"planned_requests"`
	Concurrency     int                `json:"concurrency"`
	Composition     *NativeComposition `json:"composition,omitempty"`
	CleanupPending  bool               `json:"cleanup_pending"`

	HostClockDomain       string                       `json:"host_clock_domain"`
	HostClockEpochID      string                       `json:"host_clock_epoch_id"`
	NumericalGate         string                       `json:"numerical_gate"`
	Numerics              NativeNumerics               `json:"numerics"`
	Recipe                string                       `json:"recipe,omitempty"`
	Timing                *ArtifactRef                 `json:"timing,omitempty"`
	TimingError           string                       `json:"timing_error,omitempty"`
	ExecutionError        string                       `json:"execution_error,omitempty"`
	Synthetic             bool                         `json:"synthetic"`
	Qualification         string                       `json:"qualification"`
	RemainingGates        []string                     `json:"remaining_gates"`
	Device                int                          `json:"device"`
	Model                 string                       `json:"model"`
	UUID                  string                       `json:"uuid"`
	Architecture          string                       `json:"architecture"`
	DriverVersion         int                          `json:"driver_version"`
	Build                 string                       `json:"build"`
	ExecutableSHA256      string                       `json:"executable_sha256"`
	SourceSHA256          string                       `json:"source_sha256"`
	CUBINSHA256           string                       `json:"cubin_sha256"`
	InputSHA256           string                       `json:"input_sha256"`
	LeaseDir              string                       `json:"lease_dir"`
	LeaseOwner            lock.Owner                   `json:"lease_owner"`
	ClockEpochUTC         time.Time                    `json:"clock_epoch_utc"`
	Trials                []NativeTrial                `json:"trials"`
	Activity              cuptix.ActivityResult        `json:"activity"`
	Annotations           []obsworkload.HostSubmission `json:"annotations,omitempty"`
	ActivityAnalysis      *ActivityAnalysis            `json:"activity_analysis,omitempty"`
	ActivityAnalysisError string                       `json:"activity_analysis_error,omitempty"`
	ActivitySHA256        string                       `json:"activity_sha256,omitempty"`
	ActivityRun           string                       `json:"activity_run,omitempty"`
	CaptureError          string                       `json:"capture_error,omitempty"`
	// contains filtered or unexported fields
}

NativeResult separates physical numerical execution from diagnosis admission. Scheduler capture and a bounded host/CUPTI clock mapping are required before these observations can support a host submission-delay diagnosis. Requests and Trials retain every dispatched attempt, including failed and canceled ones, in plan order; after a failure, later planned requests are not dispatched. Concurrency is the number of request workers used. InputSHA256 is the input of the first planned request.

Recipe is launch-ready-v1: every attempt enqueues its upload before its launch-ready observation and the baseline's intentional wait, and all arms of round r use the same input seed, r-1. Both differ from unversioned earlier results, which this recipe does not qualify. Timing references the exported native-timing.jsonl, one raw line per dispatched attempt; on a failed export it is nil and TimingError records why.

func RunNative

func RunNative(ctx context.Context, cfg NativeConfig) (result *NativeResult, retErr error)

RunNative executes an NVRTC-compiled vector operation on a physical GPU under cudalock, compares every output to an independent CPU oracle, and retains genuine CUPTI activity when supported. It never substitutes synthetic records. Successful numerical execution is explicitly partial diagnosis qualification. With an OutputDir, the retained vectors replay each attempt's numerical check; they do not qualify diagnosis. Every request worker quiesces before capture close, resource teardown and lease release.

func (*NativeResult) Close

func (r *NativeResult) Close() error

Close explicitly retries pending native cleanup. RunNative attempts cleanup once; a failed action retains every remaining resource and the GPU lease. A startup session whose rollback failed is returned without an automatic retry, as are the owners of a request whose cleanup failed. Call Close after investigating the failure. Successful actions are removed and never retried. The zero result has no cleanup ownership.

Example
var result NativeResult
fmt.Println(result.Close())
Output:
<nil>

type NativeSample

type NativeSample struct {
	HostBeforeNS int64  `json:"host_before_ns"`
	HostAfterNS  int64  `json:"host_after_ns"`
	CUPTI        string `json:"cupti"`
	CUPTINS      uint64 `json:"cupti_ns,omitempty"`
	Error        string `json:"error,omitempty"`
}

NativeSample is one raw CUPTI timestamp read bracketed by host times in the process monotonic epoch, taken in order: HostBeforeNS, the read, HostAfterNS. CUPTI is "observed" with the value in CUPTINS, "zero" when the read returned zero, or "error" with Error; only an observed sample has a CUPTI value. A sample is a raw bracket, not a host/CUPTI clock mapping, an uncertainty bound or the time of a CUDA API entry.

type NativeTiming

type NativeTiming struct {
	Recipe          string                        `json:"recipe"`
	OpID            obsworkload.OpID              `json:"op_id,omitempty"`
	Workload        *obsworkload.WorkloadIdentity `json:"workload,omitempty"`
	TID             uint64                        `json:"tid,omitempty"`
	TimestampAPI    string                        `json:"timestamp_api"`
	TimestampMethod string                        `json:"timestamp_method,omitempty"`
	Ready           *NativeReady                  `json:"ready,omitempty"`
}

NativeTiming is the raw timing record of one dispatched request attempt under Recipe. A trial without one was not observed.

OpID and Workload identify the attempt's application operation, created after its upload and before Ready; both are absent without capture. TID is the request worker's thread observed at Ready, zero where the platform reports none. It is not CUDA API entry: the trial's Correlation and annotation record entry. Ready is nil when the attempt stopped before launch-ready, as after a failed open or upload.

TimestampAPI names the CUPTI timestamp function sampled at Ready and around each of the trial's Calls, or is "unavailable". TimestampMethod is "unknown": neither the loaded library nor its timestamp method is authenticated. These observations establish no clock mapping, API entry time, scheduler evidence or diagnosis.

Example
// Host fakes stand in for the device streams and a logical clock for
// the monotonic clock; the executor and export are RunNative's. This is
// not native execution, and no observation here is CUDA API entry.
dir, err := os.MkdirTemp("", "cudadiagdemo-timing-")
if err != nil {
	fmt.Println(err)
	return
}
defer os.RemoveAll(dir)
var clock atomic.Int64
e := (&fakeNative{}).executor()
e.now = func() int64 { return clock.Add(1) }
attempts, err := e.run(context.Background(), 1, planNativeRequests(1, 2), &nativeCleanup{})
if err != nil {
	fmt.Println(err)
	return
}
result := &NativeResult{HostClockDomain: "process_monotonic"}
result.recordAttempts(attempts)
if err := exportNative(dir, result, nil); err != nil {
	fmt.Println(err)
	return
}

// Verify the timing bytes from the receipt alone.
data, err := os.ReadFile(filepath.Join(dir, "native-receipt.json"))
if err != nil {
	fmt.Println(err)
	return
}
var receipt struct {
	Timing *ArtifactRef `json:"timing"`
}
if err := json.Unmarshal(data, &receipt); err != nil || receipt.Timing == nil {
	fmt.Println("no timing reference", err)
	return
}
b, err := os.ReadFile(receipt.Timing.Path)
if err != nil || fmt.Sprintf("%x", sha256.Sum256(b)) != receipt.Timing.Digest || int64(len(b)) != receipt.Timing.SizeBytes {
	fmt.Println("unverified timing", err)
	return
}
// Place each attempt's ready observation among its wrappers by host time.
s := bufio.NewScanner(bytes.NewReader(b))
for s.Scan() {
	var line struct {
		RequestID string       `json:"request_id"`
		Attempt   string       `json:"attempt"`
		Timing    NativeTiming `json:"timing"`
		Calls     []NativeCall `json:"calls"`
	}
	if err := json.Unmarshal(s.Bytes(), &line); err != nil || line.Timing.Ready == nil {
		fmt.Println("unverified line", err)
		return
	}
	var events []string
	ready := false
	for _, c := range line.Calls {
		if !ready && line.Timing.Ready.HostNS < c.StartNS {
			events, ready = append(events, "ready"), true
		}
		events = append(events, c.Name)
	}
	fmt.Printf("%s/%s %s: %s\n", line.RequestID, line.Attempt, line.Timing.Recipe, strings.Join(events, " "))
}
Output:
request-1/baseline launch-ready-v1: cuMemcpyHtoDAsync_v2 ready cuLaunchKernel cuStreamSynchronize cuMemcpyDtoH_v2
request-1/candidate launch-ready-v1: cuMemcpyHtoDAsync_v2 ready cuLaunchKernel cuStreamSynchronize cuMemcpyDtoH_v2
request-1/device launch-ready-v1: cuMemcpyHtoDAsync_v2 ready cuLaunchKernel cuLaunchKernel cuStreamSynchronize cuMemcpyDtoH_v2

type NativeTrial

type NativeTrial struct {
	// ContextStream contains independently queried CUPTI identifiers, not raw
	// driver handles or values copied from the activity records being joined.
	// Nil means no successful identity query was retained. It establishes no activity
	// coverage, numerical correctness or native qualification.
	ContextStream     *obsworkload.ContextStreamID `json:"context_stream,omitempty"`
	OperationName     string                       `json:"operation_name,omitempty"`
	RequestedLaunches int                          `json:"requested_launches"`
	KernelLaunches    int                          `json:"kernel_launches"`
	RequestID         string                       `json:"request_id"`
	Attempt           string                       `json:"attempt"`
	Arm               string                       `json:"arm"`
	Round             int                          `json:"round"`
	Worker            int                          `json:"worker"`
	DelayNS           int64                        `json:"delay_ns"`
	WallNS            int64                        `json:"wall_ns"`
	InputSHA256       string                       `json:"input_sha256"`
	OutputSHA256      string                       `json:"output_sha256"`
	Correct           bool                         `json:"correct"`
	Correlation       string                       `json:"correlation,omitempty"`
	CUPTIBefore       uint64                       `json:"cupti_before,omitempty"`
	CUPTIAfter        uint64                       `json:"cupti_after,omitempty"`
	Calls             []NativeCall                 `json:"calls"`
	Error             string                       `json:"error,omitempty"`
	Timing            *NativeTiming                `json:"timing,omitempty"`
}

NativeTrial retains a numerical result and host observations for one request attempt. CUPTI brackets belong to CUPTI's domain; no mapping to host spans is inferred. Trials are in plan order, not execution order; Worker identifies the request worker that ran the attempt. Each attempt has its own input, checked by its own oracle; all arms of a round have the same input values. Error records why a failed or canceled attempt stopped. Timing is the attempt's raw launch-ready and timestamp observations.

Correlation records how the launches relate to CUPTI external correlation: "complete" when the native operation succeeded; "partial" when its launch function ran under correlation and then the operation failed; "not_entered" when it failed before the launch function ran, so no launch was made and the thread is unknown; "uninstrumented" without capture; and empty when the attempt stopped before its launches. A partial annotation is the scope's observation at entry on the launching thread; no native correlation ID is inferred.

type NativeVectors

type NativeVectors struct {
	Plan      int          `json:"plan"`
	RequestID string       `json:"request_id"`
	Attempt   string       `json:"attempt"`
	Input     *ArtifactRef `json:"input,omitempty"`
	Reference *ArtifactRef `json:"reference,omitempty"`
	Output    *ArtifactRef `json:"output,omitempty"`
	Error     string       `json:"error,omitempty"`
}

NativeVectors references the retained vectors of one request attempt. Plan is the attempt's plan index, which names its files. Reference is computed on the CPU from the input by NativeNumerics.Operation, never from the device output. Output is present only after a complete download, including an incorrect output; Error is the attempt's failure. A nil reference was not constructed or not completely written.

type NullControlConfig

type NullControlConfig struct {
	Enabled         bool          `json:"enabled"`
	BasketRuns      int           `json:"basket_runs"`
	MaxNoiseFloorNs time.Duration `json:"max_noise_floor_ns"`
}

NullControlConfig configures baseline-vs-baseline noise floor estimation.

type ObservedOutcome

type ObservedOutcome struct {
	// LatencyUnavailable requires LatencyNano zero; zero is then not a measurement.
	LatencyUnavailable bool              `json:"latency_unavailable,omitempty"`
	TimestampNano      int64             `json:"timestamp_nano"`
	Action             string            `json:"action"`
	LatencyNano        int64             `json:"latency_nano"`
	Details            map[string]string `json:"details,omitempty"`
}

ObservedOutcome records the baseline outcome observed without policy mutation.

type ObserverPhaseAcquisition

type ObserverPhaseAcquisition struct {
	Version int                  `json:"version"`
	Record  RegistrationArtifact `json:"record"`
}

ObserverPhaseAcquisition identifies an original acquired configuration record. Version is 1. Record contains canonical ObserverPhaseConfiguration JSON and references the actual configuration bytes. Independent policy must establish that the producer used those settings; neither this reference nor equality with registration establishes authentic acquisition.

Example
package main

import (
	"encoding/json"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	// Record must name canonical acquired configuration bytes. A reference alone
	// never establishes that a tool actually used those settings.
	acquired := diag.ObserverPhaseAcquisition{Version: 1}
	raw, _ := json.Marshal(acquired)
	fmt.Println(string(raw))
}
Output:
{"version":1,"record":{"path":"","sha256":""}}

type ObserverPhaseConfiguration

type ObserverPhaseConfiguration struct {
	Version       int                   `json:"version"`
	Arm           string                `json:"arm"`
	Phase         string                `json:"phase"`
	Tool          ToolSpec              `json:"tool"`
	Settings      ObserverPhaseSettings `json:"settings"`
	Configuration RegistrationArtifact  `json:"configuration"`
}

ObserverPhaseConfiguration binds a tool's settings and original configuration artifact to one arm and phase. Its canonical JSON is also the acquired record format. Matching bytes establish consistency, not authentic acquisition.

Example
package main

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

func main() {
	config := diag.ObserverPhaseConfiguration{Version: 1, Arm: "candidate", Phase: "observer-off"}
	fmt.Println(config.Arm, config.Phase)
}
Output:
candidate observer-off

type ObserverPhasePlan

type ObserverPhasePlan struct {
	Version        int                          `json:"version"`
	Configurations []ObserverPhaseConfiguration `json:"configurations"`
}

ObserverPhasePlan registers both off/on configurations for each comparison arm. Version is 1. These declarations do not authenticate tool execution.

Example
package main

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

func main() {
	// A real registration requires four complete candidate/comparator off/on
	// entries and original configuration artifacts before acquisition.
	plan := diag.ObserverPhasePlan{Version: 1}
	fmt.Println(plan.Version, len(plan.Configurations))
}
Output:
1 0

type ObserverPhaseSettings

type ObserverPhaseSettings struct {
	Mode           string             `json:"mode"`
	SensorScope    []string           `json:"sensor_scope"`
	Access         RegistrationFact   `json:"access"`
	FreshnessNanos int64              `json:"freshness_nanos"`
	DutyCycle      float64            `json:"duty_cycle"`
	SamplingRateHz float64            `json:"sampling_rate_hz"`
	OwnerConflicts []RegistrationFact `json:"owner_conflicts"`
}

ObserverPhaseSettings records the observer scope for one off/on phase. Access and conflicts retain unresolved states rather than implying permission.

Example
package main

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

func main() {
	settings := diag.ObserverPhaseSettings{Mode: "off"}
	fmt.Println(settings.Mode, settings.DutyCycle, settings.SamplingRateHz)
}
Output:
off 0 0

type OpID

type OpID = re_obsworkload.OpID

type Operation

type Operation = re_obsmodel.Operation

type OperationalPoint

type OperationalPoint = re_obsmodel.OperationalPoint

type OperatorCPUAnnotation

type OperatorCPUAnnotation struct {
	Annotation telemetry.WorkloadAnnotation `json:"annotation"`
	Source     telemetry.OperatorReference  `json:"source"`
}

OperatorCPUAnnotation locates an annotation in its raw-hash-scoped reader profile. Its ordinal is not a native operation or contributing member ID.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"github.com/tmc/lib/nvidia/x/obs/telemetry"
)

func main() {
	a := diag.OperatorCPUAnnotation{Source: telemetry.OperatorReference{Locator: "user_annotation/0"}}
	fmt.Println(a.Source.Locator)
}
Output:
user_annotation/0

type OperatorCPUSummary

type OperatorCPUSummary struct {
	Profile                string                        `json:"profile"`
	Version                int                           `json:"version"`
	ContextSHA256          string                        `json:"context_sha256"`
	Source                 telemetry.WorkloadSource      `json:"source"`
	TraceSource            telemetry.WorkloadSource      `json:"trace_source"`
	Trace                  telemetry.OperatorReference   `json:"trace"`
	Annotations            []OperatorCPUAnnotation       `json:"annotations"`
	ObservedCPUAnnotations uint64                        `json:"observed_cpu_annotation_count"`
	NativeAnalysisStatus   string                        `json:"native_analysis_status"`
	NativePopulation       *OperatorPopulation           `json:"native_population"`
	MembershipStatus       string                        `json:"membership_status"`
	CodeFacts              []telemetry.OperatorReference `json:"code_facts,omitempty"`
	Evidence               []telemetry.OperatorReference `json:"evidence,omitempty"`
	RawArtifactSHA256      []string                      `json:"raw_artifact_sha256"`
	PopulationLimits       []string                      `json:"population_limits"`
}

OperatorCPUSummary projects imported CPU annotations without native joins. The observed annotation count is not a complete producer denominator. CodeFacts are retained references, never contributor edges or clock links.

Example
c, source := cpuSummaryInputs()
var wire bytes.Buffer
_ = telemetry.WriteOperatorCPUContext(&wire, c, telemetry.WorkloadLimits{})
out, _ := diag.AnalyzeOperatorCPUJSON(context.Background(), &wire, source, telemetry.WorkloadLimits{})
fmt.Println(out.MembershipStatus, out.Annotations[0].Source.Locator)
Output:
unavailable user_annotation/0

func AnalyzeOperatorCPUJSON

func AnalyzeOperatorCPUJSON(ctx context.Context, metadata io.Reader, source telemetry.WorkloadSource, limits telemetry.WorkloadLimits) (OperatorCPUSummary, error)

AnalyzeOperatorCPUJSON reads application operator-cpu-context-v1 metadata and projects the existing PyTorch annotation reader's ordered CPU records. It does not consume activity JSONL, match kernels, or infer membership. A caller-owned blocking Reader cannot be interrupted by cancellation.

Example
c, source := cpuSummaryInputs()
var wire bytes.Buffer
_ = telemetry.WriteOperatorCPUContext(&wire, c, telemetry.WorkloadLimits{})
out, err := diag.AnalyzeOperatorCPUJSON(context.Background(), &wire, source, telemetry.WorkloadLimits{})
fmt.Println(out.ObservedCPUAnnotations, out.NativeAnalysisStatus, out.NativePopulation == nil, err)
Output:
1 not_collected true <nil>

type OperatorEdge

type OperatorEdge struct {
	ActivityIndex *int                        `json:"activity_index,omitempty"`
	GroupID       string                      `json:"group_id"`
	MemberID      string                      `json:"member_id"`
	Source        telemetry.OperatorReference `json:"source"`
	Outcome       obsworkload.WorkloadOutcome `json:"outcome"`
	Basis         string                      `json:"basis"`
	Reason        string                      `json:"reason"`
	ExpectedOnly  bool                        `json:"expected_only,omitempty"`
}

OperatorEdge associates one activity with one supplied/expected member. Nil ActivityIndex means metadata without an observed kernel counterpart. Compiler metadata is at most associated; edges never allocate time/counters.

type OperatorMembership

type OperatorMembership struct {
	GroupID    string `json:"group_id"`
	Status     string `json:"status"`
	Reason     string `json:"reason"`
	CodeStatus string `json:"code_status"`
}

OperatorMembership reports completeness relative to a separately retained inventory. Unknown is not an empty inventory. Agreement is not authenticity.

type OperatorPopulation

type OperatorPopulation struct {
	Total      uint64 `json:"total"`
	Exact      uint64 `json:"exact"`
	Associated uint64 `json:"associated"`
	Ambiguous  uint64 `json:"ambiguous"`
	Missing    uint64 `json:"missing"`
}

type OperatorSummary

type OperatorSummary struct {
	Version                   int                       `json:"version"`
	ContextSHA256             string                    `json:"context_sha256"`
	Source                    telemetry.WorkloadSource  `json:"source"`
	Context                   telemetry.OperatorContext `json:"context"`
	RawArtifactSHA256         []string                  `json:"raw_artifact_sha256"`
	Activities                ActivityAnalysis          `json:"activities"`
	KernelPopulation          OperatorPopulation        `json:"observed_kernel_population"`
	MemberEdgePopulation      OperatorPopulation        `json:"member_edge_population"`
	Membership                []OperatorMembership      `json:"membership"`
	Edges                     []OperatorEdge            `json:"edges"`
	UnattributedKernelIndices []int                     `json:"unattributed_kernel_indices"`
	OrphanGroups              []string                  `json:"orphan_groups"`
	PopulationLimits          []string                  `json:"population_limits"`
}

OperatorSummary retains activity findings once and compiler member edges separately. Context omits raw artifact payloads; ContextSHA256 identifies the original context file containing them. Retain that file for drilldown.

func AnalyzeOperatorJSONL

func AnalyzeOperatorJSONL(ctx context.Context, activities, metadata io.Reader, source telemetry.WorkloadSource, limits telemetry.WorkloadLimits) (OperatorSummary, error)

AnalyzeOperatorJSONL reads versioned application metadata, invokes the existing byte-bound activity analysis, and attaches supplied compiler members. Source must identify application operator-context-v1. Cancellation is checked between reads/records; it cannot interrupt a caller-owned blocking Reader. No framework SDK, compiler, device or artifact-reference path is invoked.

Example
// Constructed raw records and separately retained member inventory.
// Counts below demonstrate host composition, not native/framework proof.
activity, supplied, source := operatorSummaryInputs()
var metadata bytes.Buffer
if err := telemetry.WriteOperatorContext(&metadata, supplied, telemetry.WorkloadLimits{}); err != nil {
	panic(err)
}
summary, err := diag.AnalyzeOperatorJSONL(context.Background(), bytes.NewReader(activity), &metadata, source, telemetry.WorkloadLimits{})
if err != nil {
	panic(err)
}
fmt.Println(summary.KernelPopulation.Total, summary.MemberEdgePopulation.Associated, summary.MemberEdgePopulation.Exact)
Output:
1 2 0

type OptionalOutcome

type OptionalOutcome struct {
	Path           string `json:"path"`
	ExpectedDigest string `json:"expected_digest"`
	Status         string `json:"status"`
	Reason         string `json:"reason"`
	Required       bool   `json:"required"`
}

OptionalOutcome retains the original acquisition disposition of an unselected artifact.

type PTXData

type PTXData struct {
	FunctionOffsetUnknown bool           `json:"function_offset_unknown,omitempty"`
	ArtifactDigest        string         `json:"artifact_digest,omitempty"`
	Geometry              *bpf.Geometry  `json:"geometry,omitempty"`
	Schema                *kernel.Schema `json:"schema,omitempty"`
	KernelName            string         `json:"kernel_name"`
	TargetArch            string         `json:"target_arch"`
	FunctionOffset        uint64         `json:"function_offset"`
	CodeSize              uint64         `json:"code_size"`
}

PTXData holds kernel instrumentation input parameters.

type PairIdentity

type PairIdentity struct {
	Version                  int                    `json:"version"`
	RegistrationDigest       string                 `json:"registration_digest"`
	ProtocolDigest           string                 `json:"protocol_digest"`
	LedgerDigest             string                 `json:"ledger_digest"`
	CandidateEnvelopeDigest  string                 `json:"candidate_envelope_digest"`
	ComparatorEnvelopeDigest string                 `json:"comparator_envelope_digest"`
	CandidateRawDigest       string                 `json:"candidate_raw_digest"`
	ComparatorRawDigest      string                 `json:"comparator_raw_digest"`
	SelectedCells            []SelectedCellIdentity `json:"selected_cells"`
	RoleScopeIDs             []string               `json:"role_scope_ids"`
	CheckedBindings          []CheckedBinding       `json:"checked_bindings"`
	OptionalOutcomes         []OptionalOutcome      `json:"optional_outcomes"`
	PairDigest               string                 `json:"pair_digest"`
}

PairIdentity retains explicit bounded evidence identities, not acquisition authority.

type PendingLaunchObservation

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

PendingLaunchObservation retains the same read-only owner view used at begin. Its zero value is unavailable. It does not execute or request baseline work. Complete may be retried after a read failure, but records at most one outcome.

func BeginLaunchObservation

func BeginLaunchObservation(ctx context.Context, evaluator *Evaluator, source bpf.LaunchSource, reader InvocationObservationReader, options LaunchObservationOptions) (*PendingLaunchObservation, error)

BeginLaunchObservation reads an existing PTX descriptor and fresh original fallback owner, then evaluates the built-in PTX shadow policy. It never loads, launches or closes an owner. Baseline execution remains with the caller. The returned snapshot ID identifies observation replay, not kernel replay.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/kernel"
	"github.com/tmc/lib/nvidia/x/obs/bpf"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	artifact, err := kernel.NewArtifact(kernel.KindPTX, []byte(".version 7.0\n.target sm_80\n.address_size 64\n.visible .entry kernel() { ret; }\n"), "kernel", kernel.Schema{}, "sm_80")
	if err != nil {
		panic(err)
	}
	source, err := bpf.NewArtifactSource(artifact, bpf.Geometry{Grid: [3]uint32{1, 1, 1}, Block: [3]uint32{32, 1, 1}})
	if err != nil {
		panic(err)
	}
	evaluator, err := diag.NewEvaluator(4)
	if err != nil {
		panic(err)
	}
	// Supply the existing caller-owned loaded original's view here. This example
	// uses an unready owner and refuses observation without loading or launching.
	owner := new(bpf.LoadedInjection)
	_, err = diag.BeginLaunchObservation(context.Background(), evaluator, source, owner.ObservationReader(), diag.LaunchObservationOptions{
		Source: "example-host-epoch", Sequence: 1,
		Policy: diag.PolicyInfo{Name: "artifact-ptx", Version: "1", Domain: diag.DomainPTXInstrument, Seed: 23},
	})
	fmt.Println(err != nil, len(evaluator.Snapshots()))
}
Output:
true 0

func (*PendingLaunchObservation) Complete

func (p *PendingLaunchObservation) Complete(ctx context.Context) error

Complete records producer-reported completion from the retained owner view. Its timestamp is host completion publication, and latency is unavailable. Missing, failed, pending or changed-owner receipts leave the outcome absent.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	var pending *diag.PendingLaunchObservation
	fmt.Println(pending.Complete(context.Background()) != nil)
}
Output:
true

func (*PendingLaunchObservation) SnapshotID

func (p *PendingLaunchObservation) SnapshotID() string

SnapshotID returns the evaluated input's ID, or empty for an unavailable token.

Example
var pending *PendingLaunchObservation
fmt.Printf("%q\n", pending.SnapshotID())
Output:
""

type PerformanceChange

type PerformanceChange struct {
	Channel   timing.TimingKind `json:"channel"`
	Baseline  time.Duration     `json:"baseline"`
	Candidate time.Duration     `json:"candidate"`
	Delta     time.Duration     `json:"delta"`
	Ratio     float64           `json:"ratio"`
}

PerformanceChange captures timing metric delta on a specific timing channel.

type PhaseCensus

type PhaseCensus struct {
	Phase          CmpPhase
	SummedKernelNs int64 // Sum of individual kernel launch durations (or Unmeasured)
	GPUBusyNs      int64 // Duration of the union of GPU execution intervals (or Unmeasured)
	HostElapsedNs  int64 // Duration of host CPU wall time (or Unmeasured)
	APICallNs      int64 // Duration of driver/runtime API calls (or Unmeasured)
	Families       map[string]KernelMetric
	Entries        []obsmodel.Entry
}

PhaseCensus stores the census partitioned by workload phase.

func BuildPhaseCensus

func BuildPhaseCensus(phase CmpPhase, launches []obsmodel.CensusLaunch, coster obsmodel.Coster, fc *FamilyClassifier) (PhaseCensus, error)

BuildPhaseCensus aggregates launches for a phase and groups them by architectural family. It computes both SummedKernelNs (sum of individual launch durations) and GPUBusyNs (duration of the union of GPU execution intervals).

func ExtractPhaseCensus

func ExtractPhaseCensus(c *obsmodel.CensusCapture, phase CmpPhase, coster obsmodel.Coster, fc *FamilyClassifier) (PhaseCensus, error)

ExtractPhaseCensus extracts launches from the capture for the given phase and builds its PhaseCensus.

func ExtractPhases

func ExtractPhases(c *obsmodel.CensusCapture, coster obsmodel.Coster, fc *FamilyClassifier) (prefill, decode PhaseCensus, err error)

ExtractPhases extracts both prefill and decode PhaseCensus from a capture.

func (PhaseCensus) Duration

func (p PhaseCensus) Duration() time.Duration

Duration returns the summed kernel execution duration for this phase.

func (PhaseCensus) GPUBusyDuration

func (p PhaseCensus) GPUBusyDuration() time.Duration

GPUBusyDuration returns the duration of the union of GPU execution intervals for this phase.

func (PhaseCensus) SummedKernelDuration

func (p PhaseCensus) SummedKernelDuration() time.Duration

SummedKernelDuration returns the sum of kernel launch execution durations for this phase.

func (PhaseCensus) TimingDecomposition

func (p PhaseCensus) TimingDecomposition() TimingDecomposition

TimingDecomposition returns the decomposed non-additive timing channels for this phase.

type PhaseReport

type PhaseReport = re_obsmodel.PhaseReport

type PlanOptions

type PlanOptions struct {
	WarmupRuns      int
	Rounds          int
	Order           string
	ExecutionScope  TimingScope
	StoppingRules   RegressStoppingRules
	NullControls    NullControlConfig
	Sources         []ArtifactRef
	Binaries        []ArtifactRef
	Libraries       []LibraryRef
	Inputs          []InputRef
	Oracle          CorrectnessOracle
	DeviceOverrides *DeviceConfig
}

PlanOptions configures experiment plan generation from an incident.

type PlanReceipt

type PlanReceipt struct {
	PlanID               string        `json:"plan_id"`
	PlanDigest           string        `json:"plan_digest"`
	IncidentID           string        `json:"incident_id"`
	CreatedAt            time.Time     `json:"created_at"`
	ArtifactClosureValid bool          `json:"artifact_closure_valid"`
	ArtifactsVerified    int           `json:"artifacts_verified"`
	ImmutableRefs        []ArtifactRef `json:"immutable_refs"`
}

PlanReceipt certifies the generation and validation of an ExperimentPlan.

type Planned

type Planned = re_obsmodel.Planned

type Policy

type Policy interface {
	// Info returns the policy's name, version, domain, and seed.
	Info() PolicyInfo
	// Evaluate produces a proposed decision given an observed input.
	Evaluate(ctx context.Context, in Input) (Decision, error)
}

Policy defines an observational policy evaluator.

func NewAdaptivePrefetchPolicy

func NewAdaptivePrefetchPolicy(info PolicyInfo) (Policy, error)

NewAdaptivePrefetchPolicy constructs a sequential/stride prefetch policy modeled after gpu_ext prefetch.

func NewFIFOPolicy

func NewFIFOPolicy(info PolicyInfo) (Policy, error)

NewFIFOPolicy constructs a FIFO UVM eviction policy modeled after gpu_ext eviction_fifo.bpf.c.

func NewLFUPolicy

func NewLFUPolicy(info PolicyInfo) (Policy, error)

NewLFUPolicy constructs a Least-Frequently-Used eviction policy with PID priority quota.

func NewMRUPolicy

func NewMRUPolicy(info PolicyInfo) (Policy, error)

NewMRUPolicy constructs a Most-Recently-Used eviction policy.

func NewPTXShadowPolicy

func NewPTXShadowPolicy(info PolicyInfo) (Policy, error)

NewPTXShadowPolicy constructs an observation-only policy for inspecting PTX kernels. It verifies that zero PTX mutations, code injections, or rewrites are emitted.

func NewPriorityTimeslicePolicy

func NewPriorityTimeslicePolicy(info PolicyInfo) (Policy, error)

NewPriorityTimeslicePolicy constructs a timeslice scheduling policy based on process priority.

type PolicyInfo

type PolicyInfo struct {
	Name       string            `json:"name"`
	Version    string            `json:"version"`
	Domain     Domain            `json:"domain"`
	Parameters map[string]string `json:"parameters,omitempty"`
	Seed       int64             `json:"seed"`
}

PolicyInfo identifies the policy implementation, version, and configuration.

func RegisteredCorpusPolicies

func RegisteredCorpusPolicies() []PolicyInfo

RegisteredCorpusPolicies returns a deterministic catalog of standard policy configurations.

func (PolicyInfo) Validate

func (pi PolicyInfo) Validate() error

Validate ensures policy metadata is complete.

type Population

type Population struct {
	Family          string `json:"family"`
	DenominatorUnit string `json:"denominator_unit"`
	Declared        uint64 `json:"declared"`
	Observed        uint64 `json:"observed"`
	Missing         uint64 `json:"missing"`
	Lost            uint64 `json:"lost"`
	Withheld        uint64 `json:"withheld"`
	Unknown         bool   `json:"unknown"`
}

Population retains explicit bounded evidence identities, not acquisition authority.

type PowerClockEvidence

type PowerClockEvidence struct {
	ClockThrottled bool                     `json:"clock_throttled"`
	PowerCapped    bool                     `json:"power_capped"`
	Intervals      []tracecontract.Interval `json:"intervals,omitempty"`
}

PowerClockEvidence captures power capping and clock throttling telemetry.

type PreEntryEvent

type PreEntryEvent struct {
	Span        tracecontract.Interval     `json:"span"`
	Submission  obsworkload.HostSubmission `json:"submission"`
	Complete    bool                       `json:"complete"`
	SourceClass string                     `json:"source_class"`
}

PreEntryEvent measures application submission-ready to API entry, separately from the API call. Submission identifies the operation at API entry; its TID does not identify an earlier unpinned application interval. SourceClass is native, synthetic, imported or managed. These declarations do not authenticate a producer; the caller must retain and validate the source receipt and bytes.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/cudaprof/tracecontract"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	// Constructed replay timing; the API has its own entry-to-return span.
	event := diag.PreEntryEvent{Span: tracecontract.Interval{Start: 10, End: 400, Clock: "replay"}, Complete: true, SourceClass: "synthetic"}
	fmt.Println(event.Span.Duration(), event.SourceClass)
}
Output:
390 synthetic

type Precision

type Precision = re_obsmodel.Precision

type PrecisionPeak

type PrecisionPeak = re_obsmodel.PrecisionPeak

type PrefetchData

type PrefetchData struct {
	PID          int    `json:"pid"`
	FaultAddr    uint64 `json:"fault_addr"`
	FirstPage    uint16 `json:"first_page"`
	OuterPage    uint16 `json:"outer_page"`
	AccessBitmap uint64 `json:"access_bitmap"`
	StrideBytes  int64  `json:"stride_bytes"`
}

PrefetchData holds fault and address range prefetch input parameters.

type PreregisteredBudgets

type PreregisteredBudgets struct {
	MaxThroughputDegradationPct float64 `json:"max_throughput_degradation_pct"`
	MaxRSSGrowthMB              float64 `json:"max_rss_growth_mb"`
	MaxTailLatencyP99Pct        float64 `json:"max_tail_latency_p99_pct"`
	MaxIncorrectJoins           int     `json:"max_incorrect_joins"`
	MinNoFaultRejectionPct      float64 `json:"min_no_fault_rejection_pct"`
	MinHeldOutDiagnosisPct      float64 `json:"min_held_out_diagnosis_pct"`
}

PreregisteredBudgets specifies acceptance thresholds frozen before qualification.

func DefaultBudgets

func DefaultBudgets() PreregisteredBudgets

DefaultBudgets returns conservative, preregistered qualification thresholds.

type PreregistrationCheck

type PreregistrationCheck struct {
	ChronologyArtifact                RegistrationArtifact `json:"chronology_artifact"`
	RegistrationSeenBeforeAcquisition bool                 `json:"registration_seen_before_acquisition"`
	RegisteredAt                      time.Time            `json:"registered_at"`
	FirstAcquisitionAt                time.Time            `json:"first_acquisition_at"`
}

PreregistrationCheck retains explicit bounded evidence identities, not acquisition authority.

type ProbeAllocation

type ProbeAllocation = re_obsprobe.ProbeAllocation

type ProbeCapture

type ProbeCapture = re_obsprobe.ProbeCapture

type ProbeIdentity

type ProbeIdentity = re_obsprobe.ProbeIdentity

type ProbeLaunch

type ProbeLaunch = re_obsprobe.ProbeLaunch

type ProbeOutlier

type ProbeOutlier struct {
	Sequence, EntryTimestamp, ReturnTimestamp, HostDurationNanos uint64
	Record                                                       iket.Record
}

ProbeOutlier is one observed long host API interval. Record retains the existing probe identity/binding/demangler labels. A missing KernelName is accompanied by kernel_identity_reason; a name establishes caller consistency only, not physical loading, successful execution or a GPU duration.

type ProbeReport

type ProbeReport struct {
	RawSHA256      string
	Records        int
	Gap, Partial   bool
	Process        obsprobe.Process
	ThreadID       uint32
	Clock, Epoch   string
	ThresholdNanos uint64
	Outliers       []ProbeOutlier
}

ProbeReport describes a bounded post-drain input. RawSHA256 hashes the exact consumed JSONL bytes. Gap also includes sequence and pairing discontinuities. Partial is always true: received observations cannot prove complete capture.

func ReadProbeReport

func ReadProbeReport(ctx context.Context, input io.Reader, o ProbeReportOptions) (*ProbeReport, error)

ReadProbeReport selects host API outliers from newline-terminated JSON cudatracehost.Result records, as emitted by CollectHostEvidence or the collector CLI. It uses Decode, RecordWithBindings/Identify and the supplied Demangler.Records rather than inferring a kernel from a function address. Invalid framing/context returns no report. A demangler failure returns the report with retained names/failure labels and an error. It never attaches a probe, loads an artifact, reads process mappings or calls a GPU API. The reader must supply finite post-drain input; context cancellation cannot interrupt a blocked call to an arbitrary Reader's Read method.

Example
package main

import (
	"bytes"
	"context"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/bpf"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"time"
)

func main() {
	process := diag.Process{PID: 12, Generation: 30}
	// Recorded input preserves the live collector's unknown address space.
	capture := &diag.ProbeCapture{Identity: diag.ProbeIdentity{Process: process, ThreadID: 14, ThreadGeneration: 44, ThreadGenerationKnown: true, Library: "/recorded/libcuda.so", BuildID: "recorded-build", Version: "fixture-v1", Symbol: "cuLaunchKernel", ABI: "linux-amd64-sysv-v1", Provenance: "example-recorded-input"}}
	binary.LittleEndian.PutUint16(capture.Data[:], 1)
	binary.LittleEndian.PutUint16(capture.Data[2:], 3)
	binary.LittleEndian.PutUint64(capture.Data[8:], 1)
	binary.LittleEndian.PutUint64(capture.Data[16:], 100)
	binary.LittleEndian.PutUint64(capture.Data[32:], 99)
	raw := bpf.TraceHostResult{Capture: capture, Call: &bpf.CallInterval{Process: process, TID: 14, ThreadGeneration: 44, ThreadGenerationKnown: true, ExecID: 9, PairingStatus: "verified_thread_lifetime", EntryTimestamp: 100, ReturnTimestamp: 250, Clock: "linux_monotonic", Epoch: "recorded-boot"}}
	var input bytes.Buffer
	if err := json.NewEncoder(&input).Encode(raw); err != nil {
		fmt.Println(err)
		return
	}
	r, err := diag.ReadProbeReport(context.Background(), &input, diag.ProbeReportOptions{
		Manifest: bpf.Manifest{Process: process, Backend: "bpf", Clock: "linux_monotonic", Epoch: "recorded-boot"},
		ThreadID: 14, ThreadGeneration: 44, ExecID: 9, AddressSpace: 1, ModuleGeneration: 7,
		FirstSequence: 1, LastSequence: 1, LossKnown: true,
		Received: time.Unix(1700000000, 0), Threshold: 100 * time.Nanosecond,
		MaxBytes: 64 << 10, MaxLineBytes: 16 << 10, MaxRecords: 8, MaxOutliers: 4,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(len(r.Outliers), r.Outliers[0].HostDurationNanos, r.Partial)
	fmt.Println(r.Outliers[0].Record.Labels["kernel_identity_reason"])
}
Output:
1 150 true
capture address space unavailable

type ProbeReportOptions

type ProbeReportOptions struct {
	Manifest                                                 bpf.Manifest
	ThreadID                                                 uint32
	ThreadGeneration, ExecID, AddressSpace, ModuleGeneration uint64
	FirstSequence, LastSequence                              uint64
	LossKnown                                                bool
	Dropped                                                  uint64
	Gap                                                      bool
	Received                                                 time.Time
	Threshold                                                time.Duration
	MaxBytes                                                 int64
	MaxLineBytes, MaxRecords, MaxOutliers                    int
	Bindings                                                 []obsprobe.Binding
	Demangler                                                *obsprobe.Demangler
}

ProbeReportOptions declares the context of a drained collector JSONL stream. Manifest supplies process, backend, monotonic clock and boot epoch. Other manifest fields do not establish coverage or authenticate this input. ThreadGeneration, ExecID, AddressSpace and ModuleGeneration are independent caller assertions; zero leaves kernel attribution unavailable. Capture AddressSpace is never filled from these assertions or from a binding.

FirstSequence and LastSequence identify the inclusive captured-call range, not raw entry/scheduler line numbers. LossKnown and Dropped describe the caller's post-drain loss receipt; they cannot establish complete coverage. Every resulting report remains partial. Threshold selects host API entry-to-return durations, never GPU execution or pre-entry launch latency.

All limits must be positive. MaxBytes is at most 64 MiB, MaxLineBytes at most 256 KiB, MaxRecords at most 65536 and MaxOutliers at most 4096. Bindings admits at most 256 entries and 16 MiB of artifact bytes in total. Demangler is optional; give it capacity for MaxOutliers. Its actual process is invoked only after the entire stream has been consumed and validated, with a finite context deadline. Bindings and the demangler must not be concurrently mutated or used during this call.

type ProbeSource

type ProbeSource = re_obsprobe.ProbeSource

type Process

type Process = re_obsprobe.Process

type ProcessGenID

type ProcessGenID = re_obsworkload.ProcessGenID

type PropertyGate

type PropertyGate struct {
	Property      string `json:"property"`
	GateName      string `json:"gate_name"`
	Disposition   string `json:"disposition"` // "passed", "failed", "withheld", "unavailable", "pending"
	MeasuredValue string `json:"measured_value"`
	Threshold     string `json:"threshold"`
	Reason        string `json:"reason"`
	Provenance    string `json:"provenance"`
}

PropertyGate holds the pass/fail determination for an evaluated property.

type PropertyMeasurement

type PropertyMeasurement struct {
	Unit        string   `json:"unit,omitempty"`
	Denominator uint64   `json:"denominator,omitempty"`
	Uncertainty *float64 `json:"uncertainty,omitempty"`
	Property    string   `json:"property"`
	Status      string   `json:"status"`
	Value       float64  `json:"value"`
	Reason      string   `json:"reason,omitempty"`
}

PropertyMeasurement retains an observed metric separately from unavailable evidence. Property is attribution, diagnosis, cost or reproducibility. Lower is better.

type Protocol

type Protocol struct {
	Comparison        *ComparisonSpec      `json:"comparison,omitempty"`
	Tools             []ToolSpec           `json:"tools,omitempty"`
	PropertyLimits    map[string]float64   `json:"property_limits,omitempty"`
	Name              string               `json:"name"`
	Phase             EvalPhase            `json:"phase"`
	Frozen            bool                 `json:"frozen"`
	FrozenDigest      string               `json:"frozen_digest,omitempty"`
	FrozenTimestamp   time.Time            `json:"frozen_timestamp,omitempty"`
	Workloads         []WorkloadSpec       `json:"workloads"`
	Hardware          HardwareClosure      `json:"hardware"`
	Budgets           PreregisteredBudgets `json:"budgets"`
	Sampling          SamplingConfig       `json:"sampling"`
	ExecutionOrder    string               `json:"execution_order"`
	UncertaintyMethod string               `json:"uncertainty_method"`
	StoppingRules     []string             `json:"stopping_rules"`
	ExclusionRules    []string             `json:"exclusion_rules"`
}

Protocol defines the preregistered evaluation plan.

func DefaultProtocol

func DefaultProtocol(phase EvalPhase) Protocol

DefaultProtocol creates a preregistered evaluation protocol.

Example
package main

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

func main() {
	proto := diag.DefaultProtocol(diag.PhaseQualification)
	fmt.Printf("Name: %s\n", proto.Name)
	fmt.Printf("Phase: %s\n", proto.Phase)
	fmt.Printf("Max incorrect joins: %d\n", proto.Budgets.MaxIncorrectJoins)
}
Output:
Name: cudasotaeval-submission-delay-v1
Phase: qualification
Max incorrect joins: 0

func (*Protocol) Freeze

func (p *Protocol) Freeze() error

Freeze locks the protocol parameters prior to qualification runs.

func (*Protocol) Validate

func (p *Protocol) Validate() error

Validate verifies protocol structural correctness and completeness.

type Provenance

type Provenance = re_obsmodel.Provenance

type QualificationAttempt

type QualificationAttempt struct {
	Path     string                `json:"path"`
	SHA256   string                `json:"sha256"`
	Evidence QualificationEvidence `json:"evidence"`
}

QualificationAttempt preserves a previous pass, failure or withheld attempt. SHA256 authenticates the envelope, which is checked against Evidence.

type QualificationCell

type QualificationCell struct {
	ID           string                   `json:"id"`
	CapabilityID string                   `json:"capability_id"`
	Capability   string                   `json:"capability"`
	Gate         string                   `json:"gate"`
	Status       string                   `json:"status"`
	SourcePaths  []string                 `json:"source_paths"`
	Consumers    []string                 `json:"consumers"`
	DependsOn    []string                 `json:"depends_on,omitempty"`
	Closure      QualificationClosure     `json:"closure"`
	Attempts     []QualificationAttempt   `json:"attempts,omitempty"`
	References   []QualificationReference `json:"references,omitempty"`
	Owner        string                   `json:"owner"`
	NextAction   string                   `json:"next_action"`
}

QualificationCell separates discovery from evidence for one declared target. Capability is supported, denied, conflicting, unsupported or unknown. Status is not-selected, unavailable, pending, failed or qualified. Gate is host, ABI, native, backend, operations, observer, diagnostic or comparison.

type QualificationClosure

type QualificationClosure struct {
	Candidate          string            `json:"candidate"`
	Tree               string            `json:"tree"`
	Base               string            `json:"base"`
	SignatureMapSHA256 string            `json:"signature_map_sha256"`
	BinarySHA256       string            `json:"binary_sha256"`
	DependenciesSHA256 string            `json:"dependencies_sha256"`
	InputsSHA256       string            `json:"inputs_sha256"`
	OutputsSHA256      string            `json:"outputs_sha256"`
	HostOS             string            `json:"host_os"`
	HostArch           string            `json:"host_arch"`
	Device             string            `json:"device"`
	Architecture       string            `json:"architecture"`
	ProducerVersion    string            `json:"producer_version"`
	Libraries          map[string]string `json:"libraries"`
	Toolchain          string            `json:"toolchain"`
	Topology           string            `json:"topology"`
	Workload           string            `json:"workload"`
	Deployment         string            `json:"deployment"`
	Observer           string            `json:"observer"`
}

QualificationClosure pins the source, executable and observation environment. A receipt transfers only when every field matches; source identity alone does not transfer native evidence to another executable or target. Unknown fields may be empty in pending cells, but passed receipts require a complete closure.

type QualificationEvidence

type QualificationEvidence struct {
	CellID    string               `json:"cell_id"`
	Gate      string               `json:"gate"`
	Status    string               `json:"status"`
	Closure   QualificationClosure `json:"closure"`
	RawPath   string               `json:"raw_path"`
	RawSHA256 string               `json:"raw_sha256"`
	Command   []string             `json:"command"`
	Verifier  string               `json:"verifier"`
}

QualificationEvidence is the immutable receipt envelope stored under an artifact root. RawSHA256 authenticates a separately retained raw output. Verifier identifies the external verifier, not this consistency checker. A valid envelope does not establish that its author's measurements are true.

type QualificationLedger

type QualificationLedger struct {
	Version int                 `json:"version"`
	Cells   []QualificationCell `json:"cells"`
}

QualificationLedger is a bounded, versioned inventory, not a test executor. Commands retained in receipts are never executed by this package.

func ReadQualificationLedger

func ReadQualificationLedger(r io.Reader) (*QualificationLedger, error)

ReadQualificationLedger reads at most 4 MiB and rejects unknown fields, duplicate JSON keys, trailing values and invalid dependency graphs.

Example
var output bytes.Buffer
if err := WriteQualificationLedger(&output, pendingLedgerExample()); err != nil {
	fmt.Println(err)
	return
}
ledger, err := ReadQualificationLedger(&output)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(ledger.Cells[0].Status)
Output:
pending

func (QualificationLedger) Validate

func (l QualificationLedger) Validate() error

Validate checks structural consistency without accessing receipts or hardware.

Example
fmt.Println(pendingLedgerExample().Validate())
Output:
<nil>

type QualificationReference

type QualificationReference struct {
	Path   string `json:"path"`
	SHA256 string `json:"sha256"`
	Scope  string `json:"scope"`
	Reason string `json:"reason"`
}

QualificationReference retains historical evidence whose execution closure is absent or incompatible. Verifying its bytes never qualifies a selected cell. An empty SHA256 retains a missing artifact as unknown.

type QualificationResult

type QualificationResult struct {
	CellID             string `json:"cell_id"`
	Capability         string `json:"capability"`
	Status             string `json:"status"`
	Gate               string `json:"gate"`
	Accepted           bool   `json:"accepted"`
	ReferencesVerified int    `json:"references_verified"`
	Reason             string `json:"reason,omitempty"`
	Owner              string `json:"owner"`
	NextAction         string `json:"next_action"`
}

QualificationResult reports evidence consistency separately from discovery. Accepted means the retained envelope and raw output match the selected cell; it does not certify physical measurements or authorize a profiling run.

func VerifyQualificationLedger

func VerifyQualificationLedger(ctx context.Context, root string, l QualificationLedger) ([]QualificationResult, error)

VerifyQualificationLedger checks retained evidence under root using a traversal-resistant os.Root. Missing, corrupt or scope-incompatible evidence produces pending results, never a promoted pass. All attempts are checked; only the last attempt can qualify a cell. Dependencies must also be accepted. Each artifact is bounded to 4 MiB and the combined read budget is 64 MiB.

Example
results, err := VerifyQualificationLedger(context.Background(), ".", pendingLedgerExample())
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(results[0].Gate, results[0].Status, results[0].Accepted)
Output:
native pending false

type QualityCheck

type QualityCheck struct {
	ExpectedArtifacts     []RegistrationArtifact `json:"expected_artifacts"`
	ObservedArtifacts     []RegistrationArtifact `json:"observed_artifacts"`
	QualityContractDigest string                 `json:"quality_contract_digest"`
	OracleMethodDigest    string                 `json:"oracle_method_digest"`
	OutputNames           []string               `json:"output_names"`
	Passed                bool                   `json:"passed"`
	Missing               uint64                 `json:"missing"`
	Nonfinite             uint64                 `json:"nonfinite"`
}

QualityCheck retains explicit bounded evidence identities, not acquisition authority.

type QuarantineConfig

type QuarantineConfig struct {
	// Command is the child's argument vector. Its program must call
	// [ServeQuarantine] before doing anything else. Empty means the
	// running executable with no arguments.
	Command []string

	// Env holds extra KEY=VALUE pairs appended to the parent's environment.
	// The child needs the parent's gpu-lock lease (GPU_LOCK_HELD and
	// GPU_LOCKDIR), which it inherits from that environment.
	Env []string

	// Dir receives the request, report, output and log files, which are
	// kept. Empty means a temporary directory removed on return.
	Dir string

	// Startup bounds everything in the child except the launch: process
	// start, CUDA initialization, module load and copies. The parent kills
	// the child at Deadline+Startup. Zero means one minute.
	Startup time.Duration

	// Sanitizers lists compute-sanitizer tools to run the child under after
	// a passing launch, one run each. Each run's output bytes are classified
	// like the first run's. A tool that cannot run leaves the verdict a
	// pass but makes [QuarantineVerdict.OK] false.
	Sanitizers []Tool

	// SanitizerPath is the compute-sanitizer executable; empty means search.
	SanitizerPath string

	// SanitizerDeadline replaces Deadline in sanitizer runs, which are
	// much slower. Zero means 100 times Deadline.
	SanitizerDeadline time.Duration
}

A QuarantineConfig says how to start the child.

type QuarantineElement

type QuarantineElement struct {
	Output    string
	Index     int
	Got, Want uint32
}

A QuarantineElement is one output element that differs from the reference.

type QuarantineRange

type QuarantineRange struct {
	Output     string
	Start, End int
}

A QuarantineRange is a half-open range of float32 elements in one output.

type QuarantineSanitizerRun

type QuarantineSanitizerRun struct {
	Tool Tool

	// Ran reports that the tool produced a report and the child under it
	// completed a passing launch. When false, Reason says why, and the run
	// proves nothing about the tool's checks.
	Ran     bool
	Outcome string
	Defect  bool

	// Verdict is the parent's verdict on the launch under the tool.
	Verdict string `json:",omitempty"`
	Reason  string `json:",omitempty"`
}

A QuarantineSanitizerRun records one compute-sanitizer run.

type QuarantineSpan

type QuarantineSpan struct {
	Allocation     int
	Offset, Length int
}

A QuarantineSpan is a changed byte span in one allocation.

type QuarantineSpec

type QuarantineSpec struct {
	// Launch is the kernel, geometry, arguments and initial allocation
	// contents. It must be valid ([ReproLaunch.Validate]).
	Launch *ReproLaunch

	// Outputs names the buffer arguments the kernel must write. Each must
	// have a nonzero size that is a multiple of 4: elements are compared as
	// float32 bits. Every output is overwritten with the fill before the
	// launch, so a kernel that reads its output (y += x), or reads another
	// argument aliasing an output, sees NaN and fails with a mismatch.
	Outputs []string

	// Reference holds the expected bytes of each output, by name. It stays
	// in the parent: the child never sees it.
	Reference map[string][]byte

	// Deadline bounds the launch, from submission to completion.
	Deadline time.Duration
}

A QuarantineSpec is one launch to try in a child process.

type QuarantineVerdict

type QuarantineVerdict struct {
	Verdict  string
	Reason   string `json:",omitempty"`
	LaunchID string

	// Fill is the float32 NaN bit pattern this run wrote over every output
	// element. It is chosen at random per run and differs from every
	// reference element, but a kernel can still see an all-NaN output, so
	// a hostile kernel can tell it is quarantined.
	Fill uint32

	// PID is the child that ran the launch; 0 when none reported.
	PID int

	// Killed reports that the parent killed the child at its deadline.
	Killed bool `json:",omitempty"`

	// OutOfBounds lists changed byte spans outside the outputs, and
	// OutOfBoundsBytes counts all changed bytes. Offsets are relative to the
	// start of the captured allocation: a negative offset is in the guard
	// band before it, an offset at or past its length in the one after.
	OutOfBounds      []QuarantineSpan `json:",omitempty"`
	OutOfBoundsBytes int              `json:",omitempty"`

	// Unwritten lists element ranges that still held Fill, and
	// UnwrittenElements counts them.
	Unwritten         []QuarantineRange `json:",omitempty"`
	UnwrittenElements int               `json:",omitempty"`

	// Mismatches lists the first written elements that differ from the
	// reference, and MismatchElements counts them.
	Mismatches       []QuarantineElement `json:",omitempty"`
	MismatchElements int                 `json:",omitempty"`

	Sanitizers []QuarantineSanitizerRun `json:",omitempty"`

	// Stderr is the tail of the child's standard error, for diagnosis.
	Stderr string `json:",omitempty"`

	Duration time.Duration
}

A QuarantineVerdict is the parent's verdict on one quarantined launch.

func Quarantine

Quarantine runs spec's launch once in a child process with its own CUDA context and returns the verdict. The parent prefills every output with a random NaN, surrounds every allocation with random guard bands, and sends the child only the launch and those bytes. The child launches and returns every byte afterwards, and the parent classifies them against the reference, which never leaves the parent. The parent kills the child's process group if it outlives Deadline+Startup, so a hung or faulting kernel never touches the caller's process or context.

On a node where GPU code can reach host memory, a hostile kernel can read the fill and guard values in the child and restore them, so out-of-bounds and unwritten detection are best effort against it. It cannot learn the reference, so passing still requires the correct output bytes.

The returned error is non-nil only when spec or cfg is invalid, the request cannot be written, or ctx is canceled; everything the candidate does is reported in the verdict.

Example

The test binary is its own quarantine child: TestMain calls ServeQuarantine first. With no gpu-lock lease to inherit, the child refuses before touching a GPU, and the parent reports why.

spec, err := newQuarantineFixture()
if err != nil {
	log.Fatal(err)
}
dir, err := os.MkdirTemp("", "quarantine-example-")
if err != nil {
	log.Fatal(err)
}
defer os.RemoveAll(dir)
v, err := Quarantine(context.Background(), spec, QuarantineConfig{
	Env: []string{"GPU_LOCK_HELD=", "GPU_LOCKDIR=" + dir},
	Dir: dir,
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(v.Verdict, v.OK())
Output:
no-lease false

func (*QuarantineVerdict) OK

func (v *QuarantineVerdict) OK() bool

OK reports whether v is a pass and every requested sanitizer run ran.

type RawIDs

type RawIDs = re_obsworkload.RawIDs

type Reading

type Reading = re_obsmodel.Reading

type Reason

type Reason = re_obsworkload.Reason

type ReceiptComparison

type ReceiptComparison struct {
	TimingKind   timing.TimingKind
	CDuration    time.Duration
	GoDuration   time.Duration
	Delta        time.Duration // Go - C
	Speedup      float64       // C / Go
	NullDrift    time.Duration
	ExceedsDrift bool
}

ReceiptComparison holds the differential result of comparing two trial receipts.

func CompareReceipts

func CompareReceipts(cReceipt, goReceipt timing.Receipt, kind timing.TimingKind, nullDrift time.Duration) (ReceiptComparison, error)

CompareReceipts compares two trial receipts on an explicit timing kind against a null drift threshold. It rejects receipts that are incomplete, lack the requested timing kind, or specify a negative drift.

type Record

type Record = re_obsmodel.Record

type ReduceOptions

type ReduceOptions struct {
	Repeats       int
	MaxCandidates int
	AllowOneOff   bool
}

ReduceOptions bounds reduction work. Neither field has a default. At most Repeats*(MaxCandidates+1) runner calls are made. AllowOneOff permits reducing a baseline that reproduced exactly once.

type Reduction

type Reduction struct {
	Original        Case
	Reduced         Case
	Baseline        Measurement
	Attempts        []ReductionAttempt
	IdentityDrift   int
	CandidateRuns   int
	NoReduction     string
	BudgetExhausted bool
}

Reduction retains the fresh baseline and every candidate attempt. Original and Reduced expose the sizes of all supported dimensions. NoReduction gives the reason when no candidate was accepted; BudgetExhausted distinguishes bounded stopping from exhausting all proposed reductions.

func Reduce

func Reduce(ctx context.Context, original Case, finding ptx.RunRecord, opts ReduceOptions, replay func(context.Context, Case) (ptx.RunRecord, error)) (Reduction, error)

Reduce shrinks explicit uint64 inputs, tensor extents and launch dimensions in the documented order, preserving source text and the original failure's identity and empirical reproduction rate. replay adapts the existing campaign runner; it must use fresh processes when candidates can fault. Host fixtures may supply simulated run records, which are not native proof. Partial results are returned on cancellation or invalid execution evidence.

Example
// This fixture demonstrates reduction without a device. A native adapter
// must supply actual campaign run records, not these simulated receipts.
original := reductionCase()
r, err := Reduce(context.Background(), original, mismatchRecord(0),
	ReduceOptions{Repeats: 3, MaxCandidates: 100}, hostReplay)
fmt.Println(len(original.Inputs), len(r.Reduced.Inputs))
fmt.Println(original.Block[0], r.Reduced.Block[0])
fmt.Println(r.Baseline.Reproductions, len(r.Baseline.Runs), err)
Output:
4 1
64 2
3 3 <nil>

type ReductionAttempt

type ReductionAttempt struct {
	Dimension   string
	Case        Case
	Measurement Measurement
	Accepted    bool
}

ReductionAttempt retains the candidate, every executed run, and acceptance.

type RegionWork

type RegionWork = re_obsmodel.RegionWork

type RegisteredComparison

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

RegisteredComparison retains factual paired results. Copies and repeated comparisons share one claim-attempt lease; none establish authenticity.

func CompareRegisteredPair

func CompareRegisteredPair(ctx context.Context, p ValidatedRegisteredPair) (RegisteredComparison, error)

CompareRegisteredPair returns factual matched results from the retained original raw bytes. It does not acquire artifacts or authenticate measurements. Every result and copy shares the pair's single-use claim lease.

Example
_, err := CompareRegisteredPair(context.Background(), ValidatedRegisteredPair{})
fmt.Println(err)
Output:
paired comparison: invalid handle

func (RegisteredComparison) Results

func (c RegisteredComparison) Results() []MatchedResult

Results returns detached factual results, never an accepted claim.

Example
var comparison RegisteredComparison
fmt.Println(len(comparison.Results()))
Output:
0

type RegisteredReceipt

type RegisteredReceipt struct {
	Version            int                    `json:"version"`
	RegistrationDigest string                 `json:"registration_digest"`
	CellID             string                 `json:"cell_id"`
	Arm                string                 `json:"arm"`
	ToolReceipt        RegistrationArtifact   `json:"tool_receipt"`
	SourceClosure      QualificationClosure   `json:"source_closure"`
	ProducerArtifacts  []RegistrationArtifact `json:"producer_artifacts"`
	InputArtifacts     []RegistrationArtifact `json:"input_artifacts"`
	OutputArtifacts    []RegistrationArtifact `json:"output_artifacts"`
	EvidenceBindings   []EvidenceBinding      `json:"evidence_bindings"`
	Population         []Population           `json:"population"`
	AcquisitionBounds  []AcquisitionBounds    `json:"acquisition_bounds"`
}

RegisteredReceipt retains explicit bounded evidence identities, not acquisition authority.

func ReadRegisteredReceipt

func ReadRegisteredReceipt(r io.Reader) (RegisteredReceipt, error)

ReadRegisteredReceipt reads one canonical v1 envelope, bounded to 4 MiB. It retains no authority and cannot construct an opaque pair. The caller owns the reader and interruption of a blocked read.

Example
_, err := ReadRegisteredReceipt(strings.NewReader("{}"))
fmt.Println(err)
Output:
paired receipt: missing field version

type Registration

type Registration struct {
	Version                  int                     `json:"version"`
	ID                       string                  `json:"id"`
	ParentDigest             string                  `json:"parent_digest"`
	RevisionReason           string                  `json:"revision_reason"`
	Task                     string                  `json:"task"`
	Mode                     string                  `json:"mode"`
	Owner                    string                  `json:"owner"`
	Protocol                 Protocol                `json:"protocol"`
	SourceLibraries          []RegistrationLibrary   `json:"source_libraries"`
	Source                   QualificationClosure    `json:"source"`
	PrerequisiteLedgerSHA256 string                  `json:"prerequisite_ledger_sha256"`
	SelectedCells            []RegistrationCell      `json:"selected_cells"`
	TargetRows               []RegistrationTarget    `json:"target_rows"`
	Workload                 RegistrationWorkload    `json:"workload"`
	Oracle                   RegistrationOracle      `json:"oracle"`
	Clock                    RegistrationClock       `json:"clock"`
	Loss                     RegistrationLoss        `json:"loss"`
	Observer                 RegistrationObserver    `json:"observer"`
	Analysis                 RegistrationAnalysis    `json:"analysis"`
	PilotArtifacts           []RegistrationArtifact  `json:"pilot_artifacts"`
	HeldOutArtifacts         []RegistrationArtifact  `json:"held_out_artifacts"`
	Stopping                 RegistrationStopping    `json:"stopping"`
	MissingData              RegistrationMissingData `json:"missing_data"`
	Limits                   RegistrationLimits      `json:"limits"`
	RegisteredAt             time.Time               `json:"registered_at"`
	Digest                   string                  `json:"digest"`
}

Registration is a versioned, immutable plan beside the existing Protocol. Protocol must already be frozen. PrerequisiteLedgerSHA256 hashes the bytes emitted by WriteQualificationLedger; it does not bind future trial results. RegisteredAt is caller supplied and does not prove premeasurement registration. The zero value is invalid. Reading, freezing and verification execute no tests.

func ReadRegistration

func ReadRegistration(r io.Reader) (Registration, error)

ReadRegistration reads at most 4 MiB. It rejects duplicate and noncanonical keys, unknown fields, future versions, trailing data and nesting beyond 32. The caller owns the reader and interruption of a blocked read.

Example
r, _ := exampleRegistration()
var b bytes.Buffer
if err := WriteRegistration(&b, r); err != nil {
	fmt.Println(err)
	return
}
read, err := ReadRegistration(&b)
fmt.Println(err, read.ID)
Output:
<nil> example

func (Registration) Freeze

func (r Registration) Freeze(at time.Time) (Registration, error)

Freeze returns a detached immutable registration at the caller's UTC time. A local timestamp and digest are not premeasurement provenance.

Example
r, _ := exampleRegistration()
frozen, err := r.Freeze(time.Date(2026, 10, 11, 0, 0, 0, 0, time.UTC))
fmt.Println(err, frozen.Digest != "")
Output:
<nil> true

func (Registration) Validate

func (r Registration) Validate() error

Validate checks registration structure and frozen content, without reading artifacts. It does not authenticate declared policies, clocks or measurements.

Example
fmt.Println((Registration{}).Validate())
Output:
registration: invalid version or identity

type RegistrationAnalysis

type RegistrationAnalysis struct {
	Contract RegistrationContract      `json:"contract"`
	Body     *RegistrationAnalysisSpec `json:"body"`
}

RegistrationAnalysis freezes sample selection and the existing properties.

type RegistrationAnalysisSpec

type RegistrationAnalysisSpec struct {
	Repetitions   uint64                     `json:"repetitions"`
	Warmup        uint64                     `json:"warmup"`
	MinSamples    uint64                     `json:"min_samples"`
	Order         string                     `json:"order"`
	Seed          *uint64                    `json:"seed"`
	OrderArtifact *RegistrationArtifact      `json:"order_artifact"`
	Method        RegistrationArtifact       `json:"method"`
	Properties    []RegistrationPropertySpec `json:"properties"`
	Exclusions    []RegistrationArtifact     `json:"exclusions"`
}

RegistrationAnalysisSpec pins an externally supplied analysis method.

type RegistrationArtifact

type RegistrationArtifact struct {
	Path   string `json:"path"`
	SHA256 string `json:"sha256"`
}

RegistrationArtifact identifies an immutable input. Path is relative to the caller's artifact root. Its digest does not establish acquisition authenticity.

type RegistrationArtifactResult

type RegistrationArtifactResult struct {
	Artifact RegistrationArtifact `json:"artifact"`
	Required bool                 `json:"required"`
	Status   string               `json:"status"`
	Reason   string               `json:"reason"`
}

RegistrationArtifactResult retains the original expected path/digest and a bounded acquisition outcome. Consistent bytes are not authentic acquisition.

type RegistrationCell

type RegistrationCell struct {
	Applicability string `json:"applicability"`
	CellID        string `json:"cell_id"`
	CapabilityID  string `json:"capability_id"`
	Gate          string `json:"gate"`
	ClosureSHA256 string `json:"closure_sha256"`
	ReceiptSHA256 string `json:"receipt_sha256"`
	Reason        string `json:"reason"`
	Owner         string `json:"owner"`
	NextAction    string `json:"next_action"`
}

RegistrationCell selects a prerequisite from the frozen ledger snapshot. ReceiptSHA256 may be empty for a pending cell with a reason and next action. ClosureSHA256 hashes the JSON encoding of the selected QualificationClosure.

type RegistrationClock

type RegistrationClock struct {
	Contract RegistrationContract   `json:"contract"`
	Body     *RegistrationClockSpec `json:"body"`
}

RegistrationClock retains distinct timing domains and their calibrations.

type RegistrationClockDomain

type RegistrationClockDomain struct {
	ID            string               `json:"id"`
	Family        string               `json:"family"`
	Epoch         string               `json:"epoch"`
	Unit          string               `json:"unit"`
	Calibration   RegistrationArtifact `json:"calibration"`
	Uncertainty   float64              `json:"uncertainty"`
	ValidityStart int64                `json:"validity_start"`
	ValidityEnd   int64                `json:"validity_end"`
}

RegistrationClockDomain records a proposed epoch, range and absolute bound.

type RegistrationClockSpec

type RegistrationClockSpec struct {
	Domains []RegistrationClockDomain `json:"domains"`
}

RegistrationClockSpec does not infer equivalence between timing families.

type RegistrationContract

type RegistrationContract struct {
	State      string                 `json:"state"`
	ID         string                 `json:"id"`
	Notes      string                 `json:"notes"`
	Artifacts  []RegistrationArtifact `json:"artifacts"`
	Reason     string                 `json:"reason"`
	Owner      string                 `json:"owner"`
	NextAction string                 `json:"next_action"`
}

RegistrationContract describes a planned contract, not an executed method. Declared contracts have a typed body. Unknown/unavailable bodies are nil. Notes are supplemental and have no admission meaning.

type RegistrationFact

type RegistrationFact struct {
	State        string                `json:"state"`
	Value        string                `json:"value"`
	SourceSHA256 string                `json:"source_sha256"`
	Artifact     *RegistrationArtifact `json:"artifact"`
	Field        string                `json:"field"`
	Reason       string                `json:"reason"`
	Owner        string                `json:"owner"`
	NextAction   string                `json:"next_action"`
}

RegistrationFact records a supplied fact, not a measurement acceptance. State is known, unknown, unavailable, denied, conflicting or not-applicable. Known artifact bytes are verified; their named field/value binding is declared. Unknown facts retain their reason, owner and next action; they have no guessed value.

type RegistrationLibrary

type RegistrationLibrary struct {
	Name string           `json:"name"`
	Fact RegistrationFact `json:"fact"`
}

RegistrationLibrary retains a supplied loaded-library fact and its source.

type RegistrationLimits

type RegistrationLimits struct {
	MaxDurationNanos int64  `json:"max_duration_nanos"`
	MaxRecords       uint64 `json:"max_records"`
	MaxBytes         uint64 `json:"max_bytes"`
}

RegistrationLimits bounds the registered experiment. These are caller proposals, not measured resource use or permission to launch that experiment.

type RegistrationLoss

type RegistrationLoss struct {
	Contract RegistrationContract  `json:"contract"`
	Body     *RegistrationLossSpec `json:"body"`
}

RegistrationLoss pins completeness rules for each supplied record family.

type RegistrationLossFamily

type RegistrationLossFamily struct {
	Name            string `json:"name"`
	Required        bool   `json:"required"`
	DenominatorUnit string `json:"denominator_unit"`
	ExpectedRecords uint64 `json:"expected_records"`
	MaxMissing      uint64 `json:"max_missing"`
	MaxLost         uint64 `json:"max_lost"`
	Handling        string `json:"handling"`
}

RegistrationLossFamily never subtracts missing records from the denominator.

type RegistrationLossSpec

type RegistrationLossSpec struct {
	Families []RegistrationLossFamily `json:"families"`
}

RegistrationLossSpec retains all supplied families separately.

type RegistrationMissingData

type RegistrationMissingData struct {
	Contract RegistrationContract         `json:"contract"`
	Body     *RegistrationMissingDataSpec `json:"body"`
}

RegistrationMissingData keeps withheld cases in the declared population.

type RegistrationMissingDataSpec

type RegistrationMissingDataSpec struct {
	Handling    string                `json:"handling"`
	Denominator string                `json:"denominator"`
	MaxMissing  uint64                `json:"max_missing"`
	MaxWithheld uint64                `json:"max_withheld"`
	Method      *RegistrationArtifact `json:"method"`
}

RegistrationMissingDataSpec pins proposed budgets, not observed loss counts.

type RegistrationObserver

type RegistrationObserver struct {
	Contract RegistrationContract      `json:"contract"`
	Body     *RegistrationObserverSpec `json:"body"`
}

RegistrationObserver pins an arm's sensor access and perturbation proposals.

type RegistrationObserverSpec

type RegistrationObserverSpec struct {
	Mode           string             `json:"mode"`
	SensorScope    []string           `json:"sensor_scope"`
	Access         RegistrationFact   `json:"access"`
	FreshnessNanos int64              `json:"freshness_nanos"`
	DutyCycle      float64            `json:"duty_cycle"`
	SamplingRateHz float64            `json:"sampling_rate_hz"`
	OwnerConflicts []RegistrationFact `json:"owner_conflicts"`
	Arm            string             `json:"arm"`
	ReferenceArm   string             `json:"reference_arm"`
	// PhaseConfigurations is optional so legacy scalar registrations retain their bytes.
	PhaseConfigurations *ObserverPhasePlan `json:"phase_configurations,omitempty"`
}

RegistrationObserverSpec retains unresolved access and ownership conflicts.

type RegistrationOracle

type RegistrationOracle struct {
	Contract RegistrationContract    `json:"contract"`
	Body     *RegistrationOracleSpec `json:"body"`
}

RegistrationOracle pins an independent expected result and quality rules.

type RegistrationOracleSpec

type RegistrationOracleSpec struct {
	Method         string                    `json:"method"`
	Implementation RegistrationArtifact      `json:"implementation"`
	Expected       []RegistrationArtifact    `json:"expected"`
	Quality        []RegistrationQualitySpec `json:"quality"`
}

RegistrationOracleSpec names supplied oracle artifacts; none is executed.

type RegistrationPropertySpec

type RegistrationPropertySpec struct {
	Property          string               `json:"property"`
	Unit              string               `json:"unit"`
	Denominator       uint64               `json:"denominator"`
	Direction         string               `json:"direction"`
	TimingFamily      string               `json:"timing_family"`
	ClockDomain       string               `json:"clock_domain"`
	UncertaintyKind   string               `json:"uncertainty_kind"`
	UncertaintyMethod RegistrationArtifact `json:"uncertainty_method"`
	Overlap           string               `json:"overlap"`
	MaxValue          float64              `json:"max_value"`
}

RegistrationPropertySpec matches CompareTools' lower-is-better absolute bounds.

type RegistrationQualitySpec

type RegistrationQualitySpec struct {
	Output            string  `json:"output"`
	Unit              string  `json:"unit"`
	AbsoluteTolerance float64 `json:"absolute_tolerance"`
	RelativeTolerance float64 `json:"relative_tolerance"`
	Nonfinite         string  `json:"nonfinite"`
}

RegistrationQualitySpec freezes a numerical rule for one output.

type RegistrationReport

type RegistrationReport struct {
	// ReceiptConsistency covers selected prerequisites and all acquired artifact
	// outcomes. It is false for omitted optional artifacts, never a qualification.
	ReceiptConsistency    bool                         `json:"receipt_consistency"`
	Artifacts             []RegistrationArtifactResult `json:"artifacts"`
	SourceLibraries       []RegistrationLibrary        `json:"source_libraries"`
	RegistrationDigest    string                       `json:"registration_digest"`
	MeasurementAcceptance string                       `json:"measurement_acceptance"`
	Cells                 []RegistrationResult         `json:"cells"`
	Targets               []RegistrationTarget         `json:"targets"`
	FactBinding           string                       `json:"fact_binding"`
}

RegistrationReport is a deterministic factual report, not a comparative claim, health judgment or execution authority. Targets retain unknown facts.

func VerifyRegistration

func VerifyRegistration(ctx context.Context, r Registration, l QualificationLedger, root string) (RegistrationReport, error)

VerifyRegistration checks the immutable prerequisite snapshot and selected cell bindings using the existing ledger verifier. It reports receipt consistency only. Even a consistent qualified receipt remains an unverified measurement. Registered artifact bytes are checked; field/value bindings remain declared. Verification uses a private checked-byte snapshot, removed on return. It executes no recorded command or policy method.

Example
r, l := exampleRegistration()
r, err := r.Freeze(time.Date(2026, 10, 11, 0, 0, 0, 0, time.UTC))
if err != nil {
	fmt.Println(err)
	return
}
root, err := os.MkdirTemp("", "registration-example-")
if err != nil {
	fmt.Println(err)
	return
}
defer os.RemoveAll(root)
report, err := VerifyRegistration(context.Background(), r, l, root)
fmt.Println(err, report.MeasurementAcceptance)
fmt.Println(report.Cells[0].ReceiptConsistency, report.Cells[0].MeasurementAcceptance)
Output:
<nil> unverified
false unverified

type RegistrationResult

type RegistrationResult struct {
	Applicability         string `json:"applicability"`
	CellID                string `json:"cell_id"`
	Selected              bool   `json:"selected"`
	Capability            string `json:"capability"`
	Status                string `json:"status"`
	Gate                  string `json:"gate"`
	ReceiptConsistency    bool   `json:"receipt_consistency"`
	MeasurementAcceptance string `json:"measurement_acceptance"`
	Reason                string `json:"reason"`
	Owner                 string `json:"owner"`
	NextAction            string `json:"next_action"`
}

RegistrationResult separates retained receipt consistency from measurement acceptance. MeasurementAcceptance is always unverified in this source-only API.

type RegistrationStopping

type RegistrationStopping struct {
	Contract RegistrationContract      `json:"contract"`
	Body     *RegistrationStoppingSpec `json:"body"`
}

RegistrationStopping pins the sample and duration bounds without running them.

type RegistrationStoppingSpec

type RegistrationStoppingSpec struct {
	Rule             string                `json:"rule"`
	MaxSamples       uint64                `json:"max_samples"`
	MaxDurationNanos int64                 `json:"max_duration_nanos"`
	Method           *RegistrationArtifact `json:"method"`
}

RegistrationStoppingSpec requires a method for sequential stopping.

type RegistrationTarget

type RegistrationTarget struct {
	ID            string           `json:"id"`
	Applicability string           `json:"applicability"`
	Host          RegistrationFact `json:"host"`
	Device        RegistrationFact `json:"device"`
	Stack         RegistrationFact `json:"stack"`
	Topology      RegistrationFact `json:"topology"`
	Workload      RegistrationFact `json:"workload"`
	Deployment    RegistrationFact `json:"deployment"`
	Observer      RegistrationFact `json:"observer"`
	Reason        string           `json:"reason"`
	Owner         string           `json:"owner"`
	NextAction    string           `json:"next_action"`
}

RegistrationTarget retains a selected or unavailable target row. Applicability is selected, not-selected or unsupported. It never qualifies hardware or implies that discovery or a test was executed.

type RegistrationWorkload

type RegistrationWorkload struct {
	Contract RegistrationContract      `json:"contract"`
	Body     *RegistrationWorkloadSpec `json:"body"`
}

RegistrationWorkload pins the question, mechanism and pretrial inputs.

type RegistrationWorkloadSpec

type RegistrationWorkloadSpec struct {
	Question        string                 `json:"question"`
	Mechanism       string                 `json:"mechanism"`
	Code            RegistrationArtifact   `json:"code"`
	Inputs          []RegistrationArtifact `json:"inputs"`
	ExpectedOutputs []RegistrationArtifact `json:"expected_outputs"`
	CacheState      string                 `json:"cache_state"`
	PowerSettings   RegistrationFact       `json:"power_settings"`
	Contention      RegistrationFact       `json:"contention"`
	HardwareLease   RegistrationFact       `json:"hardware_lease"`
}

RegistrationWorkloadSpec contains proposed environment facts, not executions.

type RegressStoppingRules

type RegressStoppingRules struct {
	MaxTrials              int     `json:"max_trials"`
	RelativeThreshold      float64 `json:"relative_threshold"` // fractional slowdown, e.g. 0.10 for 10%
	NoiseNanos             float64 `json:"noise_nanos"`
	MinSamples             int     `json:"min_samples"`
	MinEffectSize          float64 `json:"min_effect_size,omitempty"`
	OracleTolerance        float64 `json:"oracle_tolerance,omitempty"`
	MaxConsecutiveFailures int     `json:"max_consecutive_failures,omitempty"`
	HaltOnDrift            bool    `json:"halt_on_drift"`
}

StoppingRules specifies criteria for stopping or reporting regression.

func DefaultStoppingRules

func DefaultStoppingRules() RegressStoppingRules

DefaultStoppingRules returns standard conservative regression evaluation thresholds.

type RepeatedSequence

type RepeatedSequence struct {
	StreamID        int64
	Pattern         []string
	Repetitions     int
	TotalDurationNs int64
	Intervals       []Interval
	MissingEvidence []string
}

RepeatedSequence records a pattern of kernel launches repeating consecutively on the same stream.

type ReplayFunc

type ReplayFunc func(ctx context.Context, armName string, round int) (timing.Receipt, []float64, error)

ReplayFunc adapts a function to the ReplayRunner interface.

func (ReplayFunc) RunArm

func (f ReplayFunc) RunArm(ctx context.Context, armName string, round int) (timing.Receipt, []float64, error)

RunArm calls the adapted ReplayFunc.

type ReplayOptions

type ReplayOptions struct {
	CurrentEnvironment Environment
	AllowDriftFork     bool
	DriftRationale     string
	BaselineFamilies   []string
	CandidateFamilies  []string
	BaselineResources  map[string]string
	CandidateResources map[string]string
	ReferenceValues    []float64
}

ReplayOptions configures preflight validation and execution policies for replay.

type ReplayRunner

type ReplayRunner interface {
	RunArm(ctx context.Context, armName string, round int) (timing.Receipt, []float64, error)
}

type Report

type Report = re_obsmodel.Report

type ReproAllocation

type ReproAllocation struct {
	Address uint64
	Data    []byte
}

Allocation is one complete backing allocation at capture time.

type ReproIdentity

type ReproIdentity struct {
	Index  uint64
	Policy string
}

Identity identifies an exact uint64 mismatch at a logical output element. Other numerical policies and access-violation identities are unsupported. Its zero value is invalid.

func IdentifyRepro

func IdentifyRepro(run ptx.RunRecord) (ReproIdentity, error)

Identify validates the campaign's execution evidence and returns the runner-produced comparison identity. It never derives identity from prose.

Example
digest := strings.Repeat("a", 64)
run := ptx.RunRecord{
	Exited: true, Stdout: "MISMATCH\n",
	PTXDigest: digest, ExpectedPTXDigest: digest, PTXDigestSource: "runner_receipt",
	Mismatch: &ptx.MismatchIdentity{Index: 0, Policy: "exact-uint64"},
}
identity, err := IdentifyRepro(run)
fmt.Println(identity, err)
Output:
{0 exact-uint64} <nil>

func (ReproIdentity) Matches

func (i ReproIdentity) Matches(run ptx.RunRecord) (bool, error)

Matches reports whether a classified run reproduces i. A different verdict or output element does not reproduce it. Missing or invalid execution or comparison evidence is an error, not an accepted or healthy candidate.

Example
identity := ReproIdentity{Index: 0, Policy: "exact-uint64"}
matched, err := identity.Matches(ptx.RunRecord{})
fmt.Println(matched, err)
Output:
false compare failure: invalid execution evidence

type ReproLaunch

type ReproLaunch struct {
	Version     int
	ID          string
	Artifact    *kernel.Artifact
	Grid, Block [3]uint32
	SharedBytes uint32
	Stream      uint64
	CallSite    string
	Arguments   []Argument
	Allocations []ReproAllocation
	Sources     map[string]string
	Options     []string
}

Launch is a self-contained isolated launch. ID identifies this capture, not a CUPTI launch. Stream is diagnostic metadata, never reused for replay. Sources and Options are optional provenance; Artifact is the executed image.

func CaptureRepro

func CaptureRepro(stream *cuda.Stream, artifact *kernel.Artifact, grid, block [3]uint32, shared uint32, limit uint64, args ...Argument) (*ReproLaunch, error)

Capture snapshots one launch without submitting it. limit is the maximum total allocation bytes to copy, and must be positive. Only native CUBINs are accepted so replay does not silently recompile different code. Artifact.Schema() must be the complete, accurate ABI supplied by a trusted producer. The caller must keep all allocations live and exclude concurrent writes until it returns.

Example
_, err := CaptureRepro(nil, nil, [3]uint32{1, 1, 1}, [3]uint32{1, 1, 1}, 0, 1024)
fmt.Println(err)
Output:
cudarepro: nil stream

func Read

func Read(r io.Reader, limit int64) (*ReproLaunch, error)

Read reads a capture with an explicit encoded byte limit. Use captures from trusted producers only: replay executes their native GPU code.

Example
_, err := Read(bytes.NewBufferString("{}"), 64)
fmt.Println(err)
Output:
cudarepro: invalid capture version or identity

func (*ReproLaunch) Replay

func (l *ReproLaunch) Replay(dev *cuda.Device, before func(*ReproLaunch) error) (result map[string][]byte, err error)

Replay runs an isolated launch on fresh allocations and returns each buffer argument's output bytes. before, when nonnil, receives relocated addresses before submission; save that record to attribute a sanitizer report from this replay. It must not mutate the record. Aliases retain their original offsets. Replay does not recreate concurrent work, mutable globals or external state.

Example
var launch *ReproLaunch
_, err := launch.Replay(nil, nil)
fmt.Println(err)
Output:
cudarepro: invalid capture version or identity

func (*ReproLaunch) Validate

func (l *ReproLaunch) Validate() error

Validate checks the image digest, launch dimensions and allocation mapping.

Example
var launch *ReproLaunch
fmt.Println(launch.Validate())
Output:
cudarepro: invalid capture version or identity

func (*ReproLaunch) Write

func (l *ReproLaunch) Write(w io.Writer) error

Write validates and writes a capture as JSON, including allocation contents.

Example
var launch *ReproLaunch
fmt.Println(launch.Write(&bytes.Buffer{}))
Output:
cudarepro: invalid capture version or identity

type ReproducerBundleOptions

type ReproducerBundleOptions struct {
	Reason                string
	Source                string
	Inputs                []uint64
	Shape                 []uint64
	Grid                  [3]uint32
	Block                 [3]uint32
	SharedMem             uint32
	IncludeGPUVisTimeline bool
}

ReproducerBundleOptions configures construction of a minimal reproducer bundle from a decoded flight ring snapshot.

type ReproducerManifest

type ReproducerManifest struct {
	Source     string
	Inputs     []uint64
	Shape      []uint64
	Grid       [3]uint32
	Block      [3]uint32
	SharedMem  uint32
	Reproducer *iket.Reproducer
	Finding    *cudaschedule.SeedResult
	Reason     string
}

ReproducerManifest describes explicit workload inputs, tensor shapes, launch geometry, and kernel source to be validated and exported.

func ExtractManifest

func ExtractManifest(incident any, opts EscalateOptions) (*ReproducerManifest, error)

ExtractManifest converts an incident (iket.DeviceRing lookback, iket.IKETIncident, StuckSegmentError, or Bundle) and caller options into a validated ReproducerManifest.

type ReproducibilityReceipt

type ReproducibilityReceipt struct {
	ArtifactManifestSHA256 string            `json:"artifact_manifest_sha256"`
	ReplayMatches          bool              `json:"replay_matches"`
	MatrixCompleted        bool              `json:"matrix_completed"`
	ArtifactDigests        map[string]string `json:"artifact_digests"`
	GateDisposition        string            `json:"gate_disposition"`
}

ReproducibilityReceipt summarizes replay and manifest consistency.

type Request

type Request struct {
	ID            string        `json:"id"`
	WorkloadName  string        `json:"workload_name"`
	Data          []float64     `json:"data"`
	Mode          Mode          `json:"mode"`
	Delay         time.Duration `json:"delay,omitempty"`
	CorrelationID uint32        `json:"correlation_id,omitempty"`
	TID           uint64        `json:"tid,omitempty"`
}

Request defines a work item submitted to the GPU service fixture.

type Residency

type Residency = re_obsmodel.Residency

type ResilienceMode

type ResilienceMode string

ResilienceMode indicates a system stress or recovery condition.

const (
	// ResilienceNormal represents standard undisturbed execution.
	ResilienceNormal ResilienceMode = "normal"

	// ResilienceOverflow represents telemetry ring buffer overflow and record drop.
	ResilienceOverflow ResilienceMode = "buffer_overflow"

	// ResilienceRestart represents worker process restart and PID/Gen recycling.
	ResilienceRestart ResilienceMode = "process_restart"

	// ResilienceLateAttach represents collector attaching after workload start.
	ResilienceLateAttach ResilienceMode = "late_attach"

	// ResilienceShutdown represents graceful finalization during inflight work.
	ResilienceShutdown ResilienceMode = "collector_shutdown"
)

type Resolution

type Resolution = re_obsprobe.Resolution

type Resolver

type Resolver = re_obsprobe.Resolver

type ResourceChange

type ResourceChange struct {
	Resource  string `json:"resource"` // e.g. clock_mhz, power_watts, sm_occupancy, memory_bytes
	Baseline  string `json:"baseline"`
	Candidate string `json:"candidate"`
}

ResourceChange captures hardware or resource state divergence between baseline and candidate.

type Response

type Response struct {
	RequestID    string           `json:"request_id"`
	WorkloadName string           `json:"workload_name"`
	OpID         obsworkload.OpID `json:"op_id"`
	Output       []float64        `json:"output"`
	Duration     time.Duration    `json:"duration"`
	GroundTruth  GroundTruthLog   `json:"ground_truth"`
	Observation  SubmissionTiming `json:"observation"`
	Error        error            `json:"error,omitempty"`
}

Response records the output and performance characteristics of a completed request.

type Result

type Result struct {
	// Config is the configuration the run used, retained as evidence of
	// what was actually asked for.
	Config Config

	// Outcome classifies the run. Read this rather than ExitCode.
	Outcome SanitizerOutcome

	// Err carries the reason for [OutcomeToolFailure]: [ErrToolNotFound],
	// [ErrTimeout], [ErrNoVerdict], [ErrUnsupportedOption] for an option the
	// resolved tool does not accept, which [Config.CheckOptions] reports
	// before the run starts, or an error from starting or waiting on the
	// process. It is nil for the other outcomes.
	Err error

	// Args is the argument vector that was executed, starting with the
	// compute-sanitizer executable.
	Args []string

	// ExitCode is the process exit status, or -1 if it is unknown: the
	// process never ran, was killed by a signal, or was abandoned before
	// waiting on it finished. It is retained for diagnosis; it is not the
	// verdict.
	ExitCode int

	// ErrorExitCode is the --error-exitcode value that was passed. It is
	// never 0.
	ErrorExitCode int

	// ExitCodeCollision reports that the application exited with the same
	// status as ErrorExitCode while the tool's report showed no errors, so
	// the exit status alone would have been read as sanitizer errors.
	ExitCodeCollision bool

	// Log is the parsed tool report. It is never nil.
	Log *Log

	// LogPath is where the tool's report was left on disk, set only when
	// [Config.LogDir] asked for it to be kept.
	LogPath string

	// Stdout and Stderr are the retained copies of the application's
	// output, truncated to [Config.MaxOutputBytes] per stream.
	Stdout, Stderr string

	// StdoutTruncated and StderrTruncated report whether output was
	// dropped from the retained copies.
	StdoutTruncated, StderrTruncated bool

	// MissingEvidence lists [Config.RequireOutput] entries that did not
	// appear in the application's output, and ForbiddenEvidence lists
	// [Config.ForbidOutput] entries that did. Either makes the run
	// [OutcomeApplicationFailed] rather than [OutcomeClean].
	MissingEvidence   []string
	ForbiddenEvidence []string

	// CrashObservation records the classified defect signature mapped from the
	// immediately preceding completed trace, when crash classification was performed.
	CrashObservation *CrashObservation

	// Duration is how long the run took.
	Duration time.Duration
}

Result describes one run. [Run] always returns a non-nil Result when the Config was valid, including for runs that never started.

func Check

func Check(t testing.TB, cfg Config, prog string, args ...string) *Result

Check runs prog under compute-sanitizer and reports the outcome to t. It is [Run] followed by Result.Report, for tests that drive a separate GPU program rather than running themselves under the tool.

A configuration error fails the test immediately, since it is a bug in the test rather than a finding about the program.

Example

A test that drives a separate GPU program rather than running itself under the tool uses Check, which classifies the run and reports it to t.

package main

import (
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"testing"
	"time"
)

func main() {
	test := func(t *testing.T) {
		diag.Check(t, diag.Config{
			Tool:          diag.Racecheck,
			MissingTool:   diag.MissingToolFail,
			RequireOutput: []string{"reduction complete"},
			Timeout:       2 * time.Minute,
		}, "./testdata/reduction")
	}
	_ = test
}

func RunSanitizer

func RunSanitizer(ctx context.Context, cfg Config, prog string, args ...string) (*Result, error)

Run executes prog under compute-sanitizer and classifies the result.

The returned error is non-nil only for a Config that cannot be used; in that case the Result is nil. Everything that can go wrong once the configuration is valid — a missing tool, a failure to start, a timeout, an application crash, reported sanitizer errors — is reported through the Result, so callers switch on Result.Outcome rather than on an error.

Run bounds the subprocess with ctx and, if set, Config.Timeout, whichever expires first. On Unix, the run owns a process group that is killed on expiry and cleaned up after the tool exits, including descendants whose parent already exited. Windows uses a Job Object to own and terminate the process tree. Other platforms currently kill only the direct child. Either expiry produces OutcomeToolFailure with ErrTimeout; a timed-out run is never reported as a pass.

Example

Run returns a Result rather than a bool, because one exit status stands for four different situations that call for four different reactions.

package main

import (
	"context"
	"errors"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"time"
)

func main() {
	res, err := diag.RunSanitizer(context.Background(), diag.Config{
		Tool:        diag.Initcheck,
		MissingTool: diag.MissingToolFail,
		Timeout:     time.Minute,
	}, "./vectoradd")
	if err != nil {
		panic(err) // the configuration is unusable
	}
	switch res.Outcome {
	case diag.OutcomeClean:
		fmt.Println("no uninitialized reads")
	case diag.OutcomeSanitizerErrors:
		fmt.Println(res.Details())
	case diag.OutcomeApplicationFailed:
		fmt.Println("the program itself failed:", res.ExitCode)
	case diag.OutcomeToolFailure:
		if errors.Is(res.Err, diag.ErrToolNotFound) {
			fmt.Println("compute-sanitizer is not installed; nothing was checked")
		} else {
			fmt.Println("no verdict:", res.Err)
		}
	}
}

func (*Result) Details

func (r *Result) Details() string

Details returns the summary followed by the retained evidence: the tool's report and the application's output. A detected error the caller cannot read is close to useless, so failure paths print this rather than the summary alone.

func (*Result) FoundDefect

func (r *Result) FoundDefect() bool

FoundDefect reports whether this run found something wrong in the program under test. It is true only for OutcomeSanitizerErrors backed by a non-zero count, so a run that produced no verdict at all is false.

Use this rather than negating a clean check. "Not clean" is the shorthand every caller reaches for and it is wrong: OutcomeToolFailure is also not clean, and it means the tool timed out, was not found, or never printed a summary. A positive control asserting !clean therefore passes when the tool never ran, which is the one way a control must not fail. On GB10 that is not hypothetical: initcheck and racecheck each hit a 300s deadline and reported no verdict, and a suite asserting !clean recorded both fixtures as caught.

The three outcomes a caller needs are distinct and stay distinct:

r.FoundDefect()                        // the program is wrong
r.Outcome == OutcomeClean              // the program is right
r.Outcome == OutcomeToolFailure        // we do not know; see r.Err

func (*Result) Report

func (r *Result) Report(t testing.TB)

Report records the result on t.

A clean run is logged. Sanitizer errors and application failures are errors, reported with the full tool report and the program's output, because a finding the reader cannot see is nearly useless. A tool failure is fatal, except that a missing compute-sanitizer under MissingToolSkip skips the test with an explicit notice. Report never leaves a run silently passing.

func (*Result) Summary

func (r *Result) Summary() string

Summary returns a one-paragraph account of the run, suitable for a test log. It never includes the full tool report; use Result.Details for that.

type Sample

type Sample = re_obsmodel.Sample

type SamplingConfig

type SamplingConfig struct {
	BufferCapacity int           `json:"buffer_capacity"`
	Window         time.Duration `json:"window"`
	RateHz         int           `json:"rate_hz"`
}

SamplingConfig defines collection parameters.

type SanitizerClassifier

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

SanitizerClassifier classifies sanitizer defect findings and maps them to unique crash signatures, deduplicating recurring defects across trial runs.

Example
package main

import (
	"crypto/sha256"
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/timing"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	classifier := diag.NewSanitizerClassifier()

	m, _ := timing.NewThreadEdgeMap(32, 1)
	m.Record(0, 3)

	identity := diag.CrashIdentity{
		Kernel:  "vector_add",
		Image:   sha256.Sum256([]byte("img")),
		Epoch:   "campaign_1",
		Trial:   "trial_0",
		Input:   sha256.Sum256([]byte("inp0")),
		Ordinal: 0,
	}
	failing := identity
	failing.Trial = "trial_1"
	failing.Ordinal = 1
	failing.Input = sha256.Sum256([]byte("inp1"))

	trace := diag.CompletedCrashTrace{
		Identity: identity,
		Complete: true,
		MapSize:  32,
		Bitmap:   m.Snapshot(),
	}

	res := &diag.Result{
		Config:  diag.Config{Tool: diag.Memcheck},
		Outcome: diag.OutcomeSanitizerErrors,
		Log:     diag.ParseLog("========= Invalid __global__ write of size 4 bytes\n========= ERROR SUMMARY: 1 error\n"),
	}

	_, isNovel1, _ := classifier.Classify(res, trace, failing)
	fmt.Printf("First crash observation novel: %v\n", isNovel1)

	// Duplicate observation from another trial
	failing2 := failing
	failing2.Trial = "trial_2"
	failing2.Ordinal = 1
	_, isNovel2, _ := classifier.Classify(res, trace, failing2)
	fmt.Printf("Second crash observation novel: %v\n", isNovel2)
	fmt.Printf("Unique crashes recorded: %d\n", classifier.UniqueCount())

}
Output:
First crash observation novel: true
Second crash observation novel: false
Unique crashes recorded: 1

func NewSanitizerClassifier

func NewSanitizerClassifier() *SanitizerClassifier

NewSanitizerClassifier allocates an empty classifier.

func (*SanitizerClassifier) Classify

func (c *SanitizerClassifier) Classify(result *Result, preceding CompletedCrashTrace, failure CrashIdentity) (CrashObservation, bool, error)

Classify calculates the CrashObservation for result using preceding trace and failure identity. It reports whether the resulting defect signature is novel (seen for the first time). If the signature is novel, it is recorded. The resulting CrashObservation is attached to result.CrashObservation.

func (*SanitizerClassifier) Observations

func (c *SanitizerClassifier) Observations() []CrashObservation

Observations returns all distinct crash observations recorded so far.

func (*SanitizerClassifier) UniqueCount

func (c *SanitizerClassifier) UniqueCount() int

UniqueCount returns the number of distinct crash signatures observed.

type SanitizerGating

type SanitizerGating int

SanitizerGating selects a host trace-abstraction policy. It does not enable instrumentation or establish that an oracle is observable in a fuzz worker.

const (
	GatingAllTrace SanitizerGating = iota + 1
	GatingSimplifyTrace
	GatingUniqueTrace
	GatingCoverageIncrease
)

type SanitizerOutcome

type SanitizerOutcome int

Outcome is what a run turned out to be.

compute-sanitizer reports these four situations through a single exit status, which conflates them. They call for four different reactions, so this package keeps them apart.

const (
	// OutcomeToolFailure means no verdict exists: compute-sanitizer could
	// not be found or started, the run was cancelled or timed out, or the
	// tool produced no complete report. It is never a pass, and in particular a
	// timeout is this outcome rather than a slow success.
	OutcomeToolFailure SanitizerOutcome = iota

	// OutcomeClean means the run completed, the tool reported zero errors,
	// and any evidence the caller required was present.
	OutcomeClean

	// OutcomeSanitizerErrors means the tool reported errors. This is the
	// outcome even when the process exited 0, which is what happens when
	// compute-sanitizer's --error-exitcode is left at its default.
	OutcomeSanitizerErrors

	// OutcomeApplicationFailed means the tool completed and reported no
	// errors, but the application exited nonzero or did not produce the
	// output the caller required as evidence that the intended work ran.
	OutcomeApplicationFailed
)

The possible outcomes of a run. The zero value is OutcomeToolFailure, so a Result that was never filled in does not read as a pass.

func (SanitizerOutcome) String

func (o SanitizerOutcome) String() string

String returns a short name for the outcome.

type SchedEvidence

type SchedEvidence struct {
	Process      obsworkload.ProcessGenID `json:"process"`
	TID          uint64                   `json:"tid"`
	ProbePresent bool                     `json:"probe_present"`
	Loss         uint64                   `json:"loss"`
	UnknownLoss  bool                     `json:"unknown_loss"`
	Intervals    []SchedInterval          `json:"intervals"`
}

SchedEvidence holds operating system scheduler trace evidence for a target thread.

func SchedulerEvidence

func SchedulerEvidence(proc obsworkload.ProcessGenID, tid uint64, clock string, events []SchedulerEvent, loss uint64, unknownLoss bool) (SchedEvidence, error)

SchedulerEvidence derives intervals between observed target-thread transitions. It does not extrapolate before the first or after the last transition. The process generation must come from the captured process, not PID alone. A raw tracefs capture without quantified loss must pass unknownLoss=true; its intervals remain diagnostic evidence and cannot admit a complete diagnosis.

Example
proc := obsworkload.ProcessGenID{PID: 7, Generation: 99}
events := []SchedulerEvent{{Kind: "sched_wakeup", Timestamp: 10, WakeTID: 7}, {Kind: "sched_switch", Timestamp: 30, NextTID: 7}, {Kind: "sched_switch", Timestamp: 50, PreviousTID: 7, PreviousState: "S"}}
ev, err := SchedulerEvidence(proc, 7, "linux_monotonic", events, 0, true)
fmt.Println(len(ev.Intervals), ev.UnknownLoss, err)
Output:
2 true <nil>

func (SchedEvidence) Durations

func (s SchedEvidence) Durations() (runnable, scheduled, wait time.Duration, err error)

Durations computes runnable, scheduled and blocked time separately. Zero-length and inverted intervals contribute zero. It returns zero durations and an error if any recognized state's duration is unrepresentable.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/cudaprof/tracecontract"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	s := diag.SchedEvidence{Intervals: []diag.SchedInterval{{State: diag.SchedRunning, Span: tracecontract.Interval{End: 10}}}}
	runnable, scheduled, wait, err := s.Durations()
	fmt.Println(runnable, scheduled, wait, err)
}
Output:
0s 10ns 0s <nil>

func (SchedEvidence) Matches

func (s SchedEvidence) Matches(proc obsworkload.ProcessGenID, tid uint64) bool

Matches reports whether the scheduler evidence belongs to the specified process and thread.

func (SchedEvidence) Validate

func (s SchedEvidence) Validate(proc obsworkload.ProcessGenID, tid uint64) error

Validate checks whether scheduler evidence is present, complete, and properly matched.

type SchedInterval

type SchedInterval struct {
	State SchedState             `json:"state"`
	Span  tracecontract.Interval `json:"span"`
	CPU   int                    `json:"cpu"`
}

SchedInterval captures one contiguous scheduling interval for a thread.

type SchedState

type SchedState string
const (
	// SchedRunning indicates the thread was actively executing on a CPU.
	SchedRunning SchedState = "running"
	// SchedRunnable indicates the thread was queued and ready to run, waiting for CPU.
	SchedRunnable SchedState = "runnable"
	// SchedBlocked indicates the thread was off-CPU waiting for an event, lock, or I/O.
	SchedBlocked SchedState = "blocked"
)

type Schedule

type Schedule struct {
	Options   isa_ptx.Options
	Decisions []isa_ptx.InjectionDecision
}

Schedule records the original perturbation options and the retained subset of injection decisions. Reduction preserves options and decision order. An empty subset replays the pristine source, rather than skipping execution.

Example
s := Schedule{Options: isa_ptx.Options{Seed: 17, Intensity: 1}}
fmt.Println(s.Options.Seed, len(s.Decisions))
Output:
17 0

type SchedulerEvent

type SchedulerEvent struct {
	Kind                          string
	Timestamp                     int64
	CPU                           int
	PreviousTID, NextTID, WakeTID uint64
	PreviousState                 string
}

type SchedulingData

type SchedulingData struct {
	PID          int    `json:"pid"`
	ChannelID    uint32 `json:"channel_id"`
	CurrentSlice uint64 `json:"current_slice_us"`
	QueueLength  uint32 `json:"queue_length"`
	Priority     int    `json:"priority"`
}

SchedulingData holds channel and context scheduling input parameters.

type Scope

type Scope = re_obsworkload.Scope

type ScopeDecision

type ScopeDecision struct {
	Scope                     EvidenceScope `json:"scope"`
	Disposition               string        `json:"disposition"`
	AttestationArtifactDigest string        `json:"attestation_artifact_digest"`
	Reason                    string        `json:"reason"`
	Owner                     string        `json:"owner"`
	NextAction                string        `json:"next_action"`
}

ScopeDecision retains explicit bounded evidence identities, not acquisition authority.

type ScopeOption

type ScopeOption = re_obsworkload.ScopeOption

type SelectedCellIdentity

type SelectedCellIdentity struct {
	CellID                 string                 `json:"cell_id"`
	CapabilityID           string                 `json:"capability_id"`
	Gate                   string                 `json:"gate"`
	ClosureDigest          string                 `json:"closure_digest"`
	LatestReceiptDigest    string                 `json:"latest_receipt_digest"`
	TransitiveDependencies []SelectedCellIdentity `json:"transitive_dependencies"`
}

SelectedCellIdentity retains explicit bounded evidence identities, not acquisition authority.

type SequenceAnalysis

type SequenceAnalysis struct {
	StreamIDs          []int64
	Gaps               []Gap
	RepeatedSequences  []RepeatedSequence
	BatchingCandidates []BatchingCandidate
}

SequenceAnalysis contains the structural launch analysis across streams.

func AnalyzeLaunchSequences

func AnalyzeLaunchSequences(launches []obsmodel.CensusLaunch, cfg SequenceConfig) (SequenceAnalysis, error)

AnalyzeLaunchSequences performs a pure analysis pass over kernel launch records, identifying per-stream repeated sequences, execution gaps, and candidate batching regions.

Because activity records provide only timing and symbols, findings are reported as hypotheses accompanied by explicit lists of missing evidence (e.g. unobserved host activity or unverified graph safety), rather than speculative promises of recoverable latency.

type SequenceConfig

type SequenceConfig struct {
	// MinGapNs is the minimum duration in nanoseconds between consecutive launches
	// on the same stream to be reported as an observed gap. Defaults to 1,000 ns (1 µs).
	MinGapNs int64

	// MinSequenceLen is the minimum pattern length (number of kernels) for repeated sequence detection.
	// Defaults to 2.
	MinSequenceLen int

	// MinRepetitions is the minimum number of consecutive repetitions of a pattern to report.
	// Defaults to 2.
	MinRepetitions int

	// CandidateBatchingMinLaunches is the minimum number of consecutive kernels in a candidate batching region.
	// Defaults to 3.
	CandidateBatchingMinLaunches int

	// CandidateBatchingMaxGapNs is the maximum allowable gap duration between adjacent launches within a candidate
	// batching region. Defaults to 5,000 ns (5 µs).
	CandidateBatchingMaxGapNs int64
}

SequenceConfig specifies parameters for launch sequence and gap analysis.

type ServiceFixture

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

ServiceFixture is a portable concurrent service with synthetic device activity, actual application timing and separate request ground truth.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"time"
)

func main() {
	ctx := context.Background()
	cfg := diag.DemonstrationConfig{
		NumRequests:       2,
		Concurrency:       1,
		HostDelay:         1 * time.Millisecond,
		DeviceDelay:       100 * time.Microsecond,
		SkipIntervention:  true,
		ExerciseCorruptEv: false,
	}

	res, err := diag.RunDemonstration(ctx, cfg)
	if err != nil {
		fmt.Printf("error: %v\n", err)
		return
	}

	fmt.Printf("Attribution Precision: %.2f\n", res.AttributionAccuracy)

}
Output:
Attribution Precision: 1.00

func NewServiceFixture

func NewServiceFixture(
	annotator *obsworkload.Annotator,
	recorder *iket.Recorder,
	coordinator *iket.EscalationCoordinator,
	joiner *obsworkload.Joiner,
	opts ...FixtureOption,
) (*ServiceFixture, error)

NewServiceFixture instantiates a service fixture.

func (*ServiceFixture) BatchProcess

func (sf *ServiceFixture) BatchProcess(ctx context.Context, reqs []Request, concurrency int) ([]Response, error)

BatchProcess executes requests concurrently across a worker pool.

func (*ServiceFixture) GroundTruthLogs

func (sf *ServiceFixture) GroundTruthLogs() []GroundTruthLog

GroundTruthLogs returns a copy of all accumulated execution logs.

func (*ServiceFixture) Process

func (sf *ServiceFixture) Process(ctx context.Context, req Request) (resp Response, retErr error)

Process executes a single request through the service pipeline.

func (*ServiceFixture) ProcessGen

func (sf *ServiceFixture) ProcessGen() obsworkload.ProcessGenID

ProcessGen returns the fixture's process generation identity.

type ServingAttemptSummary

type ServingAttemptSummary struct {
	Attempt      telemetry.ServingAttemptRef `json:"attempt"`
	Role         string                      `json:"role"`
	Outcome      string                      `json:"outcome"`
	OutputTokens *uint64                     `json:"output_tokens,omitempty"`
	Batches      []string                    `json:"batches"`
	Transfers    []string                    `json:"transfers"`
}

ServingAttemptSummary keeps one supplied attempt's outcome with the batch and transfer edges admitted for it. Shared batches are listed, not divided.

type ServingEdge

type ServingEdge struct {
	Kind     string                       `json:"kind"`
	Attempt  *telemetry.ServingAttemptRef `json:"attempt,omitempty"`
	Target   string                       `json:"target"`
	Basis    string                       `json:"basis"`
	Evidence string                       `json:"evidence,omitempty"`
	Finding  tracecontract.Finding        `json:"finding"`
}

ServingEdge is one evaluated supplied relation. Kind is route, batch_member, batch_operation, cache_use or transfer. Target is the frontend, batch ID, batch ID and operation, cache namespace and generation, or transfer ID. A native_id basis may be observed, an annotation basis at most associated, and an unknown basis is withheld. Transfer and batch operation edges are at most associated: movement request identities are supplied annotations. Evidence is the supplied reference. Finding.Artifacts of an admitted edge holds the raw digests it relies on: the native_id evidence digest, the owning cache declaration's evidence when that is a SHA-256 digest, the movement record's raw digest and the activity join's evidence reference. Annotation evidence is not a digest and is never listed.

type ServingInput

type ServingInput struct {
	Serving  io.Reader
	Source   telemetry.WorkloadSource
	Limits   telemetry.WorkloadLimits
	Movement *MovementInput

	Before, After                       *telemetry.WorkloadExport
	WindowStartNanos, WindowEndNanos    int64
	WindowClockDomain, WindowClockEpoch string
}

type ServingSummary

type ServingSummary struct {
	Version       int                             `json:"version"`
	ContextSHA256 string                          `json:"context_sha256"`
	Source        telemetry.WorkloadSource        `json:"source"`
	Context       telemetry.ServingContextV2      `json:"context"`
	Outcomes      telemetry.ServingContextSummary `json:"outcomes"`
	Attempts      []ServingAttemptSummary         `json:"attempts"`
	Edges         []ServingEdge                   `json:"edges"`
	Movement      *MovementSummary                `json:"movement,omitempty"`
	Aggregate     []telemetry.WorkloadDelta       `json:"aggregate"`
	AggregateRaw  []string                        `json:"aggregate_raw_sha256"`
	// AggregateSource retains the before-export's supplied context after the
	// endpoint identities have passed window validation. It is separate from
	// Source, which identifies the application serving context. Nil means no
	// aggregate window; a nil Rank remains unknown, not rank zero. Neither
	// the source nor its rank is authenticated by this report.
	AggregateSource *telemetry.WorkloadSource `json:"aggregate_source,omitempty"`
	Limits          []string                  `json:"limits"`
}

ServingSummary is a versioned serving incident summary. It retains the movement summary and aggregate window it consumed and the digests of their sources. Aggregate deltas are never attributed to requests or batches.

func SummarizeServing

func SummarizeServing(ctx context.Context, in ServingInput) (ServingSummary, error)

SummarizeServing reads a version 2 serving context, summarizes its version 1 attempt outcomes, runs SummarizeMovement and, when supplied, the aggregate counter window, and evaluates each supplied edge independently. An edge with a missing or unresolved attempt, a worker epoch or cache generation that contradicts the attempt, an unknown basis, or a transfer whose movement record names another attempt is withheld alone. Batch operations require an exact activity join and remain shared work.

Example
c := newServingCase()
// The second attempt's batch membership lost its request identity.
c.serving.Batches[0].Members[1].RequestID = ""
var b bytes.Buffer
if err := telemetry.WriteServingContextV2(&b, c.serving, telemetry.WorkloadLimits{}); err != nil {
	fmt.Println(err)
	return
}
movement, err := c.movement.build()
if err != nil {
	fmt.Println(err)
	return
}
s, err := diag.SummarizeServing(context.Background(), diag.ServingInput{
	Serving:  &b,
	Source:   telemetry.WorkloadSource{Provider: "application", Version: "serving-app-1", RunID: "run"},
	Movement: &movement,
})
if err != nil {
	fmt.Println(err)
	return
}
for _, a := range s.Attempts {
	fmt.Println(a.Attempt.RequestID, a.Outcome, a.Batches, a.Transfers)
}
for _, e := range s.Edges {
	fmt.Println(e.Kind, e.Target, e.Finding.Class)
}
Output:
r1 accepted [b1] [t1]
r2 failed [] [t2]
route fe-0 observed
batch_member b1 associated
batch_member b1 unavailable
batch_operation b1/9 associated
cache_use kv/g1 associated
transfer t1 associated
transfer t2 associated

type ShadowProvenance

type ShadowProvenance struct {
	// Kind is empty for legacy native claims.
	Kind string `json:"kind,omitempty"`
	// Source identifies the host adapter epoch, not a device or module.
	Source        string        `json:"source,omitempty"`
	DeviceID      int           `json:"device_id"`
	DriverVersion string        `json:"driver_version"`
	KernelModule  string        `json:"kernel_module"`
	Hook          Hook          `json:"hook"`
	Sequence      uint64        `json:"sequence"`
	TimestampNano int64         `json:"timestamp_nano"`
	TTL           time.Duration `json:"ttl,omitempty"`
}

Provenance captures the provenance and observation context of a policy input.

func (ShadowProvenance) Validate

func (p ShadowProvenance) Validate() error

Validate verifies that mandatory provenance fields are present and well-formed.

type Snapshot

type Snapshot struct {
	ID              string           `json:"id"`
	Provenance      ShadowProvenance `json:"provenance"`
	Policy          PolicyInfo       `json:"policy"`
	Input           Input            `json:"input"`
	Decision        Decision         `json:"decision"`
	Status          InputStatus      `json:"status"`
	ObservedOutcome *ObservedOutcome `json:"observed_outcome,omitempty"`
}

Snapshot is a bounded, serializable record of a shadow policy decision.

func DecodeSnapshot

func DecodeSnapshot(data []byte) (Snapshot, error)

DecodeSnapshot parses a single JSON Snapshot, ensuring all required fields are present and rejecting unknown fields or trailing input.

func ReadHistory

func ReadHistory(r io.Reader) ([]Snapshot, error)

ReadHistory reads a bounded version 1 or 2 replay corpus, rejecting unknown fields, invalid snapshots, unsupported versions, and trailing data.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"strings"
)

func main() {
	history, err := diag.ReadHistory(strings.NewReader(`{"version":1,"snapshots":[]}`))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(len(history))
}
Output:
0

func (Snapshot) MarshalJSON

func (s Snapshot) MarshalJSON() ([]byte, error)

MarshalJSON serializes a snapshot to indented or standard JSON.

func (Snapshot) Validate

func (s Snapshot) Validate() error

Validate verifies that a snapshot contains required fields.

type Span

type Span = re_obsmodel.Span

type SpatialHierarchyLevel

type SpatialHierarchyLevel = re_obsmodel.SpatialHierarchyLevel

type SpatialHierarchyMovement

type SpatialHierarchyMovement = re_obsmodel.SpatialHierarchyMovement

type SpatialTensorMovement

type SpatialTensorMovement = re_obsmodel.SpatialTensorMovement

type Statistic

type Statistic = re_obsmodel.Statistic

type StoppingRules

type StoppingRules struct {
	MaxTrials       int     `json:"max_trials"`
	MinEffectSize   float64 `json:"min_effect_size"`  // Minimum required relative improvement (e.g. 0.20 for 20%)
	OracleTolerance float64 `json:"oracle_tolerance"` // Maximum allowable absolute difference in output tensor elements
}

type StructVersions

type StructVersions = re_obsmodel.StructVersions

type SubmissionTiming

type SubmissionTiming struct {
	RequestID string                     `json:"request_id"`
	Service   tracecontract.Interval     `json:"service"`
	PreEntry  tracecontract.Interval     `json:"pre_entry"`
	API       HostCallEvent              `json:"api"`
	Host      obsworkload.HostSubmission `json:"host"`
	Device    obsworkload.DeviceActivity `json:"device"`
	Complete  bool                       `json:"complete"`
}

SubmissionTiming is the version-one portable service observation. Service, PreEntry and API use the stated process-local monotonic epoch. Device is a synthetic interval, never a physical GPU observation. Mode, requested delay, expected output and expected mechanism belong in separate ground truth.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/cudaprof/tracecontract"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	// Constructed replay intervals, not physical observations.
	timing := diag.SubmissionTiming{PreEntry: tracecontract.Interval{Start: 10, End: 400, Clock: "replay"}}
	fmt.Println(timing.PreEntry.Duration())
}
Output:
390

type Support

type Support = re_obsmodel.Support

type Sync

type Sync = re_obsprobe.Sync

type SyntheticFixture

type SyntheticFixture struct {
	Injection        InjectionType
	ExpectedOutcome  MechanismType
	ExpectedReason   string
	Workload         obsworkload.WorkloadIdentity
	OpID             obsworkload.OpID
	Input            DiagnosticInput
	ControlReference []float64
	TestOutput       []float64
}

SyntheticFixture encapsulates a deterministic test scenario, keeping the ground-truth injection label strictly decoupled from the input supplied to Diagnose.

func BuildSyntheticFixture

func BuildSyntheticFixture(inj InjectionType) SyntheticFixture

BuildSyntheticFixture creates a deterministic synthetic fixture for testing.

type SystemInfo

type SystemInfo = systeminfo.SystemInfo

SystemInfo is the single canonical hardware, library, clock/power, and host contention record embedded in cudaprof captures, servebench results, cudaflightrecorder bundles, and cuptiactivity relational table exports.

func CaptureSystemInfo

func CaptureSystemInfo(ctx context.Context, opts SystemInfoOptions) (*SystemInfo, error)

CaptureSystemInfo queries live host and GPU state to construct a populated SystemInfo record.

func StartCaptureSystemInfo

func StartCaptureSystemInfo(ctx context.Context, opts SystemInfoOptions) (*SystemInfo, error)

StartCaptureSystemInfo records the start-of-run SystemInfo snapshot (device identity, driver/library versions, start clocks/power, and start host load).

type SystemInfoOptions

type SystemInfoOptions = systeminfo.Options

SystemInfoOptions configures live SystemInfo collection.

type Table

type Table = re_obsmodel.Table

type Target

type Target = re_obsprobe.Target

type TelemetryDiagnosis

type TelemetryDiagnosis struct {
	Diagnosis    DiagnosisResult    `json:"diagnosis"`
	Observations []TelemetryFinding `json:"observations"`
}

TelemetryDiagnosis contains a mixed stream's admitted observations and the existing host/device diagnosis. Synthetic or imported inputs never become physically observed findings merely by passing protocol controls.

Example
package main

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

func main() {
	d := diag.TelemetryDiagnosis{Diagnosis: diag.DiagnosisResult{Mechanism: diag.MechanismWithheld}}
	fmt.Println(d.Diagnosis.Mechanism)
}
Output:
withheld

func DiagnoseTelemetry

func DiagnoseTelemetry(ctx context.Context, r io.Reader, opt TelemetryOptions) (TelemetryDiagnosis, error)

DiagnoseTelemetry reads the canonical stream, validates independent evidence links, joins explicit workload correlations and calls Diagnose. A malformed stream returns an error; missing evidence produces retained withheld findings. Reads and replay are bounded and cancellation is checked between reads and records. Cancellation cannot interrupt a caller-owned blocking Reader. V3 through V5 share the independent evidence gates. V5 histograms retain counts and optional summaries without computing deltas. OTLP clock and source-time assertions remain withheld: options do not independently admit their mapping, and serialization alone cannot establish calibration.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"strings"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	_, err := diag.DiagnoseTelemetry(ctx, strings.NewReader(""), diag.TelemetryOptions{})
	fmt.Println(errors.Is(err, context.Canceled))
}
Output:
true
Example (V5)
package main

import (
	"bytes"
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"github.com/tmc/lib/nvidia/x/obs/telemetry"
)

func main() {
	// A valid format and exact value do not supply independent evidence links.
	var stream bytes.Buffer
	writer := telemetry.NewWriter(&stream, telemetry.CollectorConfig{})
	manifest := telemetry.Manifest{SchemaVersion: telemetry.SchemaVersionV5,
		RunID: "example", Devices: []telemetry.DeviceMetadata{{UUID: "GPU-example"}}}
	if err := writer.WriteManifest(&manifest); err != nil {
		fmt.Println(err)
		return
	}
	value := uint64(1<<53 + 1)
	sample := telemetry.Sample{Seq: 1, QueryStartNanos: 1, QueryEndNanos: 2,
		Readings: []telemetry.Reading{{Name: "counter", DeviceUUID: "GPU-example",
			Evidence: telemetry.EvidenceMeasured, Number: &telemetry.Number{Uint: &value},
			Observation: &telemetry.Observation{Kind: "gauge", SourceClass: "synthetic",
				Observer: telemetry.Observer{SamplingCoverage: &telemetry.SamplingCoverage{Status: "unknown"}}}}}}
	if err := writer.WriteSample(&sample); err != nil {
		fmt.Println(err)
		return
	}
	manifest.IsComplete, manifest.TotalSamples = true, 1
	if err := writer.WriteManifest(&manifest); err != nil {
		fmt.Println(err)
		return
	}
	if _, _, _, err := telemetry.ReadStreamStrict(bytes.NewReader(stream.Bytes()), 1<<20); err != nil {
		fmt.Println(err)
		return
	}
	result, err := diag.DiagnoseTelemetry(context.Background(), bytes.NewReader(stream.Bytes()), diag.TelemetryOptions{})
	if err != nil {
		fmt.Println(err)
		return
	}
	finding := result.Observations[0]
	fmt.Println(*finding.Reading.Number.Uint)
	fmt.Println(finding.Finding.Admission.Status, finding.Finding.Admission.Reason)
}
Output:
9007199254740993
withheld missing or mismatched workload identity

type TelemetryFinding

type TelemetryFinding struct {
	Reading telemetry.Reading     `json:"reading"`
	Finding tracecontract.Finding `json:"finding"`
}

TelemetryFinding retains an exact canonical reading alongside its admission. Integer values remain in Reading.Number; Finding.Value is never a lossy float conversion of an integer. Unavailable findings retain their reading. Admission applies only to the retained reading and its evidence links, not to producer population completeness or known-zero producer loss. Diagnosis applies its independent population requirements separately.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/cudaprof/tracecontract"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"github.com/tmc/lib/nvidia/x/obs/telemetry"
)

func main() {
	f := diag.TelemetryFinding{Reading: telemetry.Reading{Name: "counter"}, Finding: tracecontract.Finding{Class: tracecontract.FindingUnavailable}}
	fmt.Println(f.Reading.Name, f.Finding.Class)
}
Output:
counter unavailable

type TelemetryOptions

type TelemetryOptions struct {
	MaxBytes           int64
	Workload           obsworkload.WorkloadIdentity
	OpID               obsworkload.OpID
	Assignment         telemetry.EntityAssignment
	ClockEpoch         string
	Observer           telemetry.Observer
	Receipt            *tracecontract.Receipt
	RawArtifacts       map[string][]byte
	ExpectedSources    map[string]telemetry.Observation
	HistogramBounds    map[string][]string
	RequireDenominator []string
	WallInterval       tracecontract.Interval
	Thresholds         Thresholds
}
Example
package main

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

func main() {
	o := diag.TelemetryOptions{MaxBytes: 1 << 20, ClockEpoch: "boot-epoch"}
	fmt.Println(o.MaxBytes, o.ClockEpoch)
}
Output:
1048576 boot-epoch

type TensorMovement

type TensorMovement = re_obsmodel.TensorMovement

type Threshold

type Threshold = re_obsmodel.Threshold

type Thresholds

type Thresholds struct {
	BaselineKernelDuration   time.Duration
	BaselineHostAPIDuration  time.Duration
	BaselinePreEntryDuration time.Duration
	HostDelayRatio           float64
	DeviceBottleneckRatio    float64
	MaxUncertaintyNS         int64
	MaxLoss                  uint64
	// TargetTID is the independently selected API caller thread. Zero means
	// no target was selected, and the API/scheduler rule withholds: supplied
	// scheduler evidence never selects its own thread. Pre-entry timing with
	// an active scheduler probe binds the validated Submission.TID instead,
	// which a nonzero TargetTID must equal.
	TargetTID uint64
}

Thresholds defines baseline timings and classification ratios.

func DefaultThresholds

func DefaultThresholds() Thresholds

DefaultThresholds returns sensible default diagnostic thresholds.

type TimeAccounting

type TimeAccounting struct {
	WallInterval         tracecontract.Interval `json:"wall_interval"`
	SummedKernelDuration time.Duration          `json:"summed_kernel_duration"`
	BusyDuration         time.Duration          `json:"busy_duration"`
	HostAPIDuration      time.Duration          `json:"host_api_duration"`
	// PreEntryDuration is nil when application timing is absent, not zero.
	PreEntryDuration  *time.Duration `json:"pre_entry_duration,omitempty"`
	RunnableDuration  time.Duration  `json:"runnable_duration"`
	ScheduledDuration time.Duration  `json:"scheduled_duration"`
	WaitDuration      time.Duration  `json:"wait_duration"`
}

TimeAccounting holds separated time dimensions for an analyzed workload or operation.

func ComputeTimeAccounting

func ComputeTimeAccounting(
	wall tracecontract.Interval,
	hostCalls []HostCallEvent,
	kernels []KernelEvent,
	sched SchedEvidence,
) (TimeAccounting, error)

ComputeTimeAccounting computes separate host, device and scheduler durations. It returns zero accounting and an error if any duration is unrepresentable.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/cudaprof/tracecontract"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	ta, err := diag.ComputeTimeAccounting(tracecontract.Interval{End: 20}, nil, []diag.KernelEvent{{Span: tracecontract.Interval{End: 10}}}, diag.SchedEvidence{})
	fmt.Println(ta.SummedKernelDuration, ta.BusyDuration, err)
}
Output:
10ns 10ns <nil>

type TimingDecomposition

type TimingDecomposition struct {
	HostElapsedNs      int64 // Host CPU wall time from submission to synchronization (or Unmeasured)
	SummedKernelNs     int64 // Sum of individual kernel launch durations (or Unmeasured)
	GPUIntervalUnionNs int64 // Non-overlapping device busy duration across streams (or Unmeasured)
	APICallNs          int64 // Duration of host driver/runtime API calls (or Unmeasured)
}

TimingDecomposition separates host elapsed time, summed kernel duration, GPU interval union, and API call duration into distinct, non-additive fields. Naive additions across these channels are explicitly rejected to prevent double-counting.

func (TimingDecomposition) TotalDuration

func (td TimingDecomposition) TotalDuration() (time.Duration, error)

TotalDuration returns an error to explicitly reject naive addition of overlapping timing channels.

type TimingScope

type TimingScope struct {
	Channel  timing.TimingKind `json:"channel"`
	Phases   []CmpPhase        `json:"phases,omitempty"`
	Interval string            `json:"interval,omitempty"`
}

TimingScope specifies the timing measurement channel, phases, and interval name.

type TimingSource

type TimingSource struct {
	Version     int                `json:"version"`
	Producer    string             `json:"producer"`
	SourceClass string             `json:"source_class"`
	ClockEpoch  string             `json:"clock_epoch"`
	Observer    telemetry.Observer `json:"observer"`
}

TimingSource identifies the portable timing observer. Matching these fields verifies a declared replay contract, not physical producer authenticity.

Example
package main

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

func main() {
	source := diag.TimingSource{Version: 1, SourceClass: "synthetic", ClockEpoch: "replay-one"}
	fmt.Println(source.Version, source.SourceClass, source.ClockEpoch)
}
Output:
1 synthetic replay-one

type Toggle

type Toggle int

Toggle is a three-state setting for the tool's yes/no options. The zero value leaves compute-sanitizer's own default in place and emits no flag.

const (
	ToggleDefault Toggle = iota // emit no flag
	ToggleYes                   // emit yes
	ToggleNo                    // emit no
)

Toggle states.

type Tool

type Tool string

Tool selects a compute-sanitizer checking tool. The values are the tool's own --tool argument spellings; this package does not invent an abstraction over them.

const (
	// Memcheck detects out-of-bounds and misaligned device memory accesses,
	// invalid API usage, and (with [Config.LeakCheck]) leaked allocations.
	Memcheck Tool = "memcheck"
	// Racecheck detects shared memory data hazards between
	// threads of a kernel.
	Racecheck Tool = "racecheck"
	// Initcheck detects device reads of uninitialized global memory.
	Initcheck Tool = "initcheck"
	// Synccheck detects invalid usage of synchronization primitives.
	Synccheck Tool = "synccheck"
)

The checking tools compute-sanitizer provides. Exactly one runs per invocation; checking a program with several means several runs.

type ToolReceipt

type ToolReceipt struct {
	Task           string                `json:"task,omitempty"`
	Tool           ToolSpec              `json:"tool"`
	ProtocolDigest string                `json:"protocol_digest"`
	RawDigest      string                `json:"raw_digest"`
	Measurements   []PropertyMeasurement `json:"measurements"`
	Synthetic      bool                  `json:"synthetic"`
}

ToolReceipt identifies an independently retained raw execution artifact. Measurements must come from that artifact, never from simulated defaults.

type ToolSpec

type ToolSpec struct {
	Name          string `json:"name"`
	Version       string `json:"version"`
	Configuration string `json:"configuration"`
	Lineage       string `json:"lineage"`
	Support       string `json:"support"`
}

ToolSpec freezes a tool's identity, configuration and support status. Support is measured, unknown or unavailable; lineage identifies shared implementations.

type TraceNovelty

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

TraceNovelty is a bounded, concurrent host filter. AllTrace admits every nonzero trace; SimplifyTrace compares edge presence; UniqueTrace compares quantized hit counts; CoverageIncrease admits a previously unseen hit class at any edge. The zero value is unusable; construct it with NewTraceNovelty. This filter has no device provenance and must not by itself authorize skipping sanitizer execution. Evaluate marks admission, not successful sanitization.

Example
package main

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

func main() {
	g, _ := diag.NewTraceNovelty(diag.GatingSimplifyTrace, 4, 8)
	first, _ := g.Evaluate([]byte{0, 1, 0, 0})
	duplicate, _ := g.Evaluate([]byte{0, 8, 0, 0})
	newEdge, _ := g.Evaluate([]byte{0, 8, 1, 0})
	fmt.Println(first, duplicate, newEdge)
}
Output:
true false true

func NewTraceNovelty

func NewTraceNovelty(mode SanitizerGating, size, maxTraces int) (*TraceNovelty, error)

NewTraceNovelty bounds trace size to 16 MiB and retained signatures to one million. Reaching maxTraces refuses further novel traces instead of eviction or silently treating them as duplicates.

func (*TraceNovelty) Evaluate

func (g *TraceNovelty) Evaluate(raw []byte) (bool, error)

Evaluate returns whether a complete raw counter vector is admitted. Empty, zero and mismatched vectors are errors and do not alter novelty state. The caller owns the vector and must not mutate it concurrently with this call.

func (*TraceNovelty) MustEvaluate

func (g *TraceNovelty) MustEvaluate(raw []byte) bool

MustEvaluate is like Evaluate, but panics if raw has a mismatched map size, contains zero coverage, or if the filter is uninitialized.

type Tracker

type Tracker = re_obsprobe.Tracker

type TrainingPhaseEdge

type TrainingPhaseEdge struct {
	PhaseID string
	GroupID string
	Outcome obsworkload.WorkloadOutcome
	Reason  string
}

TrainingPhaseEdge relates one phase/reference to existing operator evidence. Even an exact kernel join does not upgrade supplied phase membership to exact.

type TrainingSummary

type TrainingSummary struct {
	Version       int
	ContextSHA256 string
	Details       telemetry.TrainingPhaseContext
	Operators     OperatorSummary
	Recovery      telemetry.TrainingRecoverySummary
	Edges         []TrainingPhaseEdge
	Quality       string
	Reasons       []string
	Limits        []string
}

TrainingSummary retains observed activity, supplied phases, optimizer counts and checkpoint recovery separately. Quality is accepted, rejected or unknown for the supplied observed update population only, never a convergence or comparative speedup claim. Reasons retain missing or contradictory evidence. Policy details and all raw digests remain available for audit.

func AnalyzeTrainingJSONL

AnalyzeTrainingJSONL reads original context bytes, calls AnalyzeOperatorJSONL and reuses SummarizeTrainingRecovery's all-rank update/checkpoint rules. It never allocates operator duration/counters to phases or adds overlapping time. Cancellation is checked between records; a blocking Reader is caller-owned.

Example
// Constructed application logs and operator/activity bytes; no authentic
// provider, native run, independent oracle or convergence is qualified.
input, err := trainingSummaryFixture(nil)
if err != nil {
	panic(err)
}
out, err := diag.AnalyzeTrainingJSONL(context.Background(), input, telemetry.WorkloadLimits{})
if err != nil {
	panic(err)
}
fmt.Println(len(out.Details.Phases), out.Recovery.Updates.Accepted, out.Quality)
fmt.Println(out.Operators.KernelPopulation.Exact, out.Operators.MemberEdgePopulation.Associated, out.Edges[0].Outcome)
Output:
8 2 accepted
1 2 associated

type TrainingSummaryInput

type TrainingSummaryInput struct {
	Activities       io.Reader
	Operators        io.Reader
	OperatorSource   telemetry.WorkloadSource
	Details          io.Reader
	DetailSource     telemetry.WorkloadSource
	Outcomes         io.Reader
	OutcomeSource    telemetry.WorkloadSource
	Checkpoints      io.Reader
	CheckpointSource telemetry.WorkloadSource
	ExpectedPolicy   telemetry.TrainingQualityPolicy
}

type Transfer

type Transfer = re_obsmodel.Transfer

type Trial

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

Trial runs an interleaved differential comparison and produces a Report. The zero Trial is not usable; construct one with NewTrial.

func NewTrial

func NewTrial(cfg TrialConfig) (*Trial, error)

NewTrial creates a new trial runner with validated configuration.

func (*Trial) Config

func (t *Trial) Config() TrialConfig

Config returns the configuration used by the trial.

func (*Trial) Run

func (t *Trial) Run(ctx context.Context) ([]DifferentialReport, error)

Run executes the trial across all interleaved blocks and computes the differential reports.

func (*Trial) RunTrial

func (t *Trial) RunTrial(ctx context.Context) (*TrialResult, error)

RunTrial executes the trial, running warmup passes, establishing the null drift noise floor via baseline-versus-baseline controls, executing interleaved baseline-versus-candidate trials, and preserving all receipts.

type TrialConfig

type TrialConfig struct {
	WorkloadTokensPath string
	ContextLength      int
	PrefillTokens      int
	DecodeTokens       int
	InterleavedRuns    int
	WarmupRuns         int
	TimingKind         timing.TimingKind
	DeviceIndex        int
	Residency          obsmodel.Residency

	// BaselineArm provides the execution function for the baseline (e.g. C oracle).
	BaselineArm ArmRunner
	// CandidateArm provides the execution function for the candidate (e.g. Go implementation).
	CandidateArm ArmRunner
	// BaselineControlArm provides an independent baseline instance for baseline-vs-baseline null control.
	// If nil, BaselineArm is reused for the null control basket.
	BaselineControlArm ArmRunner

	// ValidateOutput verifies that the output digest produced by an arm is correct.
	// When nil, exact digest equality between baseline and candidate is required.
	ValidateOutput func(phase CmpPhase, digest string) error

	COraclePath string
	COracleArgs []string
}

TrialConfig specifies parameters for an interleaved comparison trial.

type TrialResult

type TrialResult struct {
	Reports             []DifferentialReport
	BaselineReceipts    []timing.Receipt
	CandidateReceipts   []timing.Receipt
	NullControlReceipts []timing.Receipt
	WarmupReceipts      []timing.Receipt
	NullDrift           time.Duration
}

TrialResult records the comprehensive results of a completed trial, preserving individual receipts, warmups, and null drift controls.

type Triple

type Triple = re_obsmodel.Triple

type UncertaintyCheck

type UncertaintyCheck struct {
	MethodArtifact   RegistrationArtifact `json:"method_artifact"`
	Property         string               `json:"property"`
	Unit             string               `json:"unit"`
	AbsoluteBound    float64              `json:"absolute_bound"`
	PopulationFamily string               `json:"population_family"`
	SampleCount      uint64               `json:"sample_count"`
}

UncertaintyCheck retains explicit bounded evidence identities, not acquisition authority.

type ValidatedRegisteredPair

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

ValidatedRegisteredPair is an opaque, detached integrity result. Its zero value is invalid. It establishes no authentic acquisition or measurements.

func ValidateRegisteredPair

func ValidateRegisteredPair(ctx context.Context, r Registration, l QualificationLedger, candidate, comparator RegisteredReceipt, root string) (out ValidatedRegisteredPair, resultErr error)

ValidateRegisteredPair acquires both envelopes and their prerequisite and producer artifacts under one 64 MiB operation budget. Artifact root ancestors are caller trusted; its final component and relative artifacts use the existing no-follow opener on Darwin/Linux. Other hosts refuse safe filesystem admission. The opaque result verifies integrity, not authentic acquisition. Unknown or failed role facts remain ineligible for claims regardless of provider metadata.

Example
_, err := ValidateRegisteredPair(context.Background(), Registration{}, QualificationLedger{}, RegisteredReceipt{}, RegisteredReceipt{}, "unused")
fmt.Println(err)
Output:
registration: invalid version or identity

func (ValidatedRegisteredPair) Identity

Identity returns a detached identity view. A zero handle returns a zero view.

Example
var pair ValidatedRegisteredPair
fmt.Println(pair.Identity().Version)
Output:
0

type Verdict

type Verdict = re_obsmodel.Verdict

type WorkloadIdentity

type WorkloadIdentity = re_obsworkload.WorkloadIdentity

type WorkloadOutcome

type WorkloadOutcome = re_obsworkload.WorkloadOutcome

type WorkloadSpec

type WorkloadSpec struct {
	Name             string `json:"name"`
	Concurrency      int    `json:"concurrency"`
	WarmupIterations int    `json:"warmup_iterations"`
	TestIterations   int    `json:"test_iterations"`
	BatchSize        int    `json:"batch_size"`
	InputDim         int    `json:"input_dim"`
}

WorkloadSpec configures a frozen evaluation workload.

func DefaultWorkloads

func DefaultWorkloads() []WorkloadSpec

DefaultWorkloads returns representative evaluation workloads.

Source Files

Directories

Path Synopsis
Package bwprobe measures device memory and cache bandwidth ceilings, block shapes, stream/owned mixes, and read/write mixes using calibrated GPU microbenchmarks.
Package bwprobe measures device memory and cache bandwidth ceilings, block shapes, stream/owned mixes, and read/write mixes using calibrated GPU microbenchmarks.
Package dieprobe measures GPU locality-domain topology, access latency, bandwidth, allocation cost, and compute binding.
Package dieprobe measures GPU locality-domain topology, access latency, bandwidth, allocation cost, and compute binding.
Package errbound checks kernel outputs against error bounds derived from a reference computation graph at a declared precision.
Package errbound checks kernel outputs against error bounds derived from a reference computation graph at a declared precision.
errboundcuda
Package errboundcuda runs CUDA kernels as errbound.Kernel values, on a GPU through NVRTC or on the host CPU through cudahostemu, so that errbound.Check can certify them.
Package errboundcuda runs CUDA kernels as errbound.Kernel values, on a GPU through NVRTC or on the host CPU through cudahostemu, so that errbound.Check can certify them.
plant
Package plant holds a corpus of CUDA kernels that cheat kernel correctness checks, with honest controls, for testing checkers such as github.com/tmc/lib/nvidia/x/obs/diag/errbound.
Package plant holds a corpus of CUDA kernels that cheat kernel correctness checks, with honest controls, for testing checkers such as github.com/tmc/lib/nvidia/x/obs/diag/errbound.
Package gemmrate measures the dense tensor-core GEMM rate a device achieves on one shape.
Package gemmrate measures the dense tensor-core GEMM rate a device achieves on one shape.
Package hotcold measures what one SASS instruction costs by timing a kernel against a copy of itself with that instruction replaced by a NOP.
Package hotcold measures what one SASS instruction costs by timing a kernel against a copy of itself with that instruction replaced by a NOP.
Package icacheprobe measures GPU instruction-cache capacity and miss boundaries across loop footprints.
Package icacheprobe measures GPU instruction-cache capacity and miss boundaries across loop footprints.
Package kernelcheck checks compiled NVIDIA CUBIN artifacts against their static ELF/SASS launch contracts, IEEE-754 float32 numerical parity, and CUDA-event interleaved paired timing, producing and verifying kernelreceipt/v0 receipts.
Package kernelcheck checks compiled NVIDIA CUBIN artifacts against their static ELF/SASS launch contracts, IEEE-754 float32 numerical parity, and CUDA-event interleaved paired timing, producing and verifying kernelreceipt/v0 receipts.
launchplan
Package launchplan captures a GPU program's launches as a declarative plan and replays the plan without the program.
Package launchplan captures a GPU program's launches as a declarative plan and replays the plan without the program.
launchplan/internal/lptool command
Lptool builds, compares, replays and mutates launch-plan bundles.
Lptool builds, compares, replays and mutates launch-plan bundles.
Package launchprobe measures CUDA kernel launch latency and queue overhead.
Package launchprobe measures CUDA kernel launch latency and queue overhead.
Package mioprobe measures whether reading a special register costs more when many warps on one SM read special registers at once.
Package mioprobe measures whether reading a special register costs more when many warps on one SM read special registers at once.
Package obsevidence holds portable measurement evidence records and claim verdicts re-exported by x/obs/diag and x/obs/diag/obsmodel.
Package obsevidence holds portable measurement evidence records and claim verdicts re-exported by x/obs/diag and x/obs/diag/obsmodel.
Package obsmodel provides hardware-neutral GPU roofline ceiling models and kernel execution census analysis.
Package obsmodel provides hardware-neutral GPU roofline ceiling models and kernel execution census analysis.
Package peerprobe times the hop latency between two GPUs through peer-mapped memory.
Package peerprobe times the hop latency between two GPUs through peer-mapped memory.
Package prefetchprobe measures L2 and global memory prefetch latency and SM rank behavior.
Package prefetchprobe measures L2 and global memory prefetch latency and SM rank behavior.
Package sfuprobe measures the throughput of the special function unit (MUFU) against FFMA on one GPU, in operations per SM per clock.
Package sfuprobe measures the throughput of the special function unit (MUFU) against FFMA on one GPU, in operations per SM per clock.
Package smtopology probes streaming multiprocessor cluster and cache topology on NVIDIA GPUs.
Package smtopology probes streaming multiprocessor cluster and cache topology on NVIDIA GPUs.
Package streamread measures sustained device global-memory read bandwidth across configurable streaming access patterns.
Package streamread measures sustained device global-memory read bandwidth across configurable streaming access patterns.
Package syncprobe measures device, stream, and event synchronization latency.
Package syncprobe measures device, stream, and event synchronization latency.

Jump to

Keyboard shortcuts

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