gpuactivity

package
v0.206.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package gpuactivity answers one question about this box's cards: WHAT is the harness doing on them right now — not merely whether something holds them.

The gap it closes (2026-09-14, register D-93). Every surface a session could read said "busy" and nothing more: `gpu status` and `offload_status.gpu_lease` reported a lease's holder pid, age and reason; the drain printed "1 in flight" sixty-one times; llama-swap's /running said a seat was loaded. None of them said whether the cards were doing work or sitting held and unused, which request was in flight, whose run it belonged to, how far along it was, or whether it was still generating. A session that cannot tell those apart reads every "busy" as "refuse", and that reading is the tenth-time incident ADR 0039 exists to stop.

Three readings compose the answer, each from the source that owns it:

  • the LEASE (internal/gpulease): who reserved the cards, whether that process is alive, what command it wrapped, when it last heartbeat;
  • the SEAT (internal/seatload): whether llama-swap has the agent seat loaded, whether it is still loading, and how many requests the engine itself reports running or waiting;
  • the RUNS (this package's registry): every agent loop in flight on this box, registered by the process that runs it, with its step, its token count, its phase and a heartbeat — the harness's own unit of work, which a seat's per-request gauge cannot see between one step and the next.

Plus one sample of the cards themselves (nvidia-smi utilization and memory, and the processes on them), so a lease held over an idle card is named as exactly that.

THE REGISTRY. A run is a multi-step loop: the seat is idle for seconds between steps while the loop parses a tool call and runs it, and a drain that reads only the seat's gauge sees "0 in flight" in that gap, unloads the seat, and the run's next step dies behind the fence (10:08:29 on 2026-09-14: the drain unloaded the 27B the instant a first step returned; the run's second step then waited its whole 600 s wall). Registration is what makes the run visible: `Start` writes one small JSON file under `<state root>/gpu/activity/` beside the lease, updates it on every step and every 15 s, and removes it at the end. Readers apply the lease's own staleness rule (a dead or recycled pid, or a heartbeat older than HeartbeatTTL, is debris and is swept), so a crashed process cannot hold a drain hostage. The registry never gates anything by itself — the drain and the run-slot wait (internal/modelaffinity) read it.

Index

Constants

View Source
const (
	// ContextRestart and ContextSleepWake are the incident labels.
	ContextRestart   = "restart"
	ContextSleepWake = "sleep-wake"
)
View Source
const (
	// HeartbeatEvery is how often a live run refreshes its record without any
	// step progress — a single 27B completion runs 3–4 minutes, longer than any
	// staleness window worth having.
	HeartbeatEvery = 15 * time.Second
	// HeartbeatTTL is the staleness bound on a record whose process is still
	// alive: a hung process that stopped beating is not a run anyone waits for.
	// Same figure as the lease's DefaultHeartbeatTTL, on purpose.
	HeartbeatTTL = 120 * time.Second

	// DirName is the registry directory, a sibling of the lease directory under
	// the same `gpu/` root — one state root, one resolver (gpulease.LeaseDir).
	DirName = "activity"
)
View Source
const (
	// PhaseAdmission is a run waiting for the endpoint to settle: cordon, swap
	// pre-flight, warm-up and coherence probe, before a single token.
	PhaseAdmission = "admission"
	// PhaseColdLoad is the seat loading for this run; PhaseCoherenceProbe is
	// the one short probe that follows it; PhaseWindowProbe is the served-window
	// read that closes admission (register S-24 — it used to run on the wall).
	PhaseColdLoad       = "cold-load"
	PhaseCoherenceProbe = "coherence-probe"
	PhaseWindowProbe    = "window-probe"
	// PhaseRunning is the planner loop; PhaseFinal the forced final step;
	// PhaseRepack the structured re-pack.
	PhaseRunning = "running"
	PhaseFinal   = "final"
	PhaseRepack  = "repack"
)

PhaseAdmission … PhaseRepack are Run.Phase's values. They are a shared vocabulary, not one package's private strings: internal/pipeline WRITES the phase, this package HEALS the pre-run ones on the first step, and internal/fleetnode COUNTS the admission ones for health's `jobs_admitting`. Three copies of a bare literal across three packages is a rename that silently zeroes a published counter, so the name lives here, beside the field.

View Source
const (
	VerdictFree        = "free"         // no lease, seat idle or absent, cards quiet
	VerdictLoadedIdle  = "loaded-idle"  // no lease; the seat is resident with nothing in flight (unloads at its ttl)
	VerdictWorking     = "working"      // a request or a registered run is in flight on the seat
	VerdictHeldWorking = "held-working" // a lease is held and the cards are busy under it (the holder's own job)
	VerdictHeldIdle    = "held-idle"    // a lease is held and NOTHING is running: seat idle, cards quiet
	VerdictBusyOutside = "busy-outside" // no lease, seat idle, but the cards are busy — work the harness does not own
	VerdictStaleHolder = "stale-holder" // a lease record whose holder is gone; the next acquirer reclaims it
	// Standing verdicts (plan P8). Highest precedence first: stale-holder, tree-orphan,
	// held-stalled, held-orphaned, held-overdue, then held-working and held-idle.
	VerdictTreeOrphan   = "tree-orphan"   // the wrapper is gone but its job tree is alive and keeps the cards
	VerdictHeldStalled  = "held-stalled"  // a progress contract exists and its file did not move inside its window
	VerdictHeldOrphaned = "held-orphaned" // an attended lease whose owner has been gone past the grace
	VerdictHeldOverdue  = "held-overdue"  // the declared window ended and the holder still holds the cards

)

Verdict vocabulary.

View Source
const (
	// FaultWindowMax is the longest window `gpu faults` reads.
	FaultWindowMax = 30 * 24 * time.Hour
)
View Source
const KindVision = "vision"

KindVision is Run.Kind for ONE single-shot vision call (vqa, ocr, assess_image, a video_describe window) while it is on its seat, whatever door it came through. Those calls hold no lease, so before they registered a script that looped one CLI call per image kept a vision seat busy for hours while every status surface read the box as idle (2026-10-28). A vision record carries no Devices: the run-cap line of a seat pinned to one card counts every record pinned to that card as holding a slot, and a vision call must not take an agent contract's slot. Readers that need its cards resolve them from the seat (gpualloc.LeaseScope.TouchesRun). internal/fleetnode counts it for health's `vision_calls_running`, so the name lives here.

Variables

View Source
var ErrCardTableUnreadable = errors.New("the card table could not be read")

ErrCardTableUnreadable marks a read whose events could not be placed on cards because the card table (the second nvidia-smi query) could not be read: the events are returned, unplaced, with this error wrapped in the reason.

View Source
var ErrNoDriverEventSource = errors.New("gpuactivity: no driver event source on this OS")

ErrNoDriverEventSource says this OS has no driver-event source: the snapshot treats it as "off", with no key and no note.

Functions

func Assess

func Assess(v View) (verdict, note string)

Assess derives the verdict from a View's readings. Pure, so the vocabulary is testable without a lease, a seat or a driver.

func CardsReadingOf

func CardsReadingOf(gpus []GPU, devices []string) gpulease.CardsReading

CardsReadingOf is the look at a lease's cards the term check takes (gpulease.TermSignals.Cards): any card of the lease, or any card at all for a whole-node lease (devices empty), at or above the verdict's busy threshold is CardsWorking. The display card is skipped (its load is the desktop's, never the lease's). Otherwise the cards are CardsIdle only when every card the lease is judged by was actually read and found quiet; a card whose utilisation is N/A, a lease card the sample does not list, and a sample with no card to judge by at all are CardsUnreadable, because an unknown must never read as idle. devices are lease ids (lower-case GPU uuids).

func ClassOf

func ClassOf(e DriverEvent) string

ClassOf is the class string of an event ("nvlddmkm 153"), without the table lookup.

func DirBeside

func DirBeside(leaseDir string) string

DirBeside is the registry directory for a lease directory: `<root>/gpu/activity` next to `<root>/gpu/lease`. Deriving it from the lease directory — not from a second resolution of the state root — is what keeps the two from ever pointing at different roots.

func FaultStorePath

func FaultStorePath(stateDir string) (string, error)

FaultStorePath is the retention file under the machine's state root (config state_dir).

func FaultSummaryPath

func FaultSummaryPath(stateDir string) (string, error)

FaultSummaryPath is the summary file under the machine's state root.

func HeadlineOf

func HeadlineOf(info gpulease.Info, h *Holder) gpulease.Info

HeadlineOf returns the record of the lease the verdict is about (the Holder) from an inspection of the live leases: Info itself describes only the lowest epoch, so a surface that prints a lease's owner, progress contract or takeover command beside the verdict reads it here and never from the lowest. info itself when there is one lease or the holder is not among them.

func ParseBusTable

func ParseBusTable(out string) map[string]BusCard

ParseBusTable parses `nvidia-smi --query-gpu=index,uuid,pci.bus_id --format=csv,noheader` rows into a table keyed by the lower-case "bus:device" an event names ("b5:00"). Rows that do not parse are skipped.

func ParsePMLines

func ParsePMLines(raw string) []roledEvent

ParsePMLines reads the kernel's suspend and hibernation lines (`journalctl -o short-unix`): entry opens a sleep, exit closes it. Other lines (the "-- Boot ... --" separators) are skipped.

func RecordIncidents

func RecordIncidents(path string, rep FaultReport, retained []Incident, now time.Time) (int, error)

RecordIncidents appends the report's incidents that were read from the log, have ended (no record for longer than a burst gap and a minute, so a burst still running is not cut in two), and overlap no retained one. It returns how many it appended. One writer only: fleet-serve's refresh.

func UtilWorking

func UtilWorking(gpus []GPU, devices []string) bool

UtilWorking reports whether a lease's cards are busy: CardsReadingOf is CardsWorking. An unknown reading is not work, and neither is no reading.

func WriteSummary

func WriteSummary(path string, s FaultSummary) error

WriteSummary writes the summary file whole: a temp file beside it, then a rename, so a reader never sees half.

Types

type BusCard

type BusCard struct {
	Index int
	UUID  string
}

BusCard is one row of the PCI bus table: the card at a bus and device.

type ClassCount

type ClassCount struct {
	Class string `json:"class"`
	Count int    `json:"count"`
}

ClassCount is how many records of one class.

type ContextEvent

type ContextEvent struct {
	At     time.Time `json:"at"`
	Kind   string    `json:"kind"`
	Source string    `json:"source"`
	ID     int       `json:"id,omitempty"`
}

ContextEvent is one restart or sleep transition the OS logged. No message text is kept: a restart record names the machine and the user that asked for it.

func ParseBootList

func ParseBootList(raw string) ([]ContextEvent, error)

ParseBootList reads `journalctl --list-boots -o json`: each boot's first entry is a restart point.

type DisplayCardProcs

type DisplayCardProcs struct {
	Index   int    `json:"index"`
	GPUUUID string `json:"gpu_uuid,omitempty"`
	Name    string `json:"name"`
	Count   int    `json:"count"`
}

DisplayCardProcs is the one summary that stands in for the processes nvidia-smi lists on a display card and cannot size. On Windows (WDDM) that is the whole desktop: explorer, every browser, the chat apps, 31 rows on the reference 3-card box, each used_known=false. Listed one by one they buried the single process that mattered (a python on a work card) in the lease view an agent reads first (F18, 2026-10-09), and they say nothing about the lease. Counted per card instead; the complete list is nvidia-smi's own (docs/systems/gpu-lease.md).

func (DisplayCardProcs) Sentence

func (d DisplayCardProcs) Sentence() string

Sentence is the summary as `gpu status` prints it.

type DriverEvent

type DriverEvent struct {
	// At is when the driver logged it (zero when the log line carried no readable time).
	At time.Time `json:"at"`
	// Source is "nvlddmkm" (the Windows System log provider) or "Xid" (the Linux kernel log's NVRM Xid line).
	Source string `json:"source"`
	// ID is the Windows event id or the Xid code.
	ID int `json:"id"`
	// Bus is the card's PCI bus and device the event names, lower-case ("b5:00"); "" when the event names none.
	Bus string `json:"bus,omitempty"`
	// Card is the nvidia-smi index of the card the bus belongs to, and UUID its uuid; UUID is "" when the event could
	// not be placed on a card (then Card means nothing).
	Card int    `json:"card"`
	UUID string `json:"uuid,omitempty"`
	// Text is the driver's message, without the Windows device object path.
	Text string `json:"text,omitempty"`
}

DriverEvent is one event the NVIDIA driver logged.

func AttributeEvents

func AttributeEvents(evs []DriverEvent, table map[string]BusCard) []DriverEvent

AttributeEvents names the card behind each event's bus. An event whose bus the table does not list, or that names none, stays unplaced (UUID ""). The input is not changed.

func ParseKernelLog

func ParseKernelLog(out string) []DriverEvent

ParseKernelLog reads the NVRM Xid lines out of a kernel log: `journalctl -k -o short-unix` lines (a unix time first) or `dmesg --time-format iso` lines (an ISO time first). Other lines are ignored; a line whose time cannot be read keeps a zero At.

func ParseWinEvents

func ParseWinEvents(out string) ([]DriverEvent, error)

ParseWinEvents parses the XML records the Windows reader prints: a sequence of <Event> elements, not one document. A stretch that is not XML ends the read with the events parsed so far and an error. The record's own host name, user and device object path are not carried: only the provider, id, time and message.

func ReadDriverEvents

func ReadDriverEvents(ctx context.Context) ([]DriverEvent, error)

ReadDriverEvents is the production reader behind Options.DriverEvents: this machine's recent driver fault events, each placed on its card when the card table allows. Cached for 60 s in this process (a failure included), so a poll of a long-lived process (the MCP server) starts no child per call; an answer that could not place its events because the card table was unreadable is cached for 10 s only. The cache lives in process memory: every `gpu status` is a fresh process and pays one read. ErrNoDriverEventSource means this OS has no source.

func (DriverEvent) Line

func (e DriverEvent) Line() string

Line is the one-line rendering `gpu status` prints.

type FaultCard

type FaultCard struct {
	Index int    `json:"index"`
	UUID  string `json:"uuid"`
	Bus   string `json:"bus"`
	Name  string `json:"name,omitempty"`
	// RecoveryAction is nvidia-smi's gpu_recovery_action ("None" = nothing pending); "" when the driver does not
	// report it.
	RecoveryAction string `json:"recovery_action,omitempty"`
	// Events counts the records placed on this card, ByClass splits them, Incidents counts the bursts that name it.
	Events    int          `json:"events"`
	ByClass   []ClassCount `json:"by_class,omitempty"`
	Incidents int          `json:"incidents"`
	// InContext counts the incidents naming it that fell at a restart or a sleep transition (faultcontext.go).
	InContext int       `json:"in_context,omitempty"`
	Last      time.Time `json:"last,omitzero"`
}

FaultCard is one card of the table with its faults in the window.

func ParseFaultCards

func ParseFaultCards(out string) []FaultCard

ParseFaultCards parses the card rows readFaultCards asks for (the recovery-action column optional). Rows that do not parse are skipped.

type FaultReport

type FaultReport struct {
	Since      time.Time `json:"since"`
	Until      time.Time `json:"until"`
	WindowDays int       `json:"window_days"`
	// Events counts the driver records in the window; Untimed those whose time could not be read (not grouped).
	Events     int               `json:"events"`
	Untimed    int               `json:"untimed,omitempty"`
	Cards      []FaultCard       `json:"cards"`
	Incidents  []Incident        `json:"incidents"`
	Repeats    []Repeat          `json:"repeats,omitempty"`
	Known      []KnownError      `json:"known_errors"`
	LiveKernel []LiveKernelEvent `json:"live_kernel_events,omitempty"`
	// Retained counts the incidents added from the retention file.
	Retained int      `json:"retained,omitempty"`
	Notes    []string `json:"notes,omitempty"`
}

FaultReport is what `gpu faults` shows.

func ReadFaults

func ReadFaults(ctx context.Context, window time.Duration) (FaultReport, error)

ReadFaults reads this machine's driver fault history for the window (capped at FaultWindowMax). Uncached: each call reads the logs. ErrNoDriverEventSource means this OS has no source; a read that is short says so in Notes.

func ReadFaultsRetained

func ReadFaultsRetained(ctx context.Context, window time.Duration, retained []Incident) (FaultReport, error)

ReadFaultsRetained is ReadFaults with the retained incidents (FaultStore.Load) merged in: one that overlaps no incident read from the OS log is added, marked Retained, and counts like the others.

type FaultSummary

type FaultSummary struct {
	WindowDays int                  `json:"window_days"`
	ReadAt     time.Time            `json:"read_at"`
	Cards      []FaultSummaryCard   `json:"cards"`
	Repeats    []FaultSummaryRepeat `json:"repeats,omitempty"`
	// Note says why the reading may be short (a log read that stopped, a card table that could not be read).
	Note string `json:"note,omitempty"`
}

FaultSummary is the per-card fault reading a fleet node publishes (gpu_faults on /fleet/health).

func ReadSummary

func ReadSummary(path string) (*FaultSummary, error)

ReadSummary reads the summary file fleet-serve wrote. A missing file is (nil, nil): no reading, not "no faults".

func Summarize

func Summarize(rep FaultReport, now time.Time) FaultSummary

Summarize reduces a report to the summary, read at now.

type FaultSummaryCard

type FaultSummaryCard struct {
	Index int    `json:"index"`
	UUID  string `json:"uuid"`
	Bus   string `json:"bus"`
	// Events and Incidents count every record and burst naming the card; InContext the bursts at a restart or sleep
	// transition among them. Incidents24h counts the bursts outside one that started in the last 24 h, and
	// LastIncident is when the newest of those ended.
	Events       int       `json:"events"`
	Incidents    int       `json:"incidents"`
	InContext    int       `json:"in_context,omitempty"`
	Incidents24h int       `json:"incidents_24h"`
	LastIncident time.Time `json:"last_incident,omitzero"`
}

FaultSummaryCard is one card's counts over the window.

type FaultSummaryRepeat

type FaultSummaryRepeat struct {
	UUID   string    `json:"uuid,omitempty"`
	Bus    string    `json:"bus"`
	Class  string    `json:"class"`
	Bursts int       `json:"bursts"`
	From   time.Time `json:"from"`
	To     time.Time `json:"to"`
}

FaultSummaryRepeat is NVSentinel's repeat rule met on one card: one class in 5 or more bursts within 24 h, From to To being the first and last of those bursts.

type GPU

type GPU struct {
	Index       int    `json:"index"`
	UUID        string `json:"uuid,omitempty"`
	Name        string `json:"name"`
	UtilPct     int    `json:"util_pct"`
	UtilKnown   bool   `json:"util_known"`
	MemUsedMiB  int    `json:"mem_used_mib"`
	MemTotalMiB int    `json:"mem_total_mib"`
	// DisplayActive is nvidia-smi's display_active: this card drives a screen,
	// so its utilization is never a lease holder's work — see
	// gpuprobe.DisplayCardUUIDs, the load-attribution rule every load surface reads.
	DisplayActive bool `json:"display_active,omitempty"`
	// DisplayAttached is nvidia-smi's display_attached: a monitor is plugged into this
	// card. It holds with the screen asleep, when display_active reads Disabled on every
	// card, so the card table reads it to keep the allocator off the monitor's card
	// (gpuprobe.ScreenCardUUIDs). The verdict's load attribution does NOT: an attached
	// monitor is not a display in use.
	DisplayAttached bool `json:"display_attached,omitempty"`
	// AttachedUnknown marks a sample whose full query failed for a reason that does not name display_attached
	// (gpuprobe.AttachedUnknown): it cannot say which card the monitor is on. Carried so the per-card table of
	// offload_status can say so instead of showing no display card.
	AttachedUnknown bool `json:"attached_unknown,omitempty"`
}

GPU is one card as nvidia-smi reports it at the moment of the sample.

func ParseGPUs

func ParseGPUs(out string) []GPU

ParseGPUs parses `index, uuid, name, utilization.gpu, memory.used, memory.total` rows. Rows that do not parse are skipped; `[N/A]` utilization is kept as unknown rather than zero (an unknown must never read as idle).

func SampleGPUs

func SampleGPUs(ctx context.Context) ([]GPU, error)

SampleGPUs queries every card's utilization and memory. An absent or failing nvidia-smi is an error the caller reports, never a row of zeros.

type GPUProcess

type GPUProcess struct {
	PID       int    `json:"pid"`
	Name      string `json:"name"`
	UsedMiB   int    `json:"used_mib,omitempty"`
	UsedKnown bool   `json:"used_known"`
	GPUUUID   string `json:"gpu_uuid,omitempty"`
}

GPUProcess is one process nvidia-smi lists on a card. On Windows (WDDM) the per-process memory is `[N/A]`; UsedKnown says so instead of reporting 0.

func ParseProcesses

func ParseProcesses(out string) []GPUProcess

ParseProcesses parses `pid, used_memory, gpu_uuid, process_name` rows.

func SampleProcesses

func SampleProcesses(ctx context.Context) ([]GPUProcess, error)

SampleProcesses lists the processes holding GPU memory.

type Handle

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

Handle is one live registration. Every method is safe on a nil *Handle, so a launcher that could not open the registry keeps running unchanged.

func Start

func Start(lockOverride, stateDir string, run Run) *Handle

Start is Begin for launchers: it resolves the registry from the box config's two lease fields, logs once when it cannot, and never fails the run — a nil handle is a no-op.

func (*Handle) End

func (h *Handle) End()

End removes the record and stops the heartbeat. Idempotent.

The delete is retried like write()'s rename: on Windows it fails with a sharing violation while a reader (a drain, a status call) has the record open, and an ignored failure left the run registered with its heartbeat stopped until HeartbeatTTL aged it out, so a drain waited on a run that had ended (register C-84).

func (*Handle) ID

func (h *Handle) ID() string

Run is a copy of the current record. ID is the run's registry id ("" for a nil handle): what a reader passes to exclude its own record from a count.

func (*Handle) OnAllowance

func (h *Handle) OnAllowance(phase string, allowance time.Duration)

OnAllowance implements the agent loop's RunObserver (0.131.0): the liveness phase and the stall bound the run is under. A phase change is progress.

func (*Handle) OnPhase

func (h *Handle) OnPhase(p string)

OnPhase implements the agent loop's RunObserver.

func (*Handle) OnProgress

func (h *Handle) OnProgress(tokensOut int)

OnProgress implements the agent loop's RunObserver (0.131.0): a streamed delta with the run's token total. The decode rate is an EWMA over deltas.

func (*Handle) OnStep

func (h *Handle) OnStep(step, tokensOut int)

OnStep implements the agent loop's RunObserver: the step just completed and the tokens the seat has generated for this run so far.

func (*Handle) Phase

func (h *Handle) Phase(p string)

Phase records where the run is.

func (*Handle) Run

func (h *Handle) Run() Run

func (*Handle) Update

func (h *Handle) Update(fn func(*Run))

Update mutates the record under the lock and writes it.

type Holder

type Holder struct {
	// Devices are the cards the lease sits on as seats read it (lease ids): the declared
	// devices, else the inferred ones; empty = the whole node.
	Devices   []string `json:"devices,omitempty"`
	PID       int      `json:"pid"`
	Alive     bool     `json:"alive"`
	Class     string   `json:"class"`
	Epoch     uint64   `json:"epoch"`
	Reason    string   `json:"reason,omitempty"`
	Origin    string   `json:"origin,omitempty"`
	Command   string   `json:"command,omitempty"`
	Exclusive bool     `json:"exclusive"`
	Draining  bool     `json:"draining"`
	// GaveUpAt/GaveUpWhy: the moment the lease's hidden holder gave up releasing it, and why (the record's holder_gave_up_*). Set for
	// a stale record only: the holder wrote it and exited, and nothing else says the release failed.
	GaveUpAt        time.Time `json:"holder_gave_up_at,omitzero"`
	GaveUpWhy       string    `json:"holder_gave_up_why,omitempty"`
	AgeSec          int       `json:"age_s"`
	HeartbeatAgeSec int       `json:"heartbeat_age_s"`
	ExpiresAt       time.Time `json:"-"`

	// --- ownership and standing (plan P8): derived by gpulease.Standing, never stored. ---
	Unattended    bool   `json:"unattended,omitempty"`
	OwnerState    string `json:"owner_state,omitempty"` // alive | gone | unknown | remote
	OwnerSession  string `json:"owner_session,omitempty"`
	OwnerPID      int    `json:"owner_pid,omitempty"`
	OrphanGraceS  int    `json:"orphan_grace_s,omitempty"`
	OrphanedSince string `json:"orphaned_since,omitempty"` // RFC3339, when the owner was first seen gone
	OrphanedForS  int    `json:"orphaned_for_s,omitempty"`
	Orphaned      bool   `json:"orphaned,omitempty"`
	Overdue       bool   `json:"overdue,omitempty"`
	OverdueBySec  int    `json:"overdue_by_s,omitempty"`
	Stalled       bool   `json:"stalled,omitempty"`
	// OwnerNote says why a RECORDED owner cannot be told apart (the session was never in the
	// registry, or the registry could not be read); OrphanMarkErr says the moment the owner
	// was first seen gone could not be recorded.
	OwnerNote     string         `json:"owner_note,omitempty"`
	OrphanMarkErr string         `json:"orphan_marker_error,omitempty"`
	TreeOrphan    bool           `json:"tree_orphan,omitempty"`
	TreePIDs      []int          `json:"tree_pids,omitempty"`
	TreeWhy       string         `json:"tree_why,omitempty"`
	Progress      *ProgressState `json:"progress,omitempty"`
	// Facts are information about a lease that has no owner and no progress contract
	// (newest ComfyUI output, ComfyUI log): never an input to the verdict.
	Facts []string `json:"activity_facts,omitempty"`

	// Terms (plan P9), from the lease record. Expired is the label the holder's tick stamped
	// when the term ended unrenewed; ExpiredWhy is its sentence. TermSec is the renewal term,
	// RequestedSec the window asked for when that was above the cap on a term, HardEnd (RFC3339)
	// the instant after which the lease is no longer renewed.
	Expired      bool   `json:"expired,omitempty"`
	ExpiredWhy   string `json:"expired_why,omitempty"`
	TermSec      int    `json:"term_s,omitempty"`
	RequestedSec int    `json:"requested_s,omitempty"`
	HardEnd      string `json:"hard_end,omitempty"`

	// The yield request (plan P11, ADR 0086), read from the lease record and its yield sidecar by
	// gpulease.YieldViewOf and never stored as a verdict. YieldFile is the path of the sidecar of a
	// lease whose holder runs the request (it exists only once the holder was asked; a detached job
	// can watch it), named while the policy is request or once the holder was asked and absent under
	// the default policy; YieldNote is the sentence a waiter reads, empty when there is nothing to say;
	// Yield is present only once the holder was asked. Under the default policy a lease nobody asked
	// carries none of the three, so a consumer of the holder reads the bytes it read before.
	YieldFile string      `json:"yield_file,omitempty"`
	YieldNote string      `json:"yield_note,omitempty"`
	Yield     *YieldState `json:"yield,omitempty"`
}

Holder describes the lease holder beyond the lease record.

func (*Holder) StandingWord

func (h *Holder) StandingWord() string

StandingWord is the standing verdict word the holder carries, in the precedence the verdicts outrank each other (tree-orphan, held-stalled, held-orphaned, held-overdue), or "" for a lease that is healthy. It is the word a surface leads with even when the SEAT's own verdict is `working` (work in flight outranks the standing verdicts but must not hide them).

type Incident

type Incident struct {
	Start   time.Time      `json:"start"`
	End     time.Time      `json:"end"`
	Events  int            `json:"events"`
	Cards   []IncidentCard `json:"cards"`
	Classes []ClassCount   `json:"classes"`
	// Unplaced counts the burst's records that name no card (Windows id 13 names none).
	Unplaced int `json:"unplaced"`
	// Units is how many GPC/TPC units the burst's graphics exceptions name, and Reading NVIDIA's Xid 13 workflow
	// applied to them ("" when fewer than two records name a unit).
	Units   int    `json:"units,omitempty"`
	Reading string `json:"reading,omitempty"`
	// LiveKernel are the live kernel dumps whose time falls in the burst (a minute before it to two after).
	LiveKernel []LiveKernelEvent `json:"live_kernel,omitempty"`
	// Context is "restart" or "sleep-wake" when the burst fell at one (faultcontext.go): listed, but not counted
	// towards a repeat. ContextEvents are the OS records that placed it there.
	Context       string         `json:"context,omitempty"`
	ContextEvents []ContextEvent `json:"context_events,omitempty"`
	// Retained marks an incident read from the retention file (faultstore.go) because the OS log no longer holds it.
	Retained bool `json:"retained,omitempty"`
}

Incident is one burst of driver records.

func LoadRetained

func LoadRetained(path string) (incs []Incident, bad int, err error)

LoadRetained reads the retained incidents. A missing file is none; a line that does not parse is skipped and counted in bad.

type IncidentCard

type IncidentCard struct {
	Index  int    `json:"index"`
	UUID   string `json:"uuid,omitempty"`
	Bus    string `json:"bus"`
	Events int    `json:"events"`
	// Classes splits the card's records in the burst: the repeat rule counts per card and class, and a retained
	// incident keeps no records.
	Classes []ClassCount `json:"classes,omitempty"`
}

IncidentCard is a card a burst's records name: the table's index and uuid, or Index -1 and no uuid when the bus is not in today's table.

type KnownError

type KnownError struct {
	// Class names the event: "Xid 79", "nvlddmkm 153", "LiveKernelEvent 141".
	Class string `json:"class"`
	// Name is the short name: NVIDIA's mnemonic, or the bug check name.
	Name string `json:"name"`
	// Meaning says what happened, in the source's words where it has them.
	Meaning string `json:"meaning"`
	// Domain is where the fault sits: app, card, driver, display, link, system or unknown.
	Domain string `json:"domain"`
	// Severity is info, warn or fault.
	Severity string `json:"severity"`
	// NVIDIAAction and NVIDIAInvestigate are the catalog's immediate and investigatory resolution buckets
	// (NVIDIA's datacenter guidance), and NVIDIAActionMeaning the immediate bucket in NVIDIA's words.
	NVIDIAAction        string `json:"nvidia_action,omitempty"`
	NVIDIAActionMeaning string `json:"nvidia_action_meaning,omitempty"`
	NVIDIAInvestigate   string `json:"nvidia_investigate,omitempty"`
	// XidAnalogue is the Linux Xid a Windows event is read as (0 = none).
	XidAnalogue int `json:"xid_analogue,omitempty"`
	// Basis is how the class was reached: "nvidia-catalog" (the Xid's own row), "observed" (a Windows event read
	// by its message: NVIDIA publishes no Windows table), "microsoft-bugcheck" (a documented bug check name),
	// "user-reports" (a name only forum reports give) or "unknown".
	Basis string `json:"basis"`
}

KnownError is what a fault event is, as far as a table can say, and how sure the table is.

func ClassifyEvent

func ClassifyEvent(e DriverEvent) KnownError

ClassifyEvent reads one driver event as a known error.

func ClassifyLiveKernel

func ClassifyLiveKernel(code string) KnownError

ClassifyLiveKernel reads a LiveKernelEvent's bug check code (P1, hex without 0x, any case).

type LiveKernelEvent

type LiveKernelEvent struct {
	// At is the fault time: from the dump's file name (AtSource "dump-name", local minute) or, with no dump file,
	// the first time WER queued the report (AtSource "report-queue", which can be days late).
	At       time.Time `json:"at"`
	AtSource string    `json:"at_source"`
	Code     string    `json:"code"`
	// Dump is the dump's folder and file under LiveKernelReports; Reports how many WER records carried it.
	Dump    string `json:"dump,omitempty"`
	Reports int    `json:"reports"`
	Name    string `json:"name"`
}

LiveKernelEvent is one live kernel dump Windows Error Reporting filed.

func ParseLiveKernelEvents

func ParseLiveKernelEvents(out string, loc *time.Location) ([]LiveKernelEvent, error)

ParseLiveKernelEvents parses WER records into one LiveKernelEvent per dump file (a report with no dump file is one per report id), with the fault time read from the dump's name in loc. Records that are not LiveKernelEvent are skipped; a stretch that is not XML ends the read with what was parsed and an error.

type Options

type Options struct {
	LockOverride string // config gpu_lock_path
	StateDir     string // config state_dir
	Endpoint     string // llama-swap base; "" = do not read the seat
	Seat         string // the agent seat (id or alias); "" = do not read the seat
	// SeatTimeout bounds the seat read. A status call must never hang on a seat
	// that is loading (llama-swap holds /upstream/<seat>/… for the whole load):
	// seatload reports `Starting` without touching the upstream, and this bound
	// covers a slow /running. Zero = 3 s.
	SeatTimeout time.Duration
	// SampleGPU runs nvidia-smi for utilization/memory and the processes on the
	// cards. Off in tests and where the box has no NVIDIA driver.
	SampleGPU bool
	// Sampler overrides how the cards are read when SampleGPU is true. Nil (the
	// production default) means the real SampleGPUs (nvidia-smi). A caller one
	// package up from gpuactivity cannot reach the package-private smiRun seam
	// (internal/gpuactivity/smi.go) to fake specific per-card numbers, so this
	// field is the seam at the Options boundary: it lets a verdict test (held vs
	// held-idle vs held-working depends on the ACTUAL util numbers, not just
	// on/off) inject idle or busy cards without touching the real driver. See
	// internal/mcpserver's statusGPUSampler var for how offload_status wires it.
	Sampler func(ctx context.Context) ([]GPU, error)
	// ProcSampler overrides how the processes on the cards are listed when SampleGPU is true. Nil
	// (the production default) means SampleProcesses (nvidia-smi --query-compute-apps). The same
	// seam as Sampler, for the same reason: how a display card's desktop is folded
	// (View.splitProcesses) is only testable through a status call with process rows of its own.
	ProcSampler func(ctx context.Context) ([]GPUProcess, error)
	// Scope fills in the effective cards of a legacy whole-node lease (the evidence rule lives
	// in modelaffinity, which imports this package, so the caller hands it in). nil = the
	// lease's declared devices only.
	Scope func(gpulease.Info) gpulease.Info
	// OrphanGrace is how long an attended lease's owner may be gone before the lease
	// reads as orphaned (config gpu_orphan_grace_min). Zero = gpulease.DefaultOrphanGrace.
	OrphanGrace time.Duration
	// ComfyDir is the ComfyUI install, read for the activity facts of a lease that has no
	// owner and no progress contract. "" = none.
	ComfyDir string
	// DriverEvents reads the driver's recent fault events (nvlddmkm on Windows, NVRM Xid on Linux), already
	// attributed to cards (ReadDriverEvents is the production reader). nil = off: a box that wires none prints
	// byte-identically to before. Read only while a lease is held and the GPU sample is on, and shown as facts, never
	// as a verdict input.
	DriverEvents func(ctx context.Context) ([]DriverEvent, error)
}

Options select what one Snapshot reads.

type ProgressState

type ProgressState struct {
	File     string `json:"file"`
	State    string `json:"state"` // advancing | stalled | unknown
	AgeSec   int    `json:"age_s"`
	StallSec int    `json:"stall_s"`
	Detail   string `json:"detail,omitempty"`
	// Problem says why an unknown state is unknown ("does not exist", "cannot be read: ...").
	Problem string `json:"problem,omitempty"`
}

ProgressState is the reading of a lease's progress contract.

func (*ProgressState) UnknownWhy

func (p *ProgressState) UnknownWhy() string

UnknownWhy is unknownWhy for the status lines the CLI prints; "" unless the state is unknown.

type Registry

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

Registry is the directory of live run records.

func Open

func Open(lockOverride, stateDir string) (*Registry, error)

Open resolves the registry the same way every lease consumer resolves the lease (gpulease.LeaseDir: gpu_lock_path, then state_dir, then the platform default), refusing the same cloud-synced roots.

func OpenAt

func OpenAt(dir string) *Registry

OpenAt binds a registry to an explicit directory (tests; readers handed the lease directory by another resolver).

func (*Registry) Begin

func (r *Registry) Begin(run Run) (*Handle, error)

Begin registers a run and starts its heartbeat. The record carries this process's pid and start time; Seat, Kind, Origin, Goal, MaxSteps and Phase come from the caller. Every run gets its own id and its own record, however many begin in the same clock tick.

func (*Registry) Dir

func (r *Registry) Dir() string

Dir is the registry directory.

func (*Registry) List

func (r *Registry) List(now time.Time) []Run

List returns every LIVE run, oldest first, and sweeps the stale records it finds on the way (a dead or recycled pid, or a heartbeat past HeartbeatTTL). An unreadable directory is an empty list: the registry is advisory.

func (*Registry) OnSeat

func (r *Registry) OnSeat(now time.Time, names ...string) []Run

OnSeat is List filtered to the runs on any of the named seats (id or alias, case-insensitive) — the drain asks for the configured name and the roster's canonical id together.

func (*Registry) OnSeatPinned

func (r *Registry) OnSeatPinned(now time.Time, pins []string, names ...string) []Run

OnSeatPinned is OnSeat for a seat whose pins are known (plan P5). A seat pinned to ONE card shares that card with every other seat on it, so its line is the card's: the runs on the named seats plus every run recorded against the same pin. A seat that spans cards, or whose pin is unknown, keeps the per-seat line (OnSeat): counting by card there would mix lines that do not contend.

func (*Registry) Where

func (r *Registry) Where(now time.Time, pred func(Run) bool) []Run

Where is List filtered by a predicate: the runs a drain or a cap reads when the question is not "which seat" but "which cards".

type Repeat

type Repeat struct {
	Card   int       `json:"card"`
	UUID   string    `json:"uuid,omitempty"`
	Bus    string    `json:"bus"`
	Class  string    `json:"class"`
	Bursts int       `json:"bursts"`
	From   time.Time `json:"from"`
	To     time.Time `json:"to"`
}

Repeat is NVSentinel's RepeatedXIDErrorOnSameGPU rule met: one class in at least 5 bursts on one card in 24 h.

type Run

type Run struct {
	// ID is unique per run within a process whatever the clock does (see runID) and is the record's
	// file name. Readers compare it for equality ("is this my own record") and, in one place, as a
	// string to break a same-millisecond tie in the seat's line; nothing parses it.
	ID          string `json:"id"`
	PID         int    `json:"pid"`
	StartTimeMs int64  `json:"start_time_ms,omitempty"` // the process's start time (pid-recycling guard, as the lease)
	Seat        string `json:"seat"`
	// Kind names the door the run came through: "agent_run" (the MCP tool),
	// "contract" (a delegation contract run by this node — a local spread leg or
	// a fleet job), "lab" (the CLI replay gate), KindVision (one vision call).
	Kind        string `json:"kind"`
	Origin      string `json:"origin,omitempty"` // who asked: node id, job id, host
	Goal        string `json:"goal,omitempty"`   // the first goalClip characters
	StartedAtMs int64  `json:"started_at_ms"`
	// Phase is where the run is, spelled by the Phase* constants above:
	// "admission" (waiting for the endpoint to settle), "cold-load" (the seat is
	// loading for it), "running" (planner steps), "final" (the forced final
	// step), "repack" (the structured re-pack). Use the constants — health's
	// `jobs_admitting` counts one of these values across a package boundary.
	Phase       string `json:"phase"`
	Step        int    `json:"step,omitempty"`
	MaxSteps    int    `json:"max_steps,omitempty"`
	TokensOut   int    `json:"tokens_out,omitempty"`
	HeartbeatMs int64  `json:"heartbeat_ms"`
	// Job liveness (0.131.0, liveness walls) — DISTINCT from HeartbeatMs, which
	// is the holder PROCESS ticking (register C-32: a hung job with a live
	// holder used to look healthy). LastProgressMs is the last streamed delta,
	// tool call or phase change; TokS the smoothed decode rate over deltas;
	// LivePhase/AllowanceMs the stall bound the run is under right now.
	// Devices are the pins of the seat the run is on (the layer seat's device, PCI-order
	// indices or UUID prefixes), recorded when the run starts. Empty = no pin known (a
	// record from a build that predates the field, or a seat nobody declared a pin for).
	Devices        []string `json:"devices,omitempty"`
	LastProgressMs int64    `json:"last_progress_ms,omitempty"`
	TokS           float64  `json:"tok_s,omitempty"`
	LivePhase      string   `json:"live_phase,omitempty"`
	AllowanceMs    int64    `json:"allowance_ms,omitempty"`
}

Run is one registered run on a seat: the harness's unit of work.

func (Run) Age

func (r Run) Age(now time.Time) time.Duration

Age is how long the run has been in flight.

func (Run) Liveness

func (r Run) Liveness(now time.Time) string

Liveness is the one-line reading of a run's job liveness, shared by every status renderer so they cannot drift: "producing 3.4 tok/s, last token 2s ago (allowed 60s in decoding)", "silent 187s of 214s allowed in prefill", or "" when the run never reported progress (a pre-0.131.0 node).

func (Run) OnPin

func (r Run) OnPin(pin string) bool

OnPin reports whether the run's seat is pinned to the card pin names (the same pin space the run recorded: a layer seat's device, an index or a UUID prefix).

func (Run) Summary

func (r Run) Summary(now time.Time) string

Summary is the one-line human form used by the drain and `gpu status`.

type SeatState

type SeatState struct {
	Name      string `json:"name"`
	Canonical string `json:"canonical,omitempty"`
	Loaded    bool   `json:"loaded"`
	Starting  bool   `json:"starting"`
	Stopping  bool   `json:"stopping,omitempty"`
	Inflight  int    `json:"inflight"`
	Source    string `json:"source,omitempty"`
	Err       string `json:"error,omitempty"`
}

SeatState is what llama-swap and the engine say about the agent seat.

type View

type View struct {
	At     time.Time
	Held   bool
	Stale  bool // a lease record exists but its holder is provably gone or silent past its window
	Holder *Holder
	// Leases lists every live lease when MORE THAN ONE is held (card-scoped leases), each
	// with its own standing; Holder is the one the verdict is about (the most escalated).
	Leases    []Holder
	Seat      SeatState
	Runs      []Run
	GPUs      []GPU
	Processes []GPUProcess
	GPUErr    string
	// Verdict is one word a session can branch on; Note is the sentence behind
	// it. See Assess for the vocabulary.
	Verdict string
	Note    string
	// OtherDevices are the cards every OTHER live lease sits on (lease ids): work on them is
	// not the primary lease's holder's.
	OtherDevices []string

	// DriverEvents are the driver's recent fault events on the LEASED cards, newest first (C-83-B). Facts, never a
	// verdict input: a fault and a kill look alike in the log, and telling them apart takes A-128's kill test.
	DriverEvents []DriverEvent
	// DriverEventsTotal is how many events the leased cards had before the list was capped (0 = not capped).
	DriverEventsTotal int
	// DriverEventsUnattributed counts the events in the window that name no card this box can place, so they are in
	// no card's list: said, so an empty list is not read as "no faults".
	DriverEventsUnattributed int
	// DriverEventsNote says why the events could not be read (a reader failure is a note, never an error).
	DriverEventsNote string
}

View is one point-in-time answer.

func Snapshot

func Snapshot(ctx context.Context, opts Options) View

Snapshot composes the readings. Every leg is best-effort and independently reported: an unreadable seat or an absent nvidia-smi narrows the verdict's evidence, named in the View, and never fails the call.

func (View) Lines

func (v View) Lines() []string

Lines is the CLI rendering (`gpu status`).

func (View) Map

func (v View) Map() map[string]any

Map is the JSON shape shared by `gpu status --json` and offload_status.

type YieldState

type YieldState struct {
	AskedAt string `json:"asked_at"` // RFC 3339
	ActedAt string `json:"acted_at,omitempty"`
	// Action is what the holder did about it: "ran on_yield", "on_yield failed", "on_yield running",
	// "no on_yield recorded", or empty when it has not acted yet.
	Action  string `json:"action,omitempty"`
	Exit    int    `json:"exit,omitempty"`
	Waiters int    `json:"waiters,omitempty"`
	// GraceSec is the time the job declared it needs to stop cleanly (--yield-grace); 0 = none declared.
	GraceSec int `json:"grace_s,omitempty"`
	// Unanswered: the lease still holds its cards past the job's grace (or past a display-only threshold
	// when it declared none). Nothing is killed or taken because of it.
	Unanswered bool `json:"unanswered,omitempty"`
}

YieldState is a yield request as a status call reports it.

Jump to

Keyboard shortcuts

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