hotreload

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: 20 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.

Documentation

Overview

Package hotreload provides reusable building blocks for live CUDA kernel hot-reload loops: NVRTC compile input validation, a monotonic generation state machine with parity-gated promotion and rollback tracking, line-level diffing, and a self-contained Server-Sent Events (SSE) live view.

Compile Input Validation

ValidateSource and ValidateFlags enforce a strict allowlist over CUDA C++ sources and NVRTC compiler flags before invoking NVRTC. They reject absolute #include paths, parent-directory traversals (".."), angled or quoted includes outside an explicit allowlist, --options-file, arbitrary -I paths, and shell metacharacters. SanitizeLog strips control characters and caps compiler log output.

Generation State Machine

Session tracks edit attempts under an immutable RunID with strictly monotonic, never-recycled GenerationIDs and a separate ServingGenerationID. Promotion to ServingGenerationID requires both a successful swap and a passing parity check; failures preserve the previous serving generation and record a RollbackRecord. StageTimings stores monotonic nanosecond durations as pointers so unexecuted stages are omitted from JSON rather than reported as zero. NeedsRecapture detects grid, block, shared-memory, or parameter-signature changes that require CUDA graph recapture instead of in-place kernel-node patching.

Live View and Lazy Panes

LiveView is a read-only net/http.Handler serving a self-contained HTML instrument view with zero external CDN dependencies, JSON state snapshots at /api/state, on-demand panes at /api/pane, SSE updates at /events, and optional read-only profile artifact slots at /artifacts/overview.html and /artifacts/compare.html. LazyPaneCache computes expensive PTX, SASS, Tile IR, and diff panes on demand with singleflight deduplication so edit-to-SSE publish is not blocked by disassembly or secondary compilation. Every request is checked for an exact loopback Host header, absent Origin header, non-cross-site Sec-Fetch-Site, strict Content-Security-Policy and nosniff headers, and per-session bearer-token authentication (unless explicitly disabled for local interactive loopback use).

Kernel Slots, Paired ABBA Scoring, and Autonomous Ratchet

SlotRegistry manages KernelSlot targets with locked kernel signatures, bounded editable LaunchConfig parameters, real training shapes, unseen held-out verification shapes, and FidelityLevel tiers ("a", "b", "c"). GatherTopKSlot provides the built-in gatherTopK optimization target. ScoreABBA evaluates paired A, B, B, A repeats with hard parity gating, NVML throttle-reason rejection, cross-device guards, and two-sided significance testing. Ratchet drives a hypothesis queue with per-attempt time boxes, refuted-key memory, CUDA context poison fault recovery, and isolated per-attempt staging refs.

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

Example
package main

import (
	"fmt"
	"time"

	"github.com/tmc/lib/nvidia/x/cuda/hotreload"
)

func main() {
	src := `extern "C" __global__ void saxpy(float* out, int n) {}`
	digest, err := hotreload.ValidateSource(src, hotreload.CompileOptions{
		Flags: []string{"--std=c++20", "--gpu-architecture=sm_103a"},
	})
	if err != nil {
		panic(err)
	}

	sess := hotreload.NewSessionWithRunID("demo-run", "GPU (sm_103a)", 1024)
	g := sess.BeginAttempt(digest)
	g.Status = hotreload.StatusOK
	g.Swap = "capture"
	g.ParityPassed = true
	g.P50US = hotreload.Float64Ptr(12.5)
	g.GBs = hotreload.Float64Ptr(1600)
	g.Timings.CompileNS = hotreload.DurationPtr(18 * time.Millisecond)

	snap := sess.Record(g, []hotreload.Pane{{Name: "C++", Text: src}})
	fmt.Printf("run=%s serving=%d eligible=%v\n", snap.RunID, snap.ServingGenerationID, snap.Current.Eligible)
}
Output:
run=demo-run serving=1 eligible=true

Index

Examples

Constants

View Source
const (
	HypothesisQueued         = "queued"
	HypothesisRunning        = "running"
	HypothesisAccepted       = "accepted"
	HypothesisRefuted        = "refuted"
	HypothesisSkippedRefuted = "skipped_refuted"
	HypothesisFailed         = "failed"
	HypothesisTimedOut       = "timed_out"
)

Hypothesis status values.

View Source
const (
	OutcomeHelped   = "helped"
	OutcomeNoEffect = "no_effect"
	OutcomeHurt     = "hurt"
	OutcomeInvalid  = "invalid"
)

Outcome classifies the result of a scored candidate attempt.

View Source
const (
	VerdictSignificantWin        = "significant_win"
	VerdictSignificantRegression = "significant_regression"
	VerdictWithinNoise           = "within_noise"
	VerdictInvalid               = "invalid"
)

Verdict gives the statistical decision of a paired ABBA comparison.

View Source
const (
	StatusOK           = "ok"
	StatusCompileError = "compile error"
	StatusSwapFailed   = "swap failed"
	StatusTestFailed   = "test failed"
)

Generation status values.

View Source
const DefaultMaxLogBytes = 16 << 10

DefaultMaxLogBytes is the default cap applied by SanitizeLog.

View Source
const MaxDiffLines = 4000

MaxDiffLines bounds the quadratic LCS diff computed by ComputeLineDiff.

View Source
const StrictCSP = "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'"

StrictCSP is the Content-Security-Policy header set on LiveView responses.

Variables

View Source
var (
	ErrHypothesisRefuted = errors.New("hotreload: hypothesis key already refuted")
	ErrQueueEmpty        = errors.New("hotreload: hypothesis queue is empty")
)

Sentinel errors returned by Ratchet.

View Source
var ErrPaneNotFound = errors.New("hotreload: pane not found")

ErrPaneNotFound is returned by LazyPaneCache.Get when no pane or provider is registered for the requested (generation_id, pane_name) pair.

Functions

func BuildABBASchedule

func BuildABBASchedule(blocks int) []string

BuildABBASchedule returns the execution order ("A", "B", "B", "A", ...) for blocks paired repeats.

func ComputeLineDiff

func ComputeLineDiff(a, b string) string

ComputeLineDiff returns a unified-style line diff of a and b where each line is prefixed with " ", "- ", or "+ ". It returns "" when a and b are equal.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/hotreload"
)

func main() {
	diff := hotreload.ComputeLineDiff("a\nb\nc\n", "a\nB\nc\n")
	fmt.Print(diff)
}
Output:
  a
- b
+ B
  c

func DurationPtr

func DurationPtr(d time.Duration) *int64

DurationPtr returns a pointer to d in nanoseconds for use in StageTimings.

func Float64Ptr

func Float64Ptr(v float64) *float64

Float64Ptr returns a pointer to v for optional numeric fields on Generation.

func IsContextPoisonError

func IsContextPoisonError(err error) bool

IsContextPoisonError reports whether err indicates a poisoned CUDA context (illegal address, hardware trap, destroyed context, or watchdog timeout).

func NeedsRecapture

func NeedsRecapture(prev, next LaunchConfig) (bool, string)

NeedsRecapture reports whether transitioning from prev to next requires recapturing the CUDA graph instead of patching the kernel node in place.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/hotreload"
)

func main() {
	prev := hotreload.LaunchConfig{
		GridDim:    [3]uint32{64, 1, 1},
		BlockDim:   [3]uint32{256, 1, 1},
		ParamSizes: []uint{8, 8, 4},
	}
	next := prev
	next.GridDim[0] = 128

	recapture, reason := hotreload.NeedsRecapture(prev, next)
	fmt.Printf("recapture=%v reason=%s\n", recapture, reason)
}
Output:
recapture=true reason=grid dim changed

func Percentile

func Percentile(d []time.Duration, p float64) time.Duration

Percentile returns the p-th percentile (0..100) of d by nearest rank.

func SanitizeLog

func SanitizeLog(raw string, maxBytes int) string

SanitizeLog strips ANSI escape sequences and control characters (preserving '\n' and '\t') from compiler log output and caps the result to maxBytes. When maxBytes <= 0, DefaultMaxLogBytes is used.

func SourceSHA256

func SourceSHA256(src string) string

SourceSHA256 returns the lowercase hexadecimal SHA-256 digest of src.

func ValidateFlags

func ValidateFlags(flags []string, bundledIncludeDir string) error

ValidateFlags checks each NVRTC flag against a fixed allowlist. It rejects --options-file, shell metacharacters, unknown flags, and -I paths outside bundledIncludeDir.

func ValidateSource

func ValidateSource(src string, opts CompileOptions) (string, error)

ValidateSource checks src and opts.Flags against the NVRTC input policy and returns the source SHA-256 hex digest on success.

It rejects #include directives with absolute paths, parent-directory traversal (".."), or headers outside opts.AllowedIncludes, as well as any compiler flag not in the fixed allowlist.

func WriteSSEEvent

func WriteSSEEvent(w io.Writer, event string, id int, data []byte) error

WriteSSEEvent writes one Server-Sent Event frame. Data must not contain raw newlines (which holds for compact encoding/json output).

Types

type ABBABlock

type ABBABlock struct {
	A1 Sample `json:"a1"`
	B1 Sample `json:"b1"`
	B2 Sample `json:"b2"`
	A2 Sample `json:"a2"`
}

ABBABlock holds one paired A, B, B, A measurement block where A is the current best baseline and B is the candidate kernel.

type AttemptRecord

type AttemptRecord struct {
	GenerationID    int          `json:"generation_id"`
	RunID           string       `json:"run_id"`
	HypothesisID    string       `json:"hypothesis_id"`
	HypothesisKey   string       `json:"hypothesis_key"`
	SlotName        string       `json:"slot_name"`
	CandidateDigest string       `json:"candidate_digest"`
	StagingRef      string       `json:"staging_ref"`
	Score           *ScoreResult `json:"score,omitempty"`
	PromotionPassed bool         `json:"promotion_passed"`
	Promoted        bool         `json:"promoted"`
	RecoveredFault  bool         `json:"recovered_fault,omitempty"`
	Err             string       `json:"err,omitempty"`
	StartedAt       time.Time    `json:"started_at"`
	FinishedAt      time.Time    `json:"finished_at"`
}

AttemptRecord captures one executed or rejected ratchet attempt, including its isolated staging ref (never auto-merged to main).

type BestState

type BestState struct {
	GenerationID int          `json:"generation_id"`
	Digest       string       `json:"digest"`
	Source       string       `json:"source,omitempty"`
	Launch       LaunchConfig `json:"launch"`
	StagingRef   string       `json:"staging_ref,omitempty"`
	Score        ScoreResult  `json:"score"`
}

BestState tracks the currently promoted best candidate.

type CompileOptions

type CompileOptions struct {
	// AllowedIncludes is the explicit allowlist of header names permitted in
	// #include directives (e.g. "cuda_tile.h").
	AllowedIncludes []string

	// BundledIncludeDir is the single directory permitted for -I / --include-path
	// flags. When empty, all include-path flags are rejected.
	BundledIncludeDir string

	// Flags are the NVRTC compiler flags to validate.
	Flags []string

	// MaxLogBytes caps sanitized compiler log output. Zero selects DefaultMaxLogBytes.
	MaxLogBytes int
}

CompileOptions configures source and flag validation prior to NVRTC compilation.

type Delta

type Delta struct {
	Against int     `json:"against"`
	P50Pct  float64 `json:"p50_pct"`
	GBsPct  float64 `json:"gbs_pct"`
}

Delta compares an eligible generation's performance against the previous eligible generation.

func ComputeDelta

func ComputeDelta(hist []Generation, cur Generation) *Delta

ComputeDelta compares cur against the most recent earlier eligible generation in hist. It returns nil if cur is ineligible or no prior eligible generation exists.

type EvaluateFunc

type EvaluateFunc func(ctx context.Context, h Hypothesis, best BestState) (ScoreResult, error)

EvaluateFunc compiles, runs, and scores candidate h against best.

type FaultRecovery

type FaultRecovery struct {
	// MaxRestarts bounds automatic worker restarts per Ratchet. Zero defaults to 3.
	MaxRestarts int

	// RestartFunc restarts the GPU worker process and restores session state.
	RestartFunc func(ctx context.Context, reason string) error

	// IsPoisoned classifies errors that require a worker restart.
	// When nil, [IsContextPoisonError] is used.
	IsPoisoned func(err error) bool
}

FaultRecovery configures automatic worker restart on CUDA context poison (illegal address, trap, or hang watchdog timeout) without losing the session's RunID or monotonic GenerationID sequence.

type FidelityLevel

type FidelityLevel string

FidelityLevel identifies the profiling and verification tier for a kernel slot evaluation.

const (
	// FidelityTimingCUPTI ("a") runs CUDA event timing and lightweight CUPTI
	// activity tracing for fast inner-loop iterations.
	FidelityTimingCUPTI FidelityLevel = "a"

	// FidelityPromotion ("b") adds CUPTI PC sampling, PM/IKET metrics, and
	// compute-sanitizer checks before promoting a candidate.
	FidelityPromotion FidelityLevel = "b"

	// FidelityDeepTrace ("c") adds full Perfetto trace capture and HTML
	// overview/compare artifacts for deep post-hoc analysis.
	FidelityDeepTrace FidelityLevel = "c"
)

func (FidelityLevel) Description

func (f FidelityLevel) Description() string

Description returns a short factual summary of the fidelity level.

func (FidelityLevel) Valid

func (f FidelityLevel) Valid() bool

Valid reports whether f is one of the defined fidelity levels.

type Generation

type Generation struct {
	ID               int             `json:"generation_id"`
	Digest           string          `json:"digest"`
	WallAnchor       string          `json:"wall_anchor"`
	Status           string          `json:"status"`
	Swap             string          `json:"swap"`
	Launch           *LaunchConfig   `json:"launch,omitempty"`
	ParityPassed     bool            `json:"parity_passed"`
	MaxErr           *float64        `json:"max_err,omitempty"`
	P50US            *float64        `json:"p50_us,omitempty"`
	P95US            *float64        `json:"p95_us,omitempty"`
	GBs              *float64        `json:"gbs,omitempty"`
	Regs             int             `json:"regs,omitempty"`
	Timings          StageTimings    `json:"timings"`
	Rollback         *RollbackRecord `json:"rollback,omitempty"`
	Eligible         bool            `json:"eligible"`
	IneligibleReason string          `json:"ineligible_reason,omitempty"`
	Err              string          `json:"err,omitempty"`
}

Generation records one edit attempt in a hot-reload Session.

type Hypothesis

type Hypothesis struct {
	ID       string        `json:"id"`
	Key      string        `json:"key"`
	SlotName string        `json:"slot_name"`
	Summary  string        `json:"summary"`
	Source   string        `json:"source"`
	Launch   LaunchConfig  `json:"launch"`
	Fidelity FidelityLevel `json:"fidelity,omitempty"`
	Status   string        `json:"status"`
}

Hypothesis describes one candidate optimization queued for the Ratchet.

type KernelSlot

type KernelSlot struct {
	Name                string          `json:"name"`
	Entry               string          `json:"entry"`
	Signature           string          `json:"signature"`
	ParamSizes          []uint          `json:"param_sizes,omitempty"`
	Source              string          `json:"source"`
	CompileOpts         CompileOptions  `json:"compile_opts,omitempty"`
	Launch              LaunchConfig    `json:"launch"`
	Bounds              LaunchBounds    `json:"bounds"`
	TrainShapes         []Shape         `json:"train_shapes,omitempty"`
	HeldOutShapes       []Shape         `json:"held_out_shapes,omitempty"`
	SupportedFidelities []FidelityLevel `json:"supported_fidelities,omitempty"`
	DefaultFidelity     FidelityLevel   `json:"default_fidelity,omitempty"`
	ReferenceDigest     string          `json:"reference_digest"`
	DeviceArch          string          `json:"device_arch"`
	BaselineUS          float64         `json:"baseline_us,omitempty"`
}

KernelSlot defines one registered optimization target with a locked kernel signature, editable bounded launch geometry, real training shapes, unseen held-out verification shapes, and a device-specific baseline.

func GatherTopKSlot

func GatherTopKSlot() KernelSlot

GatherTopKSlot returns the built-in first autonomous optimization target: gatherTopK (~9.7 us/launch baseline on sm_121a), defaulting to fidelity "a" with validated editable launch bounds and distinct real training and unseen held-out shapes.

func (KernelSlot) AgentView

func (s KernelSlot) AgentView() KernelSlot

AgentView returns a copy of s with HeldOutShapes cleared so autonomous agents cannot inspect or overfit to held-out verification shapes.

func (KernelSlot) SupportsFidelity

func (s KernelSlot) SupportsFidelity(level FidelityLevel) bool

SupportsFidelity reports whether level is enabled for this slot.

type LaunchBounds

type LaunchBounds struct {
	MaxGridDim         [3]uint32 `json:"max_grid_dim"`
	MaxBlockDim        [3]uint32 `json:"max_block_dim"`
	MaxThreadsPerBlock uint32    `json:"max_threads_per_block"`
	MaxSharedMem       uint32    `json:"max_shared_mem"`
}

LaunchBounds constrains editable LaunchConfig parameters for a KernelSlot.

func DefaultLaunchBounds

func DefaultLaunchBounds() LaunchBounds

DefaultLaunchBounds returns conservative CUDA launch bounds suitable for sm_80+ GPUs when a slot does not specify tighter limits.

func (LaunchBounds) Validate

func (b LaunchBounds) Validate(cfg LaunchConfig) error

Validate checks cfg against b, rejecting zero dimensions, out-of-range grid or block sizes, excess threads per block, or excess dynamic shared memory.

type LaunchConfig

type LaunchConfig struct {
	GridDim    [3]uint32 `json:"grid_dim"`
	BlockDim   [3]uint32 `json:"block_dim"`
	SharedMem  uint32    `json:"shared_mem"`
	ParamSizes []uint    `json:"param_sizes,omitempty"`
}

LaunchConfig describes the CUDA kernel launch geometry and ABI signature captured in an instantiated graph node.

type LazyPaneCache

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

LazyPaneCache computes expensive panes (such as PTX, SASS, Tile IR, and line-level diffs) on demand or asynchronously with singleflight deduplication and caching keyed by (generation_id, pane_name).

func NewLazyPaneCache

func NewLazyPaneCache(maxGens int) *LazyPaneCache

NewLazyPaneCache creates a LazyPaneCache that retains up to maxGens generations. If maxGens <= 0, it defaults to 32.

func (*LazyPaneCache) Get

func (c *LazyPaneCache) Get(ctx context.Context, genID int, name string) (Pane, error)

Get returns the cached pane for (genID, name), computing it on demand with singleflight deduplication if only a provider is registered.

func (*LazyPaneCache) Names

func (c *LazyPaneCache) Names(genID int) []string

Names returns all pane names registered or cached for genID in sorted order.

func (*LazyPaneCache) Prefetch

func (c *LazyPaneCache) Prefetch(ctx context.Context, genID int, name string)

Prefetch starts asynchronous computation of (genID, name) in the background if it is not already cached or in flight.

func (*LazyPaneCache) Put

func (c *LazyPaneCache) Put(genID int, p Pane)

Put stores an already-computed pane in the cache.

func (*LazyPaneCache) Register

func (c *LazyPaneCache) Register(genID int, name string, fn PaneComputeFunc)

Register binds an on-demand compute function for (genID, name). Calling Register replaces any prior provider or cached value for that key.

type LiveView

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

LiveView is a read-only HTTP handler that serves a self-contained kernel hot-reload instrument page, JSON state snapshots, Server-Sent Events, and optional profile HTML artifacts.

func NewLiveView

func NewLiveView(cfg LiveViewConfig) *LiveView

NewLiveView constructs a LiveView with the given configuration.

func (*LiveView) Publish

func (v *LiveView) Publish(snap Snapshot) error

Publish stores snap and fans it out to all active SSE subscribers. Subscribers that fall behind drop the intermediate snapshot and receive the next one.

func (*LiveView) ServeHTTP

func (v *LiveView) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP enforces loopback Host validation, Origin/Sec-Fetch-Site rejection, read-only HTTP methods, strict security headers, and bearer-token auth before dispatching to the read-only routes.

func (*LiveView) SetPaneCache

func (v *LiveView) SetPaneCache(cache *LazyPaneCache)

SetPaneCache attaches or replaces the LazyPaneCache used by GET /api/pane.

func (*LiveView) SetProfileHTML

func (v *LiveView) SetProfileHTML(overviewHTML, compareHTML string)

SetProfileHTML updates the optional read-only profile artifact slots (e.g. cudaprof overview -html and compare -html outputs). If a snapshot has already been published, subscribers are notified of the updated artifact availability.

func (*LiveView) Subscribe

func (v *LiveView) Subscribe() (<-chan []byte, func())

Subscribe returns a channel of marshaled Snapshot JSON payloads primed with the latest snapshot (if any), and a cancel function that unsubscribes.

func (*LiveView) Token

func (v *LiveView) Token() string

Token returns the configured or generated bearer token. It is empty when AllowUnauthenticatedLoopback is true and no BearerToken was supplied.

type LiveViewConfig

type LiveViewConfig struct {
	// BearerToken is the per-session secret required in Authorization: Bearer <token>.
	// When empty and AllowUnauthenticatedLoopback is false, NewLiveView generates
	// a random 32-byte hex token accessible via LiveView.Token.
	BearerToken string

	// AllowQueryToken permits ?token=<token> as a fallback to Authorization: Bearer
	// for browser EventSource connections that cannot set custom request headers.
	AllowQueryToken bool

	// AllowUnauthenticatedLoopback disables bearer-token authentication for local
	// interactive CLI demos. Loopback Host, Origin, and Sec-Fetch-Site checks
	// remain enforced.
	AllowUnauthenticatedLoopback bool

	// PaneCache optionally serves on-demand panes at GET /api/pane?gen=N&name=X
	// so expensive PTX/SASS/Tile rendering does not block SSE publishing.
	PaneCache *LazyPaneCache
}

LiveViewConfig configures the security and authentication behavior of LiveView.

type Pane

type Pane struct {
	Name  string `json:"name"`
	Text  string `json:"text"`
	Diff  string `json:"diff,omitempty"`
	Bytes int    `json:"bytes"`
	Note  string `json:"note,omitempty"`
}

Pane is one rendered view of the kernel (source, Go host code, Tile IR, PTX, or SASS) along with its line-level diff against the previous generation.

type PaneComputeFunc

type PaneComputeFunc func(ctx context.Context) (Pane, error)

PaneComputeFunc computes a Pane on demand.

type PaneKey

type PaneKey struct {
	GenerationID int
	Name         string
}

PaneKey identifies a rendered pane for a specific generation.

type PromotionGateFunc

type PromotionGateFunc func(ctx context.Context, h Hypothesis, score ScoreResult) error

PromotionGateFunc runs an optional final gate (such as compute-sanitizer or fidelity-b verification) before advancing the ratchet's best pointer.

type Ratchet

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

Ratchet coordinates autonomous optimization attempts with a hypothesis queue, per-attempt time box, refuted-key memory, fault recovery, and strict best-so-far promotion gating.

func NewRatchet

func NewRatchet(cfg RatchetConfig) *Ratchet

NewRatchet creates a Ratchet bound to cfg.Session (or a new session if nil).

func (*Ratchet) Attempts

func (r *Ratchet) Attempts() []AttemptRecord

Attempts returns a copy of all recorded attempts.

func (*Ratchet) Best

func (r *Ratchet) Best() BestState

Best returns the current best-so-far state.

func (*Ratchet) Enqueue

func (r *Ratchet) Enqueue(h Hypothesis) error

Enqueue adds h to the hypothesis queue, rejecting keys that are already refuted with ErrHypothesisRefuted.

func (*Ratchet) IsRefuted

func (r *Ratchet) IsRefuted(key string) bool

IsRefuted reports whether key has been marked refuted.

func (*Ratchet) RefutedKeys

func (r *Ratchet) RefutedKeys() []string

RefutedKeys returns all refuted keys in sorted order.

func (*Ratchet) Restarts

func (r *Ratchet) Restarts() int

Restarts returns the number of automatic worker restarts performed.

func (*Ratchet) RunAll

func (r *Ratchet) RunAll(ctx context.Context, eval EvaluateFunc) ([]AttemptRecord, error)

RunAll drains the hypothesis queue until empty or ctx is cancelled.

func (*Ratchet) RunNext

func (r *Ratchet) RunNext(ctx context.Context, eval EvaluateFunc) (AttemptRecord, error)

RunNext dequeues and evaluates the next hypothesis under the configured attempt timeout, promotion gate, and fault-recovery policy.

func (*Ratchet) SeedRefuted

func (r *Ratchet) SeedRefuted(keys ...string)

SeedRefuted pre-populates refuted hypothesis keys or source digests (for example from prior notebooks) so they are never retried.

func (*Ratchet) Session

func (r *Ratchet) Session() *Session

Session returns the underlying Session whose RunID and GenerationID remain monotonic across fault recoveries.

type RatchetConfig

type RatchetConfig struct {
	Session        *Session
	Registry       *SlotRegistry
	AttemptTimeout time.Duration
	FaultRecovery  FaultRecovery
	PromotionGate  PromotionGateFunc
	StagingPrefix  string
}

RatchetConfig configures a Ratchet.

type RollbackRecord

type RollbackRecord struct {
	Attempted int    `json:"attempted"`
	Restored  int    `json:"restored"`
	Digest    string `json:"digest"`
	Reason    string `json:"reason,omitempty"`
}

RollbackRecord records a failed attempt and the previously serving generation that remained or was restored on the GPU.

type Sample

type Sample struct {
	DurationNS      int64   `json:"duration_ns"`
	ClockMHz        uint32  `json:"clock_mhz,omitempty"`
	PowerW          float64 `json:"power_w,omitempty"`
	ThrottleReasons uint64  `json:"throttle_reasons,omitempty"`
}

Sample is a single GPU timing measurement paired with NVML telemetry. Any sample with a non-zero ThrottleReasons bitmask is rejected by ScoreABBA.

func (Sample) Valid

func (s Sample) Valid() bool

Valid reports whether s has a positive duration and zero NVML throttle flags.

type ScoreRequest

type ScoreRequest struct {
	SlotName            string             `json:"slot_name"`
	BaselineDeviceArch  string             `json:"baseline_device_arch"`
	CandidateDeviceArch string             `json:"candidate_device_arch"`
	ReferenceDigest     string             `json:"reference_digest"`
	CandidateDigest     string             `json:"candidate_digest"`
	Train               []ShapeMeasurement `json:"train"`
	HeldOut             []ShapeMeasurement `json:"held_out,omitempty"`
}

ScoreRequest is the input to ScoreABBA.

type ScoreResult

type ScoreResult struct {
	Verdict          string  `json:"verdict"`
	Outcome          string  `json:"outcome"`
	ParityPassed     bool    `json:"parity_passed"`
	HeldOutPassed    bool    `json:"held_out_passed"`
	MeanSpeedupPct   float64 `json:"mean_speedup_pct"`
	MedianSpeedupPct float64 `json:"median_speedup_pct"`
	MeanDeltaNS      float64 `json:"mean_delta_ns"`
	MedianDeltaNS    float64 `json:"median_delta_ns"`
	StdErrNS         float64 `json:"std_err_ns"`
	TStat            float64 `json:"t_stat"`
	ValidBlocks      int     `json:"valid_blocks"`
	RejectedBlocks   int     `json:"rejected_blocks"`
	ThrottledSamples int     `json:"throttled_samples"`
	ScorerDigest     string  `json:"scorer_digest,omitempty"`
	ProbeDigest      string  `json:"probe_digest,omitempty"`
	ReferenceDigest  string  `json:"reference_digest,omitempty"`
	DeviceArch       string  `json:"device_arch,omitempty"`
	Reason           string  `json:"reason,omitempty"`
}

ScoreResult is the immutable, provenance-stamped output of ScoreABBA.

func ScoreABBA

func ScoreABBA(cfg ScorerConfig, req ScoreRequest) ScoreResult

ScoreABBA evaluates paired ABBA measurements against parity, NVML throttle filtering, device-arch matching, noise floor, and two-sided significance.

type ScorerConfig

type ScorerConfig struct {
	// ScorerUID and WorkerUID document and enforce process isolation between
	// the trusted scorer and the untrusted worker running candidate code.
	ScorerUID int `json:"scorer_uid,omitempty"`
	WorkerUID int `json:"worker_uid,omitempty"`

	// MinValidBlocks is the minimum number of unthrottled ABBA blocks required
	// across the evaluated shapes. Zero defaults to 4.
	MinValidBlocks int `json:"min_valid_blocks,omitempty"`

	// NoiseFloorPct is the minimum absolute mean and median speedup percentage
	// required to declare a win or regression. Zero defaults to 1.0 (1%).
	NoiseFloorPct float64 `json:"noise_floor_pct,omitempty"`

	// MinZScore is the two-sided significance threshold on the paired t/z
	// statistic. Zero defaults to 2.0.
	MinZScore float64 `json:"min_z_score,omitempty"`

	// MaxThrottleRatio caps the fraction of blocks that may be rejected due to
	// NVML throttling before the run is declared invalid. Zero defaults to 0.5.
	MaxThrottleRatio float64 `json:"max_throttle_ratio,omitempty"`

	// Provenance digests stamped onto every ScoreResult.
	ScorerDigest string `json:"scorer_digest,omitempty"`
	ProbeDigest  string `json:"probe_digest,omitempty"`
}

ScorerConfig configures ScoreABBA.

The scorer MUST run outside the worker UID and never trust worker-reported timings; both ScorerUID and WorkerUID must be positive (> 0) and distinct, otherwise ScoreABBA rejects the measurement as invalid.

type Session

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

Session manages the monotonic generation state machine for one hot-reload run.

func NewSession

func NewSession(device string, elems int) *Session

NewSession creates a Session with a fresh random immutable RunID.

func NewSessionWithRunID

func NewSessionWithRunID(runID, device string, elems int) *Session

NewSessionWithRunID creates a Session with an explicit immutable RunID.

func (*Session) BeginAttempt

func (s *Session) BeginAttempt(digest string) Generation

BeginAttempt allocates the next strictly monotonic positive GenerationID and stamps WallAnchor with the current UTC RFC3339Nano timestamp.

func (*Session) Record

func (s *Session) Record(g Generation, panes []Pane) Snapshot

Record finalizes generation g, enforces the parity gate before promoting ServingGenerationID, attaches rollback metadata on failure, computes pane diffs and performance delta, and returns the updated Snapshot.

func (*Session) RunID

func (s *Session) RunID() string

RunID returns the immutable session identifier.

func (*Session) ServingGenerationID

func (s *Session) ServingGenerationID() int

ServingGenerationID returns the currently serving generation ID, or 0 if no generation has passed the parity gate yet.

func (*Session) Snapshot

func (s *Session) Snapshot() Snapshot

Snapshot returns a copy of the current session state.

type Shape

type Shape struct {
	Name  string `json:"name"`
	Dims  []int  `json:"dims"`
	Elems int    `json:"elems,omitempty"`
	Note  string `json:"note,omitempty"`
}

Shape describes one concrete problem geometry used for training or held-out verification of a KernelSlot.

type ShapeMeasurement

type ShapeMeasurement struct {
	ShapeName    string      `json:"shape_name"`
	HeldOut      bool        `json:"held_out,omitempty"`
	ParityPassed bool        `json:"parity_passed"`
	MaxErr       float64     `json:"max_err,omitempty"`
	Blocks       []ABBABlock `json:"blocks"`
}

ShapeMeasurement holds parity status and paired ABBA blocks for one shape.

type SlotRegistry

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

SlotRegistry stores registered KernelSlot targets and validates candidate edits against L5 source validation, signature lock, and launch bounds.

func NewSlotRegistry

func NewSlotRegistry() *SlotRegistry

NewSlotRegistry creates an empty SlotRegistry.

func (*SlotRegistry) Get

func (r *SlotRegistry) Get(name string) (KernelSlot, bool)

Get returns a copy of the named slot.

func (*SlotRegistry) List

func (r *SlotRegistry) List() []KernelSlot

List returns copies of all registered slots sorted by name.

func (*SlotRegistry) Register

func (r *SlotRegistry) Register(slot KernelSlot) error

Register adds or replaces a KernelSlot after validating its metadata, bounds, fidelities, and baseline source.

func (*SlotRegistry) ValidateCandidate

func (r *SlotRegistry) ValidateCandidate(slotName, source string, launch LaunchConfig) (string, error)

ValidateCandidate enforces L5 ValidateSource, locked kernel signature and ABI parameter sizes, and LaunchBounds for a candidate edit against slotName. On success it returns the candidate source SHA-256 hex digest.

type Snapshot

type Snapshot struct {
	RunID               string       `json:"run_id"`
	ServingGenerationID int          `json:"serving_generation_id"`
	Current             *Generation  `json:"current,omitempty"`
	Delta               *Delta       `json:"delta,omitempty"`
	History             []Generation `json:"history"`
	LastError           string       `json:"last_error,omitempty"`
	Panes               []Pane       `json:"panes,omitempty"`
	Device              string       `json:"device,omitempty"`
	Elems               int          `json:"elems,omitempty"`
	HasOverview         bool         `json:"has_overview,omitempty"`
	HasCompare          bool         `json:"has_compare,omitempty"`
}

Snapshot is the complete, immutable state pushed to LiveView subscribers.

type StageTimings

type StageTimings struct {
	CompileNS *int64 `json:"compile_ns,omitempty"`
	PatchNS   *int64 `json:"patch_ns,omitempty"`
	ParityNS  *int64 `json:"parity_ns,omitempty"`
	BenchNS   *int64 `json:"bench_ns,omitempty"`
	PanesNS   *int64 `json:"panes_ns,omitempty"`
	PublishNS *int64 `json:"publish_ns,omitempty"`
}

StageTimings holds monotonic durations in nanoseconds for each reload stage. Pointer fields ensure unexecuted stages are omitted from JSON rather than serialized as zero.

Jump to

Keyboard shortcuts

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