Documentation
¶
Overview ¶
Package gpulease owns the machine-wide, crash-safe, FENCED GPU lease that every GPU consumer takes regardless of how its work arrived.
WHY THIS SUPERSEDES internal/gpulock's READ-ONLY INVARIANT (ADR: see docs/architecture/decisions): gpulock deliberately never acquires — acquisition lived only in render/gpu-lock.mjs, so the ONLY parties serialized were the Node generation runners. Measured consequence: a media job dispatched to POST /fleet/dispatch called freeLlamaSwap() and unloaded every GPU-resident model out from under an in-flight text benchmark. The llama-swap server log holds 3,356 such unloads, 330 of them for the text workhorse. Text work never took the lock, so nothing could have prevented it. A lock only one side takes is not mutual exclusion.
FOUR PROPERTIES THE OLD LOCK LACKED, each fixing an observed defect:
MACHINE-WIDE. gpu-lock.mjs defaulted to join(tmpdir(), ...), which on Windows is PER-USER (C:\Users\<u>\AppData\Local\Temp). A process in another security context — e.g. a SYSTEM-registered service — silently took a DIFFERENT lock and mutual exclusion evaporated with no error anywhere. The state root is now machine-wide, and if it is not writable we REFUSE TO START rather than fall back per-user: a silent fallback is precisely the bug.
FENCED. The lid of a laptop closing is not a crash — the process survives and resumes later. Without a fence it would resume and call freeLlamaSwap() on top of whoever holds the card now, which is the original incident replayed by a lid. Every acquisition bumps a monotonic epoch; holders re-validate with Check() before each irreversible action (unloading models, submitting a graph, promoting output).
PID-RECYCLE SAFE. The old rule trusted pid liveness alone. A recycled pid reads as "holder alive" forever. We record the holder's process START TIME alongside its pid and treat a mismatch as a dead holder.
TWO CLASSES. `media` (image/video/audio/run-graph) and `text` (a reservation taken by a benchmark/eval). Both are EXCLUSIVE — one card, one holder (a lease that names no cards holds them all; one that names its cards, devices.go, holds only those). The distinction is not access control, it is intent: only a `media` holder may unload models, and a `text` reservation makes a dispatched render WAIT instead of destroying the run. Ordinary interactive text calls are deliberately NOT lease participants: thousands per day at ~46ms, and leasing them is untenable. That asymmetry is a known limit, not an oversight — see docs.
Index ¶
- Constants
- Variables
- func AppendScopeLedger(leaseDir string, e ScopeEvent) error
- func ComfyDir() string
- func DeclaredHostRAMGiB(leases []Info) float64
- func DeclaredHostRAMLoad(leases []Info) gpuprobe.HostLoad
- func DefaultHostRAMHeadroom() float64
- func DevicesConflict(a, b []string) bool
- func DisplayAdmits(in AllocInput) (ok bool, why string)
- func DisplayBudgetGiB(totalGiB float64, capPct int, declaredFloorGiB float64) (budget float64, ok bool)
- func DisplayFloorGiB(totalGiB float64, capPct int, declaredFloorGiB float64) (floor float64, ok bool)
- func DriverUUID(id string, cards []gpuprobe.Card) string
- func EpochIsCurrent(leaseDir string, epoch uint64) bool
- func ExplainHeld(leaseDir string, info Info, grace time.Duration) string
- func HasCudaDeviceFlag(args []string) bool
- func HeartbeatHelperBehind(args []string) (helper, where string, ok bool)
- func HeartbeatHelperIn(args []string) (string, bool)
- func HeartbeatHelperInCommand(command string) (string, bool)
- func HeartbeatHelperNames() []string
- func Inherited(l Info) bool
- func InspectDirDetail(leaseDir string) (Info, *Meta, bool)
- func IsHarnessBinaryName(name string, size int64) bool
- func IsLeaseMovedOn(err error) bool
- func IsMintedProgressFile(path string) bool
- func IsRecordUnreadable(err error) bool
- func LaunchMarkerReader(comfyDir string) func() (Marker, bool)
- func LeaseDir(lockOverride, stateDir string) (string, error)
- func MaxTerm() time.Duration
- func MaxTotal() time.Duration
- func NormalizeDevices(in []string) ([]string, error)
- func OnOverdueNote() string
- func OpenShared(path string) (*os.File, error)
- func OrphanGrace() time.Duration
- func OwnersDirFor(leaseDir string) string
- func PIDAlive(pid int) bool
- func ProcessStart(pid int) (int64, bool)
- func ProgressDir(root string) string
- func ReadBuildMarkerVersion(path string) (string, error)
- func ReadSharedFile(path string) ([]byte, error)
- func ReadsPCIOrder(env func(string) string) bool
- func Reclaimable(m *Meta, now time.Time, heartbeatTTL time.Duration, ...) bool
- func RegisterOwner(leaseDir, session string, pid int) (unregister func(), err error)
- func RegisterSeatWaiter(leaseDir, reason string, devices []string) (refresh func(), unregister func())
- func ReleaseCommand(epoch uint64) string
- func ResolvePins(pins []string, cards []gpuprobe.Card) ([]string, bool)
- func ResolveStateRoot(override string) (string, error)
- func SetComfyDir(dir string)
- func SetDefaultHostRAMHeadroom(gib float64)
- func SetDefaultOnOverdue(raw string)
- func SetDefaultOrphanGrace(d time.Duration)
- func SetDefaultTerms(maxTerm, maxTotal time.Duration)
- func SweepMintedProgress(dir string, maxAge time.Duration, now time.Time) int
- func TakeoverCommand(epoch uint64) string
- func TreeMemory(root int) (privateGiB, residentGiB float64, err error)
- func TreeOrphanFreeing(epoch uint64) string
- func UseCheckFault(fn func(epoch uint64) error) (restore func())
- func UseReadFault(fn func(path string) error) (restore func())
- func UseRemoveFault(fn func(path string) error) (restore func())
- func UseStampFault(fn func(epoch uint64) error) (restore func())
- func UseStatFault(fn func(path string) error) (restore func())
- func WouldDerive(args []string, env func(string) string) bool
- func YieldFilePath(leaseDir string, epoch uint64) string
- type AllocInput
- type Allocation
- type AuditItem
- type AuditOptions
- type AuditReport
- type AwaitHostRAMOptions
- type CardsReading
- type Class
- type Derived
- type ErrGrantRefused
- type ErrHeld
- type ErrHoldStamp
- type ErrHostRAM
- type ErrLeaseMovedOn
- type Holder
- type Info
- func (i Info) AsksForHostRAM() bool
- func (i Info) DeclaresHostRAM() bool
- func (i Info) Each() []Info
- func (i Info) EffectiveDevices() []string
- func (i Info) For(ids []string) Info
- func (i Info) HoldsEpoch(epoch uint64) bool
- func (i Info) Lease(epoch uint64) (Info, bool)
- func (i Info) ScopeKind() ScopeSource
- func (i Info) Touches(ids []string) bool
- func (i Info) Where(keepLease func(Info) bool) Info
- func (i Info) WithLegacyNote(why string) Info
- type Lease
- func (l *Lease) AdvanceTerm(sig TermSignals) (TermResult, error)
- func (l *Lease) AwaitHostRAM(o AwaitHostRAMOptions) error
- func (l *Lease) Check() error
- func (l *Lease) Class() Class
- func (l *Lease) Devices() []string
- func (l *Lease) Dir() string
- func (l *Lease) Epoch() uint64
- func (l *Lease) HostRAMHold() (askedGiB float64, until time.Time, err error)
- func (l *Lease) NewYieldTicker(o YieldTickerOptions) *YieldTicker
- func (l *Lease) RecordTree(members []TreeMember) error
- func (l *Lease) Release() error
- func (l *Lease) Renew() error
- func (l *Lease) Restamp(fn func(*Meta)) error
- type Manager
- func (m *Manager) Acquire(class Class, opts Options) (*Lease, error)
- func (m *Manager) AdvanceTerm(epoch uint64, sig TermSignals) (TermResult, error)
- func (m *Manager) ApplyCardScopedConfig(on bool) error
- func (m *Manager) AwaitHostRAM(epoch uint64, o AwaitHostRAMOptions) error
- func (m *Manager) CardScoped() bool
- func (m *Manager) ClaimsOf(epoch uint64) []string
- func (m *Manager) ClearSeatWarmOwed()
- func (m *Manager) ClearSeatWarmOwedIfSeat(seat string) bool
- func (m *Manager) ClearSeatWarmOwedIfStale(seat string, readsBegan time.Time) bool
- func (m *Manager) Dir() string
- func (m *Manager) DropToken(id string)
- func (m *Manager) EmulateLegacyWriter()
- func (m *Manager) EpochIsCurrent(epoch uint64) bool
- func (m *Manager) ExplainHeld(info Info, grace time.Duration) string
- func (m *Manager) HeldError(info Info) *ErrHeld
- func (m *Manager) HostRAMCheck(needGiB float64) gpuprobe.HostRAMCheck
- func (m *Manager) HostRAMCheckLoad(need gpuprobe.HostLoad) gpuprobe.HostRAMCheck
- func (m *Manager) HostRAMCheckLoadWithout(need gpuprobe.HostLoad, epoch uint64) gpuprobe.HostRAMCheck
- func (m *Manager) HostRAMCheckWithout(needGiB float64, epoch uint64) gpuprobe.HostRAMCheck
- func (m *Manager) HostRAMHeadroom() float64
- func (m *Manager) HostRAMPending() float64
- func (m *Manager) HostRAMPendingCommit() float64
- func (m *Manager) HostRAMPendingLoad() gpuprobe.HostLoad
- func (m *Manager) Inspect() Info
- func (m *Manager) InspectDetail() (Info, *Meta, bool)
- func (m *Manager) InspectFor(devices []string) Info
- func (m *Manager) Leases() []Info
- func (m *Manager) LeaveToken(class Class, opts Options, since time.Time) (Token, error)
- func (m *Manager) MarkHolderGaveUp(epoch uint64, why string) error
- func (m *Manager) MarkSeatWarmOwed(seat string) error
- func (m *Manager) MarkSeatWarmOwedAt(seat string, at time.Time) error
- func (m *Manager) MarkToken(id, waitingFor string) bool
- func (m *Manager) NewYieldAsker(epoch uint64) *YieldAsker
- func (m *Manager) ObserveOwner(info Info) (OwnerState, time.Time)
- func (m *Manager) OwnerState(o *Owner) OwnerState
- func (m *Manager) QuarantinedCards() map[string]bool
- func (m *Manager) QueuePosition(devices []string, since time.Time, exclude string) int
- func (m *Manager) ReadOnly() *Manager
- func (m *Manager) ReaderAuditPath() string
- func (m *Manager) ReaderAuditResult() string
- func (m *Manager) RecordState(epoch uint64) (RecordState, error)
- func (m *Manager) RecordYieldAction(epoch uint64, action string, exit int) error
- func (m *Manager) ReleaseByEpoch(epoch uint64) (bool, error)
- func (m *Manager) ReleaseTarget(epoch uint64) (uint64, error)
- func (m *Manager) Restamp(epoch uint64, fn func(*Meta)) error
- func (m *Manager) ResumeToken(id string) (Token, bool)
- func (m *Manager) Root() string
- func (m *Manager) SeatWarmOwed() string
- func (m *Manager) SetCardScoped(on bool)
- func (m *Manager) SetHostRAMHeadroom(gib float64)
- func (m *Manager) StampHostRAMHold(epoch uint64, until time.Time) error
- func (m *Manager) StampHostRAMHoldPhase(epoch uint64, until time.Time, phase string) error
- func (m *Manager) Standing(info Info, grace time.Duration) Standing
- func (m *Manager) StandingAll(info Info, grace time.Duration) Standing
- func (m *Manager) StandingReadOnly(info Info, grace time.Duration) Standing
- func (m *Manager) TokenLive(t Token) bool
- func (m *Manager) Tokens() []Token
- func (m *Manager) TouchToken(id string) bool
- func (m *Manager) TryAcquire(class Class, opts Options) (*Lease, error)
- func (m *Manager) VetGrant(l *Lease, opts Options) error
- func (m *Manager) Waiters() []Waiter
- func (m *Manager) WriteReaderAudit(r AuditReport) error
- func (m *Manager) YieldOf(epoch uint64) (YieldRequest, bool)
- func (m *Manager) YieldViewOf(info Info) YieldView
- type Marker
- type Meta
- type NoCardsError
- type OnOverdue
- type Options
- type Owner
- type OwnerState
- type ProcImage
- type Progress
- type ProgressView
- type RecordState
- type RecordUnreadableError
- type Repin
- type RepinPlan
- type ResidentInfo
- type ScopeEvent
- type ScopeSource
- type Scoper
- type Skip
- type Standing
- type TermOutcome
- type TermPlan
- type TermResult
- type TermSignals
- type Token
- type TreeMember
- type TreeProc
- type Waiter
- type YieldAsker
- type YieldRequest
- type YieldRunner
- type YieldTicker
- type YieldTickerOptions
- type YieldView
- type YieldWaiter
Constants ¶
const ( ReasonQuarantined = "quarantined" ReasonDisplay = "display" // ReasonDisplayUnknown: the reading could not say which card the monitor is on // (gpuprobe.Card.DisplayUnknown), so no card is vouched for. ReasonDisplayUnknown = "display-unknown" ReasonClaimed = "claimed" ReasonForeignBusy = "foreign-busy" ReasonVRAM = "vram" )
Skip reasons. A caller branches on these, so they are constants.
const ( KindBinary = "binary" KindNodeReader = "node-reader" )
Item kinds.
const ( // DefaultHeartbeatTTL is how long a holder may go without renewing before the // heartbeat is considered stale. Deliberately generous: under a saturating // benchmark the holder process can be descheduled for a long time, and expiring // its lease during exactly the load it was taken to protect would reproduce the // incident. Staleness alone never reclaims — see Reclaimable. DefaultHeartbeatTTL = 120 * time.Second // DefaultTTL is the fallback lease duration when a caller does not stamp one. // A real video generation runs many minutes. DefaultTTL = time.Hour )
const ( HoldPhaseOuter = "outer" HoldPhaseWait = "wait" HoldPhaseRelease = "release" )
The phases of the moment a lease's hold stamp (Meta.HostRAMHoldUntilMs) stands for. Outer: a detached reserve's bound while it still clears the seat (the drain, the unload); the host has not been asked, and a live reserve keeps moving it, so it is the moment the hidden holder releases the lease only if the reserve DIES. Wait: the end of the wait for the host. Release: the reserve is releasing the lease itself and has pushed the stamp out so the holder does not race it. An older writer leaves none.
const ( ProgressAdvancing = "advancing" ProgressStalled = "stalled" ProgressUnknown = "unknown" )
Progress states.
const ( MintedProgressPrefix = "wrap-" MintedProgressSuffix = ".jsonl" )
MintedProgressPrefix and MintedProgressSuffix frame the file name of a progress file the wrapper minted (wrap-<pid>-<unix nanos>.jsonl). SweepMintedProgress deletes only names of this shape, so a file the caller keeps under a directory of its own choosing is never touched.
const ( // DefaultMaxTerm is the cap on a renewal term when config gpu_max_term_min is unset. DefaultMaxTerm = 6 * time.Hour // DefaultMaxTotal is how long after acquisition a lease may be renewed when config // gpu_max_total_min is unset. DefaultMaxTotal = 48 * time.Hour // MaxProgressTerm is the least cap on a term for a lease that declares a progress // contract: its progress file, not its window, is what judges it, so it may declare a // long first window without being warned. MaxProgressTerm = 24 * time.Hour )
const ( // TokenGrace is how long after its poller left a token still holds its place in line. TokenGrace = 30 * time.Second // TokenTTL is how long after its poller left a token can still be resumed. TokenTTL = 10 * time.Minute )
const ( YieldsWrapper = "wrapper" YieldsDetached = "detached" )
The forms of holder that run the request, as Meta.Yields records them.
const ( YieldActionRunning = "on_yield running" YieldActionRan = "ran on_yield" YieldActionFailed = "on_yield failed" YieldActionNone = "no on_yield recorded" )
Yield actions, the words the sidecar's action field carries.
const BuildMarkerPrefix = "offload-build-version="
BuildMarkerPrefix precedes the compiled-in version in a binary that carries a build marker (the version itself is read back by the audit; see internal/buildinfo).
const DefaultAuditDepth = 3
DefaultAuditDepth is how many directory levels below a scan root the walk enters.
const DefaultOrphanGrace = 15 * time.Minute
DefaultOrphanGrace is how long an owner may be gone before an attended lease reads as orphaned (config gpu_orphan_grace_min). A session that compacts or resumes is briefly between processes; the grace is what keeps that from reading as abandonment.
const FormatSignature = "gpu-lease-format-2/per-epoch-fence"
FormatSignature is the literal a format-aware binary or Node reader carries.
const MaxOnYieldBytes = 4096
MaxOnYieldBytes bounds a recorded --on-yield command. The holder runs the command verbatim, so it is stored verbatim or not at all; a command that does not fit is refused (put the logic in a script and name the script) rather than cut short.
const QueueHint = "" /* 199-byte string literal not displayed */
QueueHint is the one sentence every "the card is held" surface ends with — `gpu status`, `offload_status`, the CLI refusals. It exists because the sessions that read "held" concluded "refuse the work" — ten times over — on a machine that has had a queue since 0.113.14. A held card is a place in line, and the line is one flag. Defined here so the CLI and the MCP status tool cannot drift apart.
const RecordFormat = 2
RecordFormat is the Meta.Format every binary that understands card-scoped leases stamps.
const WaitHostRAM = "host-ram"
WaitHostRAM is Waiter.WaitingFor of a request the cards would admit but the host's memory does not yet.
const YieldFileEnv = "GPU_LEASE_YIELD_FILE"
YieldFileEnv names the variable the wrapper form hands its command: the path of the lease's yield sidecar, which exists only once the holder has been asked.
Variables ¶
var ErrCancelled = errors.New("gpulease: the wait for the card was cancelled by its caller")
ErrCancelled ends a queued Acquire whose caller closed Options.Cancel: it was told to stop while it stood in line. Nothing was claimed and the waiter's record is gone. It is not a fault of the card and not a place in line.
var ErrCardScopedOff = errors.New("gpulease: card-scoped leases are not enabled on this host (config gpu_card_scoped_leases); " +
"a lease that names devices cannot be written, and an older binary on this host would read it as a free card")
ErrCardScopedOff is returned by an acquisition that names devices on a host that has not enabled card-scoped leases.
var ErrDeviceUnresolved = errors.New("gpulease: the command's card selection cannot be resolved to cards")
ErrDeviceUnresolved wraps every refusal to turn what a command says into a card set.
var ErrReaderAuditMissing = errors.New("gpulease: gpu_card_scoped_leases is set but this host has no green reader audit")
ErrReaderAuditMissing is returned by ApplyCardScopedConfig when the config asks for card-scoped leases and the host has no green reader audit.
var ErrStillQueued = errors.New("gpulease: still queued")
ErrStillQueued is what a queued Acquire returns when its whole window passed without it ever reaching the front of the line, so no claim was attempted and no holder was seen: it waited behind a waiter that has not claimed, or behind a place held for a caller who left. A zero window is the same answer at once: the card is free, but someone registered earlier is ahead of this request, and no claim was attempted. It is a place in line and not a fault, like ErrHeld; callers that answer with a token treat the two alike.
The text says only what is true of both cases ("still queued"); the wrapping error says whether the request waited (stillQueuedErr), because "gave up waiting" is false of an attempt that was refused on the spot.
var ErrUnattendedContract = errors.New("gpulease: an unattended lease needs a declared window (--for) and a progress contract (--progress-file and --stall)")
ErrUnattendedContract is returned by an acquisition that asks to be unattended without the bounded-claim contract: a declared window and a progress file with a stall window. An unattended job has nobody to notice it going wrong, so its lease must carry the terms it is judged by; "its owner is gone" is not an escape.
Functions ¶
func AppendScopeLedger ¶
func AppendScopeLedger(leaseDir string, e ScopeEvent) error
AppendScopeLedger appends one line to the scope ledger, <gpu dir>/scope-ledger.jsonl (the directory above the lease directory, so no reader of the lease directory ever meets it). A ledger that cannot be written never fails a read, but the caller is told.
func DeclaredHostRAMGiB ¶
DeclaredHostRAMGiB is the sum of the working set the live leases declared.
func DeclaredHostRAMLoad ¶
DeclaredHostRAMLoad is the sum of what the live leases declared, per quantity.
func DefaultHostRAMHeadroom ¶
func DefaultHostRAMHeadroom() float64
DefaultHostRAMHeadroom is the headroom a Manager without its own keeps uncommitted: the installed one, else gpuprobe.DefaultHostRAMHeadroomGiB.
func DevicesConflict ¶
DevicesConflict reports whether two device sets share a card; an empty set is the whole node and conflicts with everything. It is devicesConflict for a caller outside the package that describes the line (the CLI's one entry line) and must agree with it exactly.
func DisplayAdmits ¶ added in v0.209.0
func DisplayAdmits(in AllocInput) (ok bool, why string)
DisplayAdmits is the allocator's display-card rule alone, for a launcher that puts work on the display card outside a lease (`gpu display-check`, which the opencode-only three-card vLLM seat's seat-cmd.ps1 asks before it starts): whether the display card(s) of in.Cards would take a job of in.FootprintGiB NOW. The card must be open (cap above 0, a fresh table, idle), vouched for by the reading, not claimed by a live lease, and the footprint must fit under the cap. ok is false with the allocator's own words when any display card refuses, and when the reading names no display card at all (then there is nothing to admit onto).
func DisplayBudgetGiB ¶
func DisplayBudgetGiB(totalGiB float64, capPct int, declaredFloorGiB float64) (budget float64, ok bool)
DisplayBudgetGiB is what the cap leaves a job of the display card, the desktop's own use included in what is already taken: the total less DisplayFloorGiB, never below zero. ok is false when there is no total to take it from, or when the floor has no answer.
func DisplayFloorGiB ¶
func DisplayFloorGiB(totalGiB float64, capPct int, declaredFloorGiB float64) (floor float64, ok bool)
DisplayFloorGiB is the allocator's display-card floor as a pure function of the card's total, the cap and the display layer's declared absolute floor: the rest of the card past the cap, (100 - cap) percent of the total, or the declared floor, whichever is larger. A cap of 100 or more leaves only the declared floor, and needs no total. ok is false when the cap needs a total the reading did not give. The surfaces that REPORT the cap (the card table's display_cap row, audit-yaml's display-cap-unseen note) read this same arithmetic, so none can disagree with the rule a job is admitted by.
func DriverUUID ¶
DriverUUID is a lease id as the driver prints the card's uuid. With no card table it is rebuilt: the driver's form is "GPU-" and the lower-case hex the lease id carries.
func EpochIsCurrent ¶
EpochIsCurrent is the fence for a process that holds no Lease object (an inherited lease, a render child): the lease it was handed is live and still its own. For a device lease that is per epoch, never a compare against another lease's epoch.
func ExplainHeld ¶
ExplainHeld describes, for a waiter, why the lease info is not a healthy one, or returns "" when it is (or when nothing can be said). grace <= 0 means the installed default. It is READ-ONLY: it reads the orphan marker a status surface recorded and never writes one or takes the epoch lock, so it is safe wherever a refusal is formatted (the text gate, an error's Error()). A lease whose owner is gone but that no status surface has looked at yet reads as inside its grace, so it is explained only once something recorded the moment; a stalled or overdue lease needs no marker and is explained at once.
func HasCudaDeviceFlag ¶
HasCudaDeviceFlag reports whether the command line carries ComfyUI's `--cuda-device`. The program obeys its own argv, which the wrapper does not rewrite, so an environment pin beside one is not moved.
func HeartbeatHelperBehind ¶
HeartbeatHelperBehind finds the render helper that heartbeats which the command runs: named among its arguments (HeartbeatHelperIn), named in the inline command line of an interpreter, or named in a script the command runs. It returns the helper's file name and where it was found: "" when the helper is an argument, "the inline command", or the base name of the script that names it.
func HeartbeatHelperIn ¶
HeartbeatHelperIn finds a heartbeating helper among the arguments of a command (behind an interpreter, its path in either separator style) and returns its file name.
func HeartbeatHelperInCommand ¶
HeartbeatHelperInCommand is HeartbeatHelperIn for the command line a lease records (its arguments joined by single spaces).
func HeartbeatHelperNames ¶
func HeartbeatHelperNames() []string
HeartbeatHelperNames is the list, sorted.
func Inherited ¶
Inherited reports whether this process runs under the ONE lease l describes: GPU_LEASE_EPOCH (threaded to its command by gpu reserve, and to the render runners by the pipeline's ambient lease env) equals that lease's epoch. The epoch is compared, never presence-checked, so a stale variable from a lease since handed on exempts nothing. Callers with several live leases ask it of each (Each, Where): a child of lease A is inside A and no other lease, so "inside any live lease" is never an exemption from every other lease.
func InspectDirDetail ¶
InspectDirDetail is InspectDir plus the record behind the verdict: the raw Meta (nil when no record exists or it is unreadable) and whether it was judged reclaimable. A reader that wants to say "a lease record is left over from a holder that is gone" needs the second half — Inspect's zero Info cannot distinguish that from a free card (gpuactivity, 0.117.0).
func IsHarnessBinaryName ¶
IsHarnessBinaryName reports whether a file name is one of the harness binary's names: local-offload*, offload-harness* or local-agent* (the agent binary links the lease package through modelaffinity and is deployed beside the harness), as an executable, a node-swap backup (`<exe>.bak-<suffix>`) or an extensionless Unix binary, and big enough to be one. A copy under any OTHER name is found by content (sniffable, below).
func IsLeaseMovedOn ¶
IsLeaseMovedOn is true for the refusal to release an epoch that is no longer the current lease: the one release error that says the lease is NOT this caller's any more, so there is nothing of its own left to release.
func IsMintedProgressFile ¶
IsMintedProgressFile reports whether path is a progress file of the wrapper's own minted shape (wrap-<pid>-<unix nanos>.jsonl). Such a file exists only between the start of the wrapped command and its end: a reader that finds it missing is looking at a lease that is queued, draining, unloading the seat or warming it back, not at a job that forgot to write.
func IsRecordUnreadable ¶
IsRecordUnreadable is true for a failure of the fence that is a failed READ, not a verdict.
func LaunchMarkerReader ¶
LaunchMarkerReader returns a Marker reader over a ComfyUI install directory's .offload-launch.json (the file render/comfy-ownership.mjs writes). A missing or unparseable file is no marker.
func LeaseDir ¶
LeaseDir is THE resolver every consumer must use — the CLI, the pipeline, the read-only vision gate, and the render runners via GPU_LEASE_DIR.
It exists because a second resolution order is how the lease silently splits in two. `gpu_lock_path`/GPU_LOCK were honoured by some consumers and ignored by others, so setting that supported field put the reservation verb and the render path on DIFFERENT directories, where they never contend — the original incident, restored with no warning. One function, one answer.
func MaxTerm ¶
MaxTerm is the cap on a renewal term in force: the installed one, else DefaultMaxTerm.
func MaxTotal ¶
MaxTotal is the longest a lease is renewed, from its acquisition: the installed limit, else DefaultMaxTotal.
func NormalizeDevices ¶
NormalizeDevices canonicalises a device list: trimmed, lower-cased (the claim file name must be one per card even on a case-insensitive filesystem), de-duplicated and sorted. An empty list is the whole node. A blank or non-token entry is an ERROR, never a silent widening to the whole node and never a path component.
func OnOverdueNote ¶
func OnOverdueNote() string
OnOverdueNote is the sentence a holder says once when the installed value was not recognised; empty for a recognised one.
func OpenShared ¶
OpenShared opens a file for reading in a way that does not stand in the way of a rename or a delete of that file by someone else. Off Windows that is os.Open: an open file descriptor never blocks a rename(2) or an unlink, so there is nothing to grant (openshared_windows.go says why Windows needs more).
func OrphanGrace ¶
OrphanGrace is the grace an attended lease's owner is given before the lease reads as orphaned: the installed one, else DefaultOrphanGrace.
func OwnersDirFor ¶
OwnersDirFor is the session registry beside a lease directory (<state root>/owners for <state root>/gpu/lease). Derived from the lease directory, not from the config, so the writer (an MCP server) and every reader resolve the same directory the same way, the doctrine of LeaseDir.
func PIDAlive ¶
PIDAlive is the exported view, so other packages inspecting the same lease (the read-only vision gate in internal/gpulock) share ONE definition of liveness. Two copies of this rule is how a live holder came to read as free in one package and held in another.
func ProcessStart ¶
ProcessStart is the exported process-start identity, exported for the same reason as PIDAlive: a second consumer of the lease must apply the SAME reclaim rule, and Reclaimable needs this to detect a recycled pid.
func ProgressDir ¶
ProgressDir is where `gpu reserve` mints the progress file of a lease it declares a contract for: <state root>/progress, beside owners/ and gpu/. Derived from the state root (Manager.Root) and not from the lease directory, which a gpu_lock_path override can put anywhere. The wrapper records the file's absolute path on the lease, so no reader needs to derive this directory again.
func ReadBuildMarkerVersion ¶
ReadBuildMarkerVersion returns the build version the file at path states in its build marker ("" with no error when the file carries none: a binary that predates the marker). It is the audit's own reader (scanInto), so a doctor row and a stale-image check can never read two different versions out of one file. A file that cannot be opened or read is an error, never "no marker": the caller must not take a failure for a fresh image.
func ReadSharedFile ¶
ReadSharedFile is readSharedFile for a reader in another package of a file its writer replaces by a rename over the live name: the ComfyUI launch markers (internal/comfyinst), which render/comfy-ownership.mjs restamps through a staged .tmp file.
func ReadsPCIOrder ¶
ReadsPCIOrder reports whether a bare device index in this environment is nvidia-smi's (PCI bus) index: CUDA counts indices in FASTEST_FIRST order, which nvidia-smi cannot report, unless the environment says CUDA_DEVICE_ORDER=PCI_BUS_ID.
func Reclaimable ¶
func Reclaimable(m *Meta, now time.Time, heartbeatTTL time.Duration, procStart func(int) (int64, bool)) bool
Reclaimable decides whether an existing lease may be taken over. The rule is a deliberate CONJUNCTION, and both halves are load-bearing:
(holder is provably gone) OR (heartbeat is stale AND the declared window has expired)
A bare heartbeat timeout is wrong: under the saturating benchmark a text reservation exists to protect, the holder can stall past any short TTL, and expiring it hands the card to a render mid-measurement — the exact incident. Pid-liveness alone is also wrong: `reserve --detach` spawns a PROXY holder that stays alive after the benchmark behind it dies, so a dead run could hold the card for its full declared window. Requiring BOTH staleness and expiry for the liveness-independent path, while letting provable death reclaim immediately, is the only combination that survives both.
"Provably gone" is about the WRAPPER, not the job it started (plan P10, tree.go): a holder whose pid is dead or recycled is reclaimable only if no member of the tree it recorded is still the process that was recorded. This pure rule reads the record alone: a lease that recorded no tree has no member to hold it, so it is freed at once. The reader (reader.judge in tree.go) first folds in the other evidence that ties a live process to such a lease (a launch marker, or on Windows a child of the dead wrapper), and a lease with none alive is freed as before. A launch marker that is being installed cannot be read and so cannot say that none is alive: the reader sets treeUnknown on its copy of the record, and the lease is held for as long as the marker is (at most the freshness of its staged file, tree.go).
A heartbeat that is UNKNOWN is not stale. The reader (reader.judge) passes it as RenewedAtMs 0, "no stamp", and a heartbeat nobody could read or examine (a rename is installing it, an I/O error that outlasted its wait) says nothing about the holder. What frees such a lease is the first half of the rule (the wrapper is gone: pid and start time) or `gpu release`; a heartbeat that stays unknown for good on a holder that is alive but hung keeps its lease until then. A file that can be examined is aged by its modification time, so a corrupt heartbeat nobody renews still goes stale (heartbeatAt).
func RegisterOwner ¶
RegisterOwner records this process as carrying session, in the registry beside leaseDir, and returns the function that removes the record. A second process under the same session (a resume, a compaction) simply adds its own file. Entries of processes that are no longer alive are swept on the way, so the directory cannot grow without bound. An empty session registers nothing.
func RegisterSeatWaiter ¶
func RegisterSeatWaiter(leaseDir, reason string, devices []string) (refresh func(), unregister func())
RegisterSeatWaiter marks a blocked seat/text-load admission as queued for the lease at leaseDir (register D-1xx-2, 2026-09-23; R2 2026-09-23: "seat starvation behind chained media leases").
THE INCIDENT. A `transcribe` call's admission (modelaffinity.awaitLease) waited 15+ minutes behind another client's back-to-back media leases and was never admitted between them: epoch 111 (music) released and epoch 112 (music) was re-acquired by the SAME client with no gap the admission's own 1 s poll ever caught free — seat/text-load admission had no representation in the lease queue at all, so a fresh media Acquire (once D-1xx's FIFO fix makes it queue behind registered waiters) still had nothing to queue BEHIND in this case, because the admission was not one.
THE FIX reuses the SAME waiters/ directory and Waiter record a lease Acquire itself registers (waiters.go's FIFO doctrine), tagged ClassSeat so `gpu status` and the queue log can tell it apart. Because isFrontOfQueue / Waiters() are class-agnostic (no ADR gives the queue a class priority — see waiters.go), a media/text Acquire that reaches its own front-of-queue check automatically yields to a live ClassSeat entry exactly as it yields to a real lease waiter, with NO changes needed to the ordering algorithm itself.
WHY THIS CANNOT DEADLOCK OR STARVE THE LEASE. A ClassSeat waiter NEVER itself calls TryAcquire — it is not competing FOR the lease, only for a fair turn once the card frees — so it can only ever DELAY another acquirer's first successful claim, never block it forever: once the admission notices the lease free (its own leasePollInterval-cadenced InspectDir, independent of this registration) it proceeds and the CALLER unregisters via the returned func, freeing the front of the queue for the next real Acquire loop within at most one of the admission's own poll ticks. While the lease is genuinely held by someone else, a ClassSeat entry changes nothing: TryAcquire already refuses on its own, registered waiter or not.
WHICH CARDS. devices are the cards the blocked admission is waiting to load onto — its seat's cards (lease ids), the same set awaitLease blocks on (ScopeToModel). Every newcomer is gated by a registered waiter that CONFLICTS with it, so the set is what keeps this entry from holding back work it has nothing to do with: registered as the whole node, a text-load admission blocked on its seat's card stopped a fresh `gpu reserve --devices <other card>` on a free, unrelated card (pre-ship review of D-1xx-3, 2026-10-09). nil is the whole node, the right answer only when the seat's cards cannot be named (an undeclared model, a pin the card table cannot place, a card table that cannot be read): unknown is every card, the gate's rule.
refresh must be called on every one of the caller's own poll ticks — a long wait's record otherwise goes heartbeat-stale (waiterStaleWindow, see the ALIVE BUT NOT POLLING section atop this file) and stops protecting the admission's place in line, exactly like an Acquire loop's own refreshWaiter call. unregister is safe to call more than once and must run via defer so a cancelled or timed-out admission never leaks a waiter that would otherwise sit at the front of the queue until it goes stale.
func ReleaseCommand ¶
ReleaseCommand is the command that ends a lease's claim at once, for epoch. It is the one command that frees a tree-orphan today: it stops only the ComfyUI instances kept under that lease and nothing else, so the rest of the job keeps running on the card, which is why it is never run on a guess.
func ResolvePins ¶
ResolvePins turns a seat's device pins into lease ids. A seat is launched with CUDA_VISIBLE_DEVICES under CUDA_DEVICE_ORDER=PCI_BUS_ID (the tier's gpu_env), so a bare pin is an nvidia-smi index; a pin that is a UUID prefix (a display device pinned across board reorders) resolves the same way. ok is false for no pins, no card table, or any pin the table cannot place (unknown index, ambiguous prefix, a card named twice, a blank entry): the caller reads that as UNKNOWN, which is every card.
func ResolveStateRoot ¶
ResolveStateRoot picks the machine-wide state root and REFUSES bad ones.
Order: explicit override (config state_dir) > LOCAL_OFFLOAD_STATE_DIR env > platform default. The platform default is machine-wide on purpose (%ProgramData% on Windows, /var/lib on POSIX) — a per-user default is the defect this package exists to fix.
func SetComfyDir ¶
func SetComfyDir(dir string)
SetComfyDir arms the ComfyUI install directory the launch markers are read from (config comfy_dir), once per process like the lease directory. Empty disables the marker evidence.
func SetDefaultHostRAMHeadroom ¶
func SetDefaultHostRAMHeadroom(gib float64)
SetDefaultHostRAMHeadroom installs the operator's headroom (config gpu_host_ram_headroom_gib) for EVERY Manager of this process, the way the orphan grace and the term limits are installed (SetDefaultOrphanGrace, SetDefaultTerms): config.Load calls it, so no constructor can forget. It used to be a per-Manager setter that no production path called, so the grant kept reading the built-in 8 GiB while `gpu status` and the card allocator read the configured key: an operator who raised the headroom to be safer was admitted up to the difference past the limit he set, and one who lowered it to unblock a lane was still refused (the post-implementation review, 2026-10-10). Zero, negative or not-a-number restores the default.
func SetDefaultOnOverdue ¶
func SetDefaultOnOverdue(raw string)
SetDefaultOnOverdue installs the configured policy for every holder tick and every sentence of this process, the way the orphan grace is installed. A value nobody recognises installs hold and a note that says why no request will be made.
func SetDefaultOrphanGrace ¶
SetDefaultOrphanGrace installs the operator's orphan grace for every Standing computed with a zero grace. Zero or negative restores DefaultOrphanGrace.
func SetDefaultTerms ¶
SetDefaultTerms installs the operator's term limits (config gpu_max_term_min and gpu_max_total_min) for every acquisition and every tick of this process, the way the orphan grace is installed. Zero or negative restores the default for that limit.
func SweepMintedProgress ¶
SweepMintedProgress removes the minted progress files in dir that nothing has written to for maxAge. A wrapper removes its own file when its command ends, so what is left here was left by a wrapper that was killed (a closed console, a taskkill of the tree) before it could. It runs inline in the next `gpu reserve` that mints one: no timer, no watcher. It returns how many files it removed; every error is swallowed, because a directory that cannot be swept costs disk, never a lease.
func TakeoverCommand ¶
TakeoverCommand is the command that frees a lease whose holder will not, for epoch.
func TreeMemory ¶
TreeMemory is the private and the resident memory (GiB) of root and every process below it: what a render's whole process tree holds right now. It is the measurement path of G3 (the P0 plan): sampled while a render runs, its peaks are what the footprint store keeps beside the VRAM peak. Unlike descendantsResidentGiB the root is counted, because here the root is the render's own runner, not a long-lived server. A process that cannot be read counts as holding nothing (the reading is then LOW, never high: callers that act on it only ever raise a declaration with it). err is non-nil only when the process table itself cannot be read.
func TreeOrphanFreeing ¶
TreeOrphanFreeing is the sentence that tells a reader how a tree-orphan ends: by itself when the job's processes are gone, or at once by ReleaseCommand, with what that does and does not stop.
func UseCheckFault ¶
UseCheckFault makes Lease.Check fail with what fn returns for the epoch (nil from fn lets the fence run) until the returned function is called: the way a test in another package provokes a fence read that fails for a moment, as a read of a record that is being replaced does on Windows. Nothing in production calls it.
func UseReadFault ¶
UseReadFault makes the READ of a lease record fail with what fn returns for the path (nil from fn lets the real read run), until the returned function is called: the way a test provokes a record that EXISTS and can be removed but cannot be read, as one is while a scanner or another process holds it open on Windows. The file itself is untouched, so the record is still there for the fault to be lifted. Nothing in production calls it.
func UseRemoveFault ¶
UseRemoveFault makes every lease-file removal in this process fail with what fn returns for the path (nil from fn lets it through), until the returned function is called. A test seam, for a release that must fail where a portable test cannot provoke a real filesystem error: nothing in production calls it.
func UseStampFault ¶
UseStampFault makes every StampHostRAMHold in this process fail with what fn returns for the epoch (nil from fn lets it through), until the returned function is called: the way a test in another package provokes a stamp that cannot be written while the other restamps of the lease (the drain's, the exclusive one) still work. Nothing in production calls it.
func UseStatFault ¶
UseStatFault makes the examination of a lease record before its release fail with what fn returns for the path (nil from fn lets the real stat run), until the returned function is called: the way a test provokes a stat that fails for a reason other than the record being absent, as one does on Windows while the record is being replaced. Nothing in production calls it.
func WouldDerive ¶
WouldDerive reports whether the command says anything about its cards at all, so a caller that cannot read the card table can still tell "no evidence" from "evidence I cannot resolve".
func YieldFilePath ¶
YieldFilePath is where the sidecar of one epoch is (or will be) in a lease directory.
Types ¶
type AllocInput ¶
type AllocInput struct {
Cards []gpuprobe.Card
// Claimed holds lease ids of cards a live lease claims. WholeNodeHeld says a
// whole-node lease is live, which claims every card.
Claimed map[string]bool
WholeNodeHeld bool
Quarantined map[string]bool
// ForeignBusy maps a lease id to a short description of the foreign process on it.
ForeignBusy map[string]string
// Resident maps a lease id to the seats loaded on that card.
Resident map[string]ResidentInfo
// DisplayCapPct is how much of a display card's total VRAM jobs may fill, the desktop's own
// use included (config gpu_display_cap_pct, default 60, A-RAM-15): the card is allocatable only
// while the VRAM in use now plus the job's declared footprint is at most this share of it,
// which is the display layer's display_floor arithmetic (free - footprint >= floor) with the
// floor set to the rest of the card. 0 = closed, the operator's "I need the card" switch, and
// the zero value of the field. 100 = the whole card: with no DisplayFloorGiB declared nothing is
// held back, so no footprint is needed there either (every other cap refuses a job that declares none). It applies to the display card only; every
// other card is judged by the footprint alone. A card whose reading could not say where the
// monitor is (DisplayUnknown) stays closed whatever this says.
DisplayCapPct int
// DisplayStale closes the display card whatever the cap says: the caller is placing the call from a card
// table it could not refresh, and the cap is judged on the VRAM in use now, the one number a stale table
// misstates. It is a reading's doing, not the operator's, so DisplayCapPct keeps what the config says and
// the skip says why the card is closed (the table, not a gpu_display_cap_pct of 0 nobody wrote).
DisplayStale bool
// DisplayBusy closes the display card whatever the cap says while the card is not idle (operator rule
// 2026-11-07: the cap's share is the jobs' only WHEN IDLE): the caller's reading of why, empty when the
// operator is away and the card is not busy (gpualloc.DisplayBusy reads both, and fails closed). The empty
// zero value is "idle" so an input built by hand keeps the cap's own behaviour; every production input is
// built by gpualloc.BuildInput, which always reads it.
DisplayBusy string
// DisplayFloorGiB is a floor the display layer declares in absolute terms (display_floor_gib,
// internal/placement/guards.go) and keeps on the display card on top of the cap: the card keeps
// the LARGER of this and the cap's remainder, so a stricter declaration still holds and the
// two doors onto the card agree. 0 = none declared.
DisplayFloorGiB float64
// FootprintGiB is the VRAM the job needs free on EACH card (0 = not declared).
FootprintGiB float64
// Host RAM term, the one rule the lease grant applies (gpuprobe.HostRAMAdmitsLoad): the host's memory
// now, the job's declared need (HostNeedGiB the working set it touches, HostNeedCommitGiB the commit it is charged, 0 =
// the same figure), the part of the leases ALREADY GRANTED that has not loaded yet in both quantities (HostPending,
// Manager.HostRAMPendingLoad) and the headroom to keep. Here it is advisory (it keeps the allocator
// from picking cards a grant would then refuse); the grant, under the epoch lock, is the authority.
HostMem gpuprobe.HostMemory
HostMemOK bool
HostNeedGiB, HostNeedCommitGiB float64
HostPending gpuprobe.HostLoad
HostHeadroomGiB float64
// Min and Max bound how many cards to take (1 <= Min <= Max).
Min, Max int
}
AllocInput is everything the rule reads.
type Allocation ¶
Allocation is the cards taken (lease ids, in the order chosen) and what was skipped.
func Allocate ¶
func Allocate(in AllocInput) (Allocation, error)
Allocate picks the cards. A request that is itself wrong (Min < 1, Max < Min) is a plain error; a request that cannot be met right now is a *NoCardsError.
type AuditItem ¶
type AuditItem struct {
Path string `json:"path"`
Kind string `json:"kind"`
// Found is how it was reached: "self", "scan <root>", "running (why)"; PIDs lists the
// running processes behind a "running" entry.
Found []string `json:"found"`
PIDs []int `json:"pids,omitempty"`
Size int64 `json:"size"`
// Aware is true when the file carries FormatSignature.
Aware bool `json:"aware"`
// Version is the compiled-in build version a binary's marker states ("" = the
// binary predates the marker).
Version string `json:"version,omitempty"`
// Older is set by `gpu doctor` on a RUNNING binary whose build marker states an older version than the installed
// build's: a process a rename-swap left on its pre-swap image (D-36). It is information, not a finding.
Older bool `json:"older_than_installed,omitempty"`
Err string `json:"error,omitempty"`
// contains filtered or unexported fields
}
AuditItem is one file the audit judged.
type AuditOptions ¶
type AuditOptions struct {
// Roots are directories searched for harness binaries and gpu-lock.mjs readers.
Roots []string
// SelfPath is the running executable (always audited).
SelfPath string
// Files are audited by name, without walking anything (PATH entries).
Files []string
// Images are running processes' images; ImagesErr is set when the process table
// could not be listed.
Images []ProcImage
ImagesErr error
// MaxDepth bounds the directory walk below each root (default 3).
MaxDepth int
}
AuditOptions say where to look.
type AuditReport ¶
type AuditReport struct {
Items []AuditItem `json:"items"`
// Reasons are why the audit is not green; empty when it is.
Reasons []string `json:"reasons,omitempty"`
// NotSearched lists the directories the walk did not enter. It is information, not a
// finding: a gap that is listed can be closed (--scan, a deeper cap), a gap that is
// not listed reads as a pass.
NotSearched []string `json:"not_searched,omitempty"`
Green bool `json:"green"`
}
AuditReport is the audit's whole answer.
func Audit ¶
func Audit(opts AuditOptions) AuditReport
Audit scans the options and judges every file it reaches.
type AwaitHostRAMOptions ¶
type AwaitHostRAMOptions struct {
// Deadline ends the wait with the refusal it last had. The zero time, or one already past, is a single attempt.
Deadline time.Time
// Cancel, when closed, ends the wait with ErrCancelled (a signal, a lost lease).
Cancel <-chan struct{}
// OnWait is called ONCE, at the first refusal of a wait that will go on (Deadline in the future): the CLI says
// there that the lease holds its cards and is waiting for the host. Once, because a line per poll is a
// notification per second in the session that wraps the reserve.
OnWait func(*ErrHostRAM)
// HoldUntil, when set, is the moment the caller releases the lease if the host still lacks the room (the CLI passes the
// earlier of its hold bound and its --wait deadline, which is also the Deadline): it is stamped on the lease's record
// (Meta.HostRAMHoldUntilMs) when the wait BEGINS, so `gpu status` can say when the lease will be released and the lease's
// hidden holder can release it itself if the caller died. It is taken off the record only by admission, in the same
// critical section that declares the figure: a wait that ends any other way leaves it, because a lease that still asks for
// the host and carries no moment is one nobody is bound to release, and clearing it on the way out left a window of
// milliseconds in which a caller that died stranded the cards. It bounds nothing by itself; Deadline does.
HoldUntil time.Time
// OnStampError, when set, is told when the bound's stamp could not be written. The wait does not fail on it: the stamp is
// what `gpu status` and the hidden holder read, not what ends the wait, so a failed write costs the status line and the
// holder's own enforcement, and the CLI says so once.
OnStampError func(err error)
// RequireStamp makes a stamp that cannot be written a failure of the wait: the stamp is tried a few times, and if it still has
// not landed the wait ends with *ErrHoldStamp before the host is looked at. The caller that sets it is one whose hidden holder
// is the only thing that can release the lease if the caller dies, so a wait the holder cannot see the end of must not run.
RequireStamp bool
}
AwaitHostRAMOptions bound one AwaitHostRAM.
type CardsReading ¶
type CardsReading int
CardsReading is what one look at a lease's cards found. It has three answers, not two, because "the cards show no work" and "the cards could not be read" are different statements and the label a lease wears says one of them aloud: a sample that failed or timed out (most likely when the GPU is saturated, which is when the cards are busiest) must not be worded as a card that is idle.
const ( // CardsIdle: the cards were read and none of them shows work. CardsIdle CardsReading = iota // CardsWorking: a card of the lease is at or above the verdict's busy threshold. CardsWorking // CardsUnreadable: the cards could not be read (the sample failed, timed out or returned // nothing usable). It renews nothing, as an idle reading renews nothing, but it is worded as // what it is. CardsUnreadable )
type Class ¶
type Class string
Class labels what the holder intends to do with the card. Both classes are exclusive; the label drives POLICY (who may unload, what a waiter is told).
const ( // ClassMedia is a generation job. Its holder is the ONLY party permitted to // unload llama-swap models (freeLlamaSwap), and it must do so once per LEASE, // not once per job — the per-job call is what produced 330 teardowns. ClassMedia Class = "media" // ClassText is a reservation held by a benchmark, eval, or measured run. Its // holder unloads nothing; it exists so media work WAITS rather than tearing the // text tier down mid-measurement. ClassText Class = "text" // ClassSeat (register D-1xx-2, 2026-09-23) is NOT a lease class — Valid() // deliberately excludes it, so nothing can Acquire with it and it can // never itself hold the card. It exists only to appear in the WAITERS // queue: a blocked seat/text-load admission (modelaffinity.awaitLease) // registers one via RegisterSeatWaiter while it polls for the lease to // free, so a chained media Acquire yields to it exactly as it yields to // any other registered waiter — see RegisterSeatWaiter's doc for why a // seat request otherwise starved behind back-to-back media leases that // left it no gap to ever be noticed in. ClassSeat Class = "seat" )
func (Class) LeasePhrase ¶
LeasePhrase is the class as a sentence names a holder: "a text-class lease". The bare class word ("GPU: held by text pid 792210") read as a text SEAT holding the card, and on 2026-10-07 two sessions argued over who held it while one was looking at a bench's reservation. The class only labels what the reservation is for, so every surface that names a holder says "lease". An empty class (a claim still in progress, a record that never carried one) is just "a lease".
type Derived ¶
type Derived struct {
// IDs are lease ids (lower-cased UUIDs); empty = the command names no card.
IDs []string
// Source says where the evidence came from; empty when IDs is.
Source string
}
Derived is the card set a command's own text names.
type ErrGrantRefused ¶
type ErrGrantRefused struct {
// Reason is the check's own words.
Reason string
}
ErrGrantRefused is what Acquire (and VetGrant) returns when the caller's GrantCheck found, with the cards just granted, that the request no longer qualifies for them. It is not contention: the cards were free, and the answer will not change by waiting in this place in line. The grant has been released again. The caller decides again from fresh readings (take another card the request still fits, or queue on what qualifies now) and may hand the arrival time back in Options.QueuedSince to keep its position.
func (*ErrGrantRefused) Error ¶
func (e *ErrGrantRefused) Error() string
type ErrHeld ¶
type ErrHeld struct {
Info Info
// contains filtered or unexported fields
}
ErrHeld is returned by TryAcquire when the card is legitimately held by someone else. It carries the current holder so a caller can report an honest ETA rather than a bare failure.
type ErrHoldStamp ¶
ErrHoldStamp is the failure of a wait that RequireStamp bound to its stamp: the moment the wait ends could not be put on the lease's record, after Tries attempts. The record is left as it was (an earlier, outer stamp stays).
func (*ErrHoldStamp) Error ¶
func (e *ErrHoldStamp) Error() string
func (*ErrHoldStamp) Unwrap ¶
func (e *ErrHoldStamp) Unwrap() error
type ErrHostRAM ¶
type ErrHostRAM struct {
gpuprobe.HostRAMCheck
}
ErrHostRAM is the refusal of a grant on host-RAM grounds. The embedded check carries the numbers the decision rested on; Error() is the sentence, which names the condition that refused and its numbers ("waiting for host RAM: needs N GiB, only X GiB of Y GiB physical is available, Z GiB headroom" for the touched set, "waiting for host RAM: needs N GiB, committed X of Y GiB physical, Z GiB headroom" for a commit nobody stated ("... of Y GiB commit limit ..." where an enforced limit sits below physical RAM), and "waiting for host RAM: needs N GiB of commit, committed X of Y GiB commit limit, Z GiB headroom" for a stated one).
func (*ErrHostRAM) Error ¶
func (e *ErrHostRAM) Error() string
type ErrLeaseMovedOn ¶
type ErrLeaseMovedOn struct{ Asked, Current uint64 }
ErrLeaseMovedOn is the refusal for releasing an epoch that is no longer the current lease.
func (*ErrLeaseMovedOn) Error ¶
func (e *ErrLeaseMovedOn) Error() string
type Holder ¶
Holder identifies the process holding the lease. StartTimeMs is an opaque, platform-specific process-start identity used ONLY for equality comparison; it closes the pid-recycling hole that pid-liveness alone cannot see.
type Info ¶
type Info struct {
Held bool
Class Class
Epoch uint64
PID int
Age time.Duration
Reason string
Origin string
JobID string
ExpiresAt time.Time
// Exclusive mirrors Meta.Exclusive: the holder cleared the cards and expects
// them to stay clear.
Exclusive bool
// Draining mirrors Meta.Draining: the holder is waiting for the seat to go
// idle; new runs wait, in-flight runs complete.
Draining bool
// Command mirrors Meta.Command: what the holder is running, when it said.
Command string
// HostRAMGiB mirrors Meta.HostRAMGiB: the host RAM the holder declared (0 = none declared).
HostRAMGiB float64
// HostRAMCommitGiB mirrors Meta.HostRAMCommitGiB, read as the commit the holder declared: the field when the record has one,
// else HostRAMGiB (a holder that declared one figure declared it for both).
HostRAMCommitGiB float64
// HostRAMWaitGiB mirrors Meta.HostRAMWaitGiB: host RAM the holder asked for and the host has not admitted yet.
HostRAMWaitGiB float64
// HostRAMWaitCommitGiB mirrors Meta.HostRAMWaitCommitGiB, read the same way (the field, else HostRAMWaitGiB).
HostRAMWaitCommitGiB float64
// HostRAMWaitCommitStated says the record carries a wait commit (Meta.HostRAMWaitCommitGiB above 0), which is a stated one,
// as against the touched figure HostRAMWaitCommitGiB reads as when the record has none. AwaitHostRAM puts it to the rule.
HostRAMWaitCommitStated bool `json:"-"`
// HostRAMHoldUntil mirrors Meta.HostRAMHoldUntilMs: when the hold bound releases a lease that is waiting for the host
// with its cards held (the outer bound a detached reserve stamps before its drain, then the wait's own end). Zero = no bound
// is on the record.
HostRAMHoldUntil time.Time
// HostRAMHoldPhase mirrors Meta.HostRAMHoldPhase, normalised: HoldPhaseOuter, HoldPhaseWait or HoldPhaseRelease while a stamp is on
// the record (a stamp without a phase is the wait's), empty without one.
HostRAMHoldPhase string
// HolderGaveUp mirrors Meta.HolderGaveUpMs, with the reason: the moment the lease's hidden holder gave up releasing it.
HolderGaveUp time.Time
HolderGaveUpWhy string
// HeartbeatAt is the holder's last renewal (the per-epoch heartbeat file,
// else the acquisition stamp). Zero when unknown.
HeartbeatAt time.Time
// Devices are the cards this lease claims (GPU UUIDs); empty = the whole node.
Devices []string
// Epochs lists every live lease's epoch, lowest first. Epoch is the lowest of
// them. A directory holds several leases at once only when card-scoped leases are
// in use; a whole-node lease is always a single epoch.
Epochs []uint64
// Group and WrapperVersion mirror the record's v2 fields.
Group string
WrapperVersion string
// Legacy is true when the record was written by a binary that predates card-scoped
// leases (no Meta.Format, no wrapper version) and declares no cards. Only such a record
// is ever scoped by the evidence rule (infer.go): its writer could not have named cards,
// so its silence is not a statement. A whole-node record from a binary that could have
// declared cards (an explicit --whole-node, a reserve with the writer flag off, the
// pipeline's own media lease) is the whole node by its writer's word.
Legacy bool
// Inferred is the card set a LEGACY whole-node record was scoped to by the evidence
// rule (effective.go). It is never the record's claim: Devices stays what the record
// declares, so the card table and the allocator read the lease as the whole node it
// is. Consumers that ask "does this lease sit on my card" read EffectiveDevices.
// Scope names where the effective set came from (the zero value reads as declared
// when Devices is set and whole-node otherwise); ScopeWhy is the sentence behind a
// legacy lease that stayed whole-node or was scoped; ScopeWidened marks an inferred
// set that grew after it was first established.
Inferred []string
Scope ScopeSource
ScopeWhy string
ScopeWidened bool
// AcquiredAt is when the lease was taken (the acquirer's own stamp).
AcquiredAt time.Time
// Owner, Unattended, Progress, YieldGraceMs and OnYield mirror the record's
// ownership fields (owner.go). Owner is nil for a record that names none.
Owner *Owner
Unattended bool
Progress *Progress
YieldGraceMs int64
OnYield string
OnYieldDir string
// Yields mirrors Meta.Yields: which form of holder runs the yield request ("" = a holder that
// does not: a build from before it, or an in-process holder of this build).
Yields string
// Term, Requested and HardEnd mirror the record's terms (term.go): the renewal term, the
// window the caller asked for when that was above the cap on a term (zero otherwise), and
// the instant after which the lease is no longer renewed (AcquiredAt plus the maximum
// total; zero for a record that carries none). Expired and ExpiredWhy mirror the label the
// holder's tick stamped when the term ended unrenewed: held, fenced and heartbeating all
// the same.
Term time.Duration
Requested time.Duration
HardEnd time.Time
Expired bool
ExpiredWhy string
// Leases lists every live lease on its own (lowest epoch first) when MORE THAN ONE
// is live; it is nil otherwise. Info itself describes only the lowest, so a consumer
// that decides "does a lease fence me" from Class, Exclusive and Draining must walk
// Each(), or it judges one lease and is blind to the rest. Each entry carries its own
// epoch only (Epochs has one element) and no Leases of its own.
Leases []Info
// TreeOrphan: the lease's wrapper is gone (dead, or its pid recycled) but a process of the
// job it started is still alive, so the claim is kept. TreeLive are those processes and
// TreeWhy the evidence for them (tree.go).
TreeOrphan bool
TreeLive []TreeMember
TreeWhy string
}
Info is one point-in-time inspection.
func InspectDir ¶
InspectDir reports the lease state at an explicit lease directory, for READ-ONLY consumers that do not own a Manager (the vision gate in internal/gpulock).
It exists so there is ONE inspection path. A second reader that reconstructs the judgement from the record alone gets it wrong the moment any detail moves — when the heartbeat became a per-epoch file, a record-only reader saw a frozen RenewedAtMs and would call a live, renewing holder stale as soon as its declared window lapsed. Same divergence as the path split and the schema split, one more layer down.
With card-scoped leases a directory can hold several leases at once. The Info it returns is the lowest live epoch's, so a caller that knows nothing about devices reads ANY live lease as a held card (the conservative reading, and today's for a whole-node lease); Info.Epochs lists every live epoch and InspectLeases returns one Info per lease.
func InspectLeases ¶
InspectLeases lists every live lease in a lease directory, lowest epoch first. A whole-node lease is one entry with no Devices.
func InspectScoped ¶
InspectScoped is InspectDir with the evidence rule applied to every legacy whole-node lease in it: the one inspection a consumer that gates a SEAT should make. With a nil scoper it is InspectDir.
func (Info) AsksForHostRAM ¶
AsksForHostRAM says the lease waits to have host memory admitted (either quantity): it holds its cards and has not yet declared the figure (Meta.HostRAMWaitGiB).
func (Info) DeclaresHostRAM ¶
DeclaresHostRAM says the lease declared any host memory (either quantity).
func (Info) Each ¶
Each returns the leases an Info describes, one Info per lease: Leases when several are live, else the Info itself. A consumer's per-lease question (does THIS lease fence me, am I running UNDER this lease) is asked of each element, never of the lowest-epoch summary.
func (Info) EffectiveDevices ¶
EffectiveDevices is the card set the lease sits on, as lease ids: the declared devices, else the inferred ones, else nil (the whole node).
func (Info) For ¶
For narrows an inspection to the live leases that touch ids: a consumer that gates one seat reads the leases that matter to that seat and nothing else, then asks the same predicates (Held, Class, Exclusive, Draining, Reserved, BlocksNewRun, Fenced) it always asked. An empty ids is an unknown card set and returns i unchanged. The result keeps the whole-node-era shape: one lease is the Info itself, several are the lowest epoch with Leases carrying each.
func (Info) HoldsEpoch ¶
HoldsEpoch reports whether epoch is one of the live leases this inspection saw. It is the comparison every "is this process inside the held lease" site must use: `info.Epoch == epoch` is wrong the moment a second lease is live, because Epoch is only the lowest of them.
func (Info) Lease ¶
Lease returns the record of one live lease of this inspection by epoch. Info itself describes only the lowest, so a consumer reporting something about ANOTHER lease (the most escalated of several: its owner, its progress contract, the command that takes it over) reads that lease's own record here and never mixes it with the lowest epoch's.
func (Info) ScopeKind ¶
func (i Info) ScopeKind() ScopeSource
ScopeKind names where EffectiveDevices came from, spelling out the zero value.
func (Info) Touches ¶
Touches reports whether this lease sits on any card in ids (lease ids, lower-cased UUIDs). An empty ids is an unknown card set, which is every card; a lease that holds nothing touches nothing.
func (Info) Where ¶
Where narrows an inspection to the live leases keep accepts, in the shape For returns: no lease is the zero Info, one is the Info itself, several are the lowest epoch with Leases carrying each. A consumer that asks about only some leases (the ones that refuse new work, the ones that sit on a seat's cards) filters here and then asks the predicates it always asked of the result.
func (Info) WithLegacyNote ¶
WithLegacyNote reads every held legacy whole-node lease in i as the whole node and says why in ScopeWhy: the evidence rule was not run (it is off on this host), so nothing was inferred. A lease that declares its cards, or one a binary that could name cards wrote, is left as it is.
type Lease ¶
type Lease struct {
// contains filtered or unexported fields
}
Lease is a held lease. Every irreversible action must be preceded by Check().
func (*Lease) AdvanceTerm ¶
func (l *Lease) AdvanceTerm(sig TermSignals) (TermResult, error)
AdvanceTerm is Manager.AdvanceTerm for the lease's own holder.
func (*Lease) AwaitHostRAM ¶
func (l *Lease) AwaitHostRAM(o AwaitHostRAMOptions) error
AwaitHostRAM is Manager.AwaitHostRAM for the lease's own holder.
func (*Lease) Check ¶
Check is the FENCE. Call it immediately before every irreversible action: unloading models, submitting a graph to ComfyUI, promoting an output file. A non-nil error means we no longer hold the card and must abort — not retry.
For a card-scoped lease the fence is per epoch: its own record is there and each of its cards still names its epoch. It never compares against another lease's epoch.
func (*Lease) Epoch ¶
Epoch is the fencing token. Threaded to child processes as GPU_LEASE_EPOCH so an inherited-lease child can prove it still holds what its parent acquired.
func (*Lease) HostRAMHold ¶
HostRAMHold is what this lease's OWN record says about its wait for the host: the figure it still asks for (0 = admitted, or nothing was deferred) and the moment its wait is stamped to end (the zero time = no wait is running). The hidden holder of a detached lease reads it on every poll, so that a reserve that died during the wait does not leave the cards held for good. An error means the record cannot be read (the lease is gone, or another lease holds the cards now).
func (*Lease) NewYieldTicker ¶
func (l *Lease) NewYieldTicker(o YieldTickerOptions) *YieldTicker
NewYieldTicker binds a yield ticker to a lease this process holds.
func (*Lease) RecordTree ¶
func (l *Lease) RecordTree(members []TreeMember) error
RecordTree stores the members of the tree the holder started in the lease record, so a reader that finds the holder gone can tell whether the job it started is still alive. It writes only when the set differs from the one it last recorded (the record rewrite takes the epoch lock), and refuses when the lease is no longer this holder's. The holder's own pid is not a member: the record already carries it.
func (*Lease) Release ¶
Release drops the lease — but ONLY if we still hold it. Releasing unconditionally would let a fenced-out straggler delete the CURRENT holder's lease, which is a worse failure than leaking one: it silently hands the card to a third party.
func (*Lease) Renew ¶
Renew refreshes the heartbeat. A long holder should call this periodically; the reclaim rule requires BOTH a stale heartbeat and an expired window, so missing a few renewals inside the declared window is harmless by design.
THE HEARTBEAT LIVES IN ITS OWN PER-EPOCH FILE, not in the claim record. Renewing by read-modify-writing meta.json is a read-then-write race: if a reclaim and a fresh acquisition land between the read and the write, the OLD holder stamps its stale record over the LIVE one, and the new holder's next Check() then fails while the stale holder carries on — the same shape as the token race that let two parties hold the card. Keying the heartbeat by epoch makes a stale writer harmless: it updates hb.<its own epoch>, which nothing reads any more.
This is only affordable because the heartbeat is now Go-only. Node no longer implements staleness, so the mechanism can change without a cross-language contract.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager binds a resolved state root. Construct with Open, which performs the refuse-to-start validation exactly once.
func ObserverAt ¶
ObserverAt returns a Manager bound to an explicit lease directory, for a verdict path that has the directory and not a Manager (gpuactivity, the fleet node). It does not create or probe anything; its Standing stamps and clears the orphan marker.
func Open ¶
Open resolves and VALIDATES the lease location, then returns a Manager. It returns an error rather than degrading: an unwritable or cloud-synced location is a refuse-to-start condition, never a silent fallback.
func OpenAt ¶
OpenAt is Open with an explicit gpu_lock_path override, so the CLI and the pipeline resolve exactly the directory the render runners will be told to use.
func (*Manager) Acquire ¶
Acquire takes the card, retrying for up to opts.Wait while someone else legitimately holds it. Zero Wait is ONE attempt, still behind every registered waiter that conflicts with this request (the no-wait note below): it is not a bare TryAcquire.
WHY A BOUNDED WAIT AND NOT A SINGLE TRY: the lock this package replaced existed to ORGANIZE concurrent GPU jobs into a serial queue, not to cancel them — a render that arrives thirty seconds into someone else's render should run thirty seconds later, not fail. Trying once turns ordinary contention into a dropped job.
WHY BOUNDED AND NOT THE OLD 30 MINUTES: the caller is usually a single tool call, and a tool call that blocks for half an hour is indistinguishable from a hang. Past the window the honest answer — "held by <class>, <n>s in" — is more useful to an agent that can retry than another twenty minutes of silence.
Only *ErrHeld is retried. An unwritable or cloud-synced lease location is returned immediately: it is a configuration fault, and waiting cannot fix it.
func (*Manager) AdvanceTerm ¶
func (m *Manager) AdvanceTerm(epoch uint64, sig TermSignals) (TermResult, error)
AdvanceTerm runs the term check for one live lease of this directory: nothing while the term runs; at its end, one renewal or the expired label. It writes (under the epoch lock, by restamping the lease's own record) only when something changed, so a holder may call it every tick.
func (*Manager) ApplyCardScopedConfig ¶
ApplyCardScopedConfig is the production entry for the per-host switch (config gpu_card_scoped_leases). Asking for the writer is not enough: a binary or Node reader that predates the format reads a directory holding only device leases as a FREE card, so the writer stays off until the host carries a green reader audit, the marker file reader-audit.json beside the epoch counter. `gpu doctor` is the one writer of that marker, and it writes "green" only when every binary copy (node-swap backups and running images included), media-repo wrapper copy and Node reader it can find understands the per-epoch fence. This turns invariant I7 (audit before any writer) from a convention into a mechanism: no marker, no device lease.
Off, it only switches the writer off. On without a green marker it leaves the writer off and returns an error wrapping ErrReaderAuditMissing that names the marker.
func (*Manager) AwaitHostRAM ¶
func (m *Manager) AwaitHostRAM(epoch uint64, o AwaitHostRAMOptions) error
AwaitHostRAM admits the host RAM a lease asked for after it cleared the seat (Options.HostRAMWaitGiB) and returns nil when the host admitted it, which is also what a lease that waits for nothing answers. It returns the *ErrHostRAM it last had when the Deadline passes (Impossible at once when no state of the box could ever admit the figure), ErrCancelled when Cancel closes, and an error when the lease is gone.
It is the grant's comparison at a later moment, not a looser one. Both figures are put to HostRAMAdmitsLoad with the same host reading, the same headroom and the not-yet-loaded part of every lease that HAS been admitted, and the decision and the stamp that makes the figure the lease's declared need (HostRAMGiB, the field every other grant counts) happen under the epoch lock, so two leases cannot both take the last headroom: the second one's check sees the first one's record. A lease that is still waiting declares nothing, so two of them never wait for each other's figure: whichever the lock serves first is admitted and the other counts it. (A design that kept the figure on the record from the grant on would make each count the other's as still to load, and a host that fits one of them would admit neither.) The cost, stated: while it waits a lease holds no claim on host RAM, so a grant on other cards that fits is admitted ahead of it and the lease then waits for that grant's load.
func (*Manager) CardScoped ¶
CardScoped reports whether this Manager may write card-scoped leases (the per-host switch, after ApplyCardScopedConfig).
func (*Manager) ClaimsOf ¶
ClaimsOf lists the cards (lease ids) whose claim names this epoch. A card lease's release removes its record and then its claims; a release that removed the record and failed on a claim has left the lease half released, and the record being absent does not say so.
func (*Manager) ClearSeatWarmOwed ¶
func (m *Manager) ClearSeatWarmOwed()
ClearSeatWarmOwed removes the marker once the seat has been warmed back.
func (*Manager) ClearSeatWarmOwedIfSeat ¶
ClearSeatWarmOwedIfSeat removes the marker only if it still names seat (compared case-insensitively, as the warm path compares seat names) and reports whether it removed it. It is the clear for a warm-back that failed and then OBSERVED the seat loaded, and it is only as safe as the caller's own guard re-check just before it: the config has one agent seat, so a fresh marker a new lease stamped names the same seat and would match. The compare keeps a marker for another seat; it does not tell this lease's marker from a successor's. A caller that cannot re-check the lease uses ClearSeatWarmOwedIfStale, which does tell them apart.
func (*Manager) ClearSeatWarmOwedIfStale ¶
ClearSeatWarmOwedIfStale is the clear for `gpu status`, which decides from readings it began at readsBegan (the card free of every lease, the seat loaded). It removes the marker only when the marker names seat, was stamped before those readings began, and no lease is live when it removes it; it reports whether it did. A marker stamped after the readings began belongs to a lease the readings cannot speak for, and the readings take as long as the whole activity snapshot (a lease read, a seat read, a GPU sample), not microseconds.
The stamp is whole seconds, so the marker may have been written up to a second after it, and it counts as older only when that second also ended before readsBegan. A marker with no stamp that parses cannot be shown to be older, so it stays. The marker is read again after the lease check and must be the same record, so a lease that took the card, unloaded the seat and stamped a new marker in between is not undone. What remains is the gap between that second read and the remove: a lease would have to take the card, unload the seat over HTTP and stamp inside it. A lost race would cost one skipped warm (the seat then loads on its next request), never a warm landed over a lease.
func (*Manager) DropToken ¶
DropToken forgets a token (the call got its card, or no longer wants it). A malformed id, or one that names nothing, is harmless.
func (*Manager) EmulateLegacyWriter ¶
func (m *Manager) EmulateLegacyWriter()
EmulateLegacyWriter makes this Manager write records as a binary that predates card-scoped leases did: no Format stamp, so a reader sees a LEGACY whole-node record that the evidence rule (infer.go) may scope. It exists for the tests of every consumer of that rule, which have to hold a lease the way the one that prompted it was held; production never calls it.
func (*Manager) EpochIsCurrent ¶
EpochIsCurrent is the package-level EpochIsCurrent under this Manager's seams.
func (*Manager) ExplainHeld ¶
ExplainHeld is ExplainHeld on a Manager (its clock and process table).
func (*Manager) HeldError ¶
HeldError is the refusal for a lease info that a caller of this Manager read as held and is reporting itself (a CLI that must compare the holder's pid before it queues). It is the same error TryAcquire returns, so it says what is wrong with an unhealthy lease and how to free it.
func (*Manager) HostRAMCheck ¶
func (m *Manager) HostRAMCheck(needGiB float64) gpuprobe.HostRAMCheck
HostRAMCheck is HostRAMCheckLoad for a caller that declares one figure, taken for both quantities. It states no commit, so the commit is judged against physical RAM less the headroom (the nearer enforced commit limit, where one sits below it), the line such a caller has always been held to.
func (*Manager) HostRAMCheckLoad ¶
func (m *Manager) HostRAMCheckLoad(need gpuprobe.HostLoad) gpuprobe.HostRAMCheck
HostRAMCheckLoad is the admission rule put to a declaration as it stands right now on THIS node: the host's memory, the leases live now and this Manager's headroom, the sentence a refusal would carry. It is read-only (it takes no lease, registers no waiter, spends no epoch and writes nothing), so a placer can ask whether a lane would be admitted here before it asks the node to take it; the node's own grant stays the authority, because a lease can land between this answer and the grant, and the grant re-checks under the epoch lock. A need that declares nothing is always admitted.
func (*Manager) HostRAMCheckLoadWithout ¶
func (m *Manager) HostRAMCheckLoadWithout(need gpuprobe.HostLoad, epoch uint64) gpuprobe.HostRAMCheck
HostRAMCheckLoadWithout is HostRAMCheckLoad for a load that follows a lease which is about to be released: the lease with that epoch is left out of the not-yet-loaded sum, because its command has exited and it will load nothing more, so counting its declared need as still to come would refuse the very load its release makes room for (the warm-back of a seat is such a load). epoch 0 leaves nothing out.
func (*Manager) HostRAMCheckWithout ¶
func (m *Manager) HostRAMCheckWithout(needGiB float64, epoch uint64) gpuprobe.HostRAMCheck
HostRAMCheckWithout is HostRAMCheckLoadWithout for one figure, taken for both quantities (and, as HostRAMCheck, with no commit stated).
func (*Manager) HostRAMHeadroom ¶
HostRAMHeadroom is the headroom in force for this Manager's grants: its own when set, else the process-wide one (SetDefaultHostRAMHeadroom), else the built-in default.
func (*Manager) HostRAMPending ¶
HostRAMPending is the touched-set half of HostRAMPendingLoad: what the live leases have yet to touch.
func (*Manager) HostRAMPendingCommit ¶
HostRAMPendingCommit is the commit half of HostRAMPendingLoad: what the live leases have yet to be charged.
func (*Manager) HostRAMPendingLoad ¶
HostRAMPendingLoad is pendingLoad over the leases live right now, for the readers that apply the same rule before a grant (the card allocator's pre-filter) or report it (status).
func (*Manager) Inspect ¶
Inspect reports the current lease state. A reclaimable lease reports NOT held. With card-scoped leases it reports the lowest live epoch (see InspectDir); InspectFor and Leases narrow it.
func (*Manager) InspectDetail ¶
InspectDetail is InspectDirDetail under this Manager's clock and process table.
func (*Manager) InspectFor ¶
InspectFor is Inspect narrowed to a request: the live lease that conflicts with a caller wanting devices (empty = the whole node, which any live lease conflicts with).
func (*Manager) Leases ¶
Leases lists every live lease under this Manager's clock and process table.
func (*Manager) LeaveToken ¶
LeaveToken records that a call gave up its wait still wanting a card, and returns the token that names its place. since is when the call first joined the line (a call that resumed a token passes the arrival time it resumed with, so every give-up keeps the original place). opts.ResumeToken, when it is a well-formed id, is reused: the caller keeps one name for its place across re-calls. opts.Devices is the set it wants (empty = the whole node).
func (*Manager) MarkHolderGaveUp ¶
MarkHolderGaveUp records on the lease's record that its hidden holder gave up releasing it, and why (best effort, by a holder that is about to exit with the lease still held).
func (*Manager) MarkSeatWarmOwed ¶
MarkSeatWarmOwed records that seat was unloaded for a lease and is owed a warm by the last holder to release.
func (*Manager) MarkSeatWarmOwedAt ¶
MarkSeatWarmOwedAt is MarkSeatWarmOwed with the time of the stamp given. The stamp is kept in whole seconds (RFC 3339, UTC), which is the resolution ClearSeatWarmOwedIfStale reasons with.
func (*Manager) MarkToken ¶
MarkToken is TouchToken that also records what the call is waiting for (Token.WaitingFor): WaitHostRAM when its last reading of the lane found only host RAM in the way, "" for anything else. Same rules as a touch: it refreshes a token that exists and never writes one.
func (*Manager) NewYieldAsker ¶
func (m *Manager) NewYieldAsker(epoch uint64) *YieldAsker
NewYieldAsker binds the decision to one lease of this directory, held by this process.
func (*Manager) ObserveOwner ¶
func (m *Manager) ObserveOwner(info Info) (OwnerState, time.Time)
ObserveOwner judges the owner of one live lease and keeps its orphan marker honest. The FIRST observer to see the owner gone stamps the marker, under the epoch lock with a second look inside it, so concurrent readers write one marker and agree on one moment; the marker is what makes "gone for 23 minutes" a fact any later reader shares rather than a clock each reader starts for itself. An owner seen alive again clears the marker, so a session that came back (a resume that took a minute) starts its grace afresh if it goes again. A reader that cannot take the lock reports the owner's state and an unstamped moment (now): it never fails a status call (see Standing.OrphanMarkErr for how it says so).
This is one of the writers in the read path, and it writes a sidecar only. WHO calls it matters: only the status surfaces (`gpu status`, offload_status, the fleet health) stamp. The plain inspectors the text gate polls every blocked second, and the sentences a waiter or a refusal reads (ExplainHeld, ErrHeld.Error), use peekOwner and stay read-only.
func (*Manager) OwnerState ¶
func (m *Manager) OwnerState(o *Owner) OwnerState
OwnerState judges an owner. Alive when any live registered process carries the session, or the recorded process is alive; gone when the owner could be tracked and nothing of it is alive; unknown when it could not be tracked (no entry ever, no pid) or the registry could not be read; remote for a lease asked for from another host.
func (*Manager) QuarantinedCards ¶
QuarantinedCards reads the `quarantine.<id>` sidecars beside the lease record: cards whose previous holder's process tree could not be stopped, which the allocator never hands out. Plan P12 writes them and clears them as observation shows the tree gone; until then the sidecars are only ever read.
func (*Manager) QueuePosition ¶
QueuePosition is where a request for devices (empty = the whole node) that joined the line at since stands: 1 plus the waiters and live tokens that arrived before it and want any of the same cards. exclude names a token that is the caller's own (never counted).
func (*Manager) ReadOnly ¶
ReadOnly returns a view of the same lease root whose readers of the line write nothing. Those readers (Waiters, Tokens, ResumeToken) prune a record they find dead, stale or expired, as housekeeping for whoever reads next; through the view they skip such a record exactly as before and leave it on disk. It is for a question that must not change the state it asks about (the media lane probe, internal/pipeline/medialane.go): a helper that reads the line through the view, gpualloc's included, prunes nothing. The view shares the root, the clock and the seams of m, and it does not stop an acquisition or a release made through it, which are not reads and which the probe never makes.
func (*Manager) ReaderAuditPath ¶
ReaderAuditPath is where the marker lives (for the doctor's output).
func (*Manager) ReaderAuditResult ¶
ReaderAuditResult is the marker's verdict for display: "green", "red", "absent" or "unreadable".
func (*Manager) RecordState ¶
func (m *Manager) RecordState(epoch uint64) (RecordState, error)
RecordState looks at the record of lease epoch directly (not through the reader, which treats a record it cannot read as absent): absent, held, or unreadable, with the cause for the last.
func (*Manager) RecordYieldAction ¶
RecordYieldAction updates the sidecar of an epoch that was asked with what the holder did about it. It takes the epoch lock and checks the lease is still live, like the ask: an update that races the release leaves no file behind. An epoch that was never asked has nothing to update and is left alone; a request file that exists and cannot be read is an error.
func (*Manager) ReleaseByEpoch ¶
ReleaseByEpoch drops the CURRENT lease from a process that does not hold it (the `gpu release` verb). Passing a non-zero epoch makes it a compare-and-delete: the lease is removed only if it is still the one the caller saw. Zero means "release whatever is there", which is the operator's explicit override.
A detached holder notices its lease vanish on its next Check() and exits on its own, so releasing never has to kill a process by pid — which would be unsafe under pid recycling.
func (*Manager) ReleaseTarget ¶
ReleaseTarget names the lease ReleaseByEpoch(epoch) would end, without ending it, or the refusal ReleaseByEpoch would return. It is the question a caller asks BEFORE doing anything destructive on a lease's behalf (`gpu release` stops the ComfyUI instances kept under the lease, and must not when the release is going to be refused): act on the epoch returned, never on a guess of your own at what "whatever is held" means.
The rule is ReleaseByEpoch's, step for step: a named epoch is that lease (a card lease by its record, a whole-node lease when it is the current one, else the "moved on" refusal); epoch 0 is the whole-node lease if one is recorded, else the only live card lease, and with several card leases live it is the refusal that asks for --epoch. 0 with a nil error means nothing is held (or the named epoch is not): there is nothing to end. It reads and never writes.
func (*Manager) Restamp ¶
Restamp rewrites the CURRENT lease record in place: the holder changing its own flags mid-hold (draining -> exclusive once the drain completes, 0.117.0). It runs under the epoch lock, refuses when the record's epoch is not the caller's (fenced out — the record is someone else's now), and replaces the file atomically, so a reader never sees a torn record and the claim never stops existing (a concurrent TryAcquire still meets an existing file). The epoch itself is never moved by this path.
func (*Manager) ResumeToken ¶
ResumeToken finds a token that can still be resumed: its poller left no more than TokenTTL ago. It does not consume it; registering a waiter that resumes it does. A malformed id, an id that names no token and an expired token all answer false: the call is then a new arrival, never an error.
func (*Manager) Root ¶
Root is the resolved state root (for diagnostics and for threading to the Node side as GPU_LEASE_DIR).
func (*Manager) SeatWarmOwed ¶
SeatWarmOwed reports the seat a warm is owed to, or "" when none is.
func (*Manager) SetCardScoped ¶
SetCardScoped turns the device-scoped WRITER on or off for this Manager. It is the raw switch and checks nothing: production callers go through ApplyCardScopedConfig.
func (*Manager) SetHostRAMHeadroom ¶
SetHostRAMHeadroom gives THIS Manager a headroom of its own, over the installed one. A test seam: production leaves it unset and every grant reads the process-wide value config.Load installed. Zero or negative means the process-wide value.
func (*Manager) StampHostRAMHold ¶
StampHostRAMHold puts the moment a host-RAM wait ends on the record of lease epoch (Meta.HostRAMHoldUntilMs). It does it only while the lease still asks for the host: on an admitted lease the stamp would be a bound nothing is running.
func (*Manager) StampHostRAMHoldPhase ¶
StampHostRAMHoldPhase is StampHostRAMHold saying which phase the stamped moment is.
func (*Manager) Standing ¶
Standing derives the standing of one live lease. It stamps or clears the orphan marker (ObserveOwner), so call it from a status surface (`gpu status`, offload_status, the fleet health), never from a poll or a message that must stay read-only (StandingReadOnly). grace <= 0 means the installed grace, else DefaultOrphanGrace.
func (*Manager) StandingAll ¶
StandingAll is the standing of everything an Info describes. With card-scoped leases several are live at once and Info is the lowest epoch's: a node that published only that one would hide a stalled lease behind a healthy sibling. The result carries the flags of every lease (orphaned, overdue and stalled are each true if true of ANY of them) and the detail of the most escalated one.
func (*Manager) StandingReadOnly ¶
StandingReadOnly is Standing for a caller that must not write: it reads the orphan marker a status surface recorded and never stamps or clears one, and it never takes the epoch lock. A gone owner nobody has recorded yet reads as first seen now, inside its grace.
func (*Manager) TokenLive ¶
TokenLive reports whether a token still holds its place in line: its poller left within the grace. A token past it is absent: every waiter skips it.
func (*Manager) Tokens ¶
Tokens lists the places in line that can still be resumed (not past TokenTTL since their last poll), oldest arrival first. Expired and unreadable records are removed as they are read. A token inside its grace holds its place; one past it is listed but skipped for ordering (tokenLive).
func (*Manager) TouchToken ¶
TouchToken records that the call holding token id is still here, so the place keeps holding against later callers: a call that resumed a place and then WAITS (in-process, for the card's slot) polls nothing, and a token's life is its last poll. It refreshes a token that still exists and never writes one: a token that was dropped (served, or consumed by a waiter), pruned or never existed answers false and stays gone. The arrival time is untouched. Callers join whatever repeats it before they drop the token, so a touch cannot bring a spent place back.
func (*Manager) TryAcquire ¶
TryAcquire attempts to take the card once. It returns *ErrHeld when someone else legitimately holds it, so the caller can report a real ETA instead of a bare error.
IT BYPASSES THE WAITER QUEUE: it neither registers nor consults the line, so on a card that is free it wins ahead of every registered waiter, however long they have stood there. That is the defect register D-1xx-3 closed for every production claim (Acquire, with or without a Wait, is the gated door). TryAcquire is for setup and tests, and for Acquire's own gated attempt, which has already checked the line; a production path that wants the card calls Acquire.
func (*Manager) VetGrant ¶
VetGrant puts opts.GrantCheck to a lease that has just been granted. A nil check is nil. A check that returns an error refuses the grant: the lease is released and the error is ErrGrantRefused, so the cards are free again for the next in line; a release that itself fails is reported as such and is NOT an ErrGrantRefused, because the cards are then still held and the caller must not go on as if they were free.
WHY THIS EXISTS: a request queued on the display card was decided against the rule for that card at ENQUEUE (the presence guard and the desktop floor until A-RAM-15, the card's cap and the VRAM in use since, and from 2026-11-07 the card's idle gate as well). FIFO can take hours; the operator may have closed the card, or a game may have taken its memory, by the time the front of the line is reached. Nothing re-asked, so the queue handed the screen's card to a job the rule would now refuse.
WHY AFTER THE GRANT AND NOT BEFORE IT: a check made before the claim has to know that the cards are free, and a lease that is mid-release reads as held for an instant and is then claimable, so a pre-check can be skipped by exactly the grant it was meant to vet (seen in test). Checking what the request already holds has no such window; the cost is a claim that is taken and given back, which the next waiter sees as one more poll tick. The check therefore sees its own claim on the cards and must not read it as a rival's.
func (*Manager) Waiters ¶
Waiters lists the processes queued for the card, oldest first. Records whose process is gone, whose pid was recycled, or which have not been refreshed within waiterStaleWindow (an alive process that has stopped actually polling — suspended, wedged, an old binary that never refreshes at all) are pruned as they are read, so neither a dead waiter nor a merely stalled one ever blocks the line or defers a warm forever.
TRANSIENT read/stat failures NEVER prune. Confirmed-gone (os.IsNotExist) does; a retry-exhausted transient error is treated as "skip this entry for THIS read only, try again next time" — reproduced directly (2026-09-22): treating any os.Stat error as "prune it" made a live, correctly-refreshing waiter's record vanish PERMANENTLY the one time its owner's rename and another goroutine's Stat overlapped, which is ordinary traffic once every waiter is reading every other waiter's file every poll tick.
func (*Manager) WriteReaderAudit ¶
func (m *Manager) WriteReaderAudit(r AuditReport) error
WriteReaderAudit records the audit's verdict as the reader-audit marker that ApplyCardScopedConfig reads. A report that is not green writes a RED marker: a stale green left from an earlier audit must not survive a newer binary appearing.
func (*Manager) YieldOf ¶
func (m *Manager) YieldOf(epoch uint64) (YieldRequest, bool)
YieldOf is ReadYield on a Manager.
func (*Manager) YieldViewOf ¶
YieldViewOf reads the request state of one lease without writing anything. It is for a lease whose holder is alive: a tree-orphan has nobody to ask, and its callers do not call this for one.
type Marker ¶
Marker is the ComfyUI launch marker (render/comfy-ownership.mjs, .offload-launch.json): the python pid, the node process that spawned it, when, and the exact argv it was given.
type Meta ¶
type Meta struct {
Epoch uint64 `json:"epoch"`
Class Class `json:"class"`
Holder Holder `json:"holder"`
JobID string `json:"job_id,omitempty"`
Origin string `json:"origin,omitempty"`
Reason string `json:"reason,omitempty"`
AcquiredAtMs int64 `json:"acquired_at_ms"`
// ExpiresAtMs is stamped by the ACQUIRER from its own declared duration. It is
// half of the reclaim conjunction: a heartbeat gap alone must never reclaim a
// lease whose owner declared a long, still-unexpired window.
ExpiresAtMs int64 `json:"expires_at_ms"`
// RenewedAtMs is the heartbeat. A detached holder is a PROXY process, so pid
// liveness cannot detect a benchmark that died behind it — hence the heartbeat.
RenewedAtMs int64 `json:"renewed_at_ms"`
// Exclusive (0.115.2) is stamped by a TEXT holder that cleared the cards for
// itself (`gpu reserve --drain --unload-seat`, or an explicit --exclusive). It
// tells the text-load admission gate that a model pulled onto these cards would
// land ON TOP of a measurement — the residency switch that voided two 5070 Ti
// runs — so such loads wait or route elsewhere for the lease's length. A plain
// text lease (the holder unloaded nothing) keeps the old, ungated behaviour.
Exclusive bool `json:"exclusive,omitempty"`
// Draining (0.117.0, register D-93) is stamped by a holder that is waiting for
// the seat's in-flight work to finish before it touches the cards (`gpu reserve
// --drain`). It CORDONS the seat: no NEW agent run is admitted while it is set
// (modelaffinity.BlocksNewRun), while the requests of runs already in flight
// keep flowing. The exclusive stamp — which blocks every admission — is applied
// only once the drain has completed (Restamp); stamping it at acquire made the
// drain block the very run it was waiting for (2026-09-14).
Draining bool `json:"draining,omitempty"`
// Command (0.117.0) is what the wrapper form runs under the lease (the wrapped
// argv, clipped), so a reader of `gpu status` sees WHAT holds the cards, not
// only who.
Command string `json:"command,omitempty"`
// HostRAMGiB is the host RAM the holder declared it will load (hostram.go): what the grant
// admitted it against, and what a later grant counts as still to load until the holder's processes
// hold it. Additive and omitempty: a record without it declares nothing, which every reader
// (including a binary that predates the field, which ignores it) takes to mean "adds no host RAM".
HostRAMGiB float64 `json:"host_ram_gib,omitempty"`
// HostRAMCommitGiB is the commit the holder stated it will be charged (hostram.go), beside the working set HostRAMGiB
// it will touch: the grant admits the first against the available memory and this against the OS commit limit. 0 or absent
// = nothing stated: the same figure as HostRAMGiB, admitted against physical RAM less the headroom (a record from before the
// field, and a holder that declared one figure). Present, it is stated even when equal to HostRAMGiB. Additive and
// omitempty: an older reader ignores it and judges the lease by HostRAMGiB alone.
HostRAMCommitGiB float64 `json:"host_ram_commit_gib,omitempty"`
// HostRAMWaitGiB (F82) is host RAM the holder will ask the host for AFTER it has cleared the agent seat
// (`gpu reserve --unload-seat`): the grant took the cards without comparing it to the host, because the
// memory it waits for is held by the seat its own unload frees. It is not a claim. HostRAMGiB stays 0, so
// no other grant counts it as still to load, until Manager.AwaitHostRAM admits it: that check and the move
// of the figure into HostRAMGiB (and the clearing of this field) are one critical section under the epoch
// lock, the same admission rule at the same point in every other lease's view. Additive and omitempty:
// an older reader ignores it and reads a lease that declares nothing yet.
HostRAMWaitGiB float64 `json:"host_ram_wait_gib,omitempty"`
// HostRAMWaitCommitGiB is the commit twin of HostRAMWaitGiB: the commit the holder will ask the host for after the seat is
// cleared. AwaitHostRAM moves it into HostRAMCommitGiB in the same critical section that moves HostRAMWaitGiB into HostRAMGiB.
// 0 or absent = the same figure as HostRAMWaitGiB. Additive and omitempty.
HostRAMWaitCommitGiB float64 `json:"host_ram_wait_commit_gib,omitempty"`
// HostRAMHoldUntilMs (F82 hold bound) is when the hold bound ends the wait of a lease that holds its cards while the
// host is asked for HostRAMWaitGiB: unix milliseconds, stamped when that wait begins and taken off only by admission (a
// wait that ends any other way leaves it: a lease that still asks for the host must carry a moment by which somebody
// releases it). 0 = no bound is known (the wait has not begun, or the bound is off and --wait alone ends it). It is what
// `gpu status` reads to say when the lease will be released, and what the lease's hidden holder acts on if the reserve that
// took it never releases it, since the bound can be a flag on one reserve and no other process sees that. Additive and
// omitempty: an older reader ignores it.
HostRAMHoldUntilMs int64 `json:"host_ram_hold_until_ms,omitempty"`
// HostRAMHoldPhase says which moment HostRAMHoldUntilMs is: "outer" (a detached reserve's bound while it still clears the seat; the
// host has not been asked), "wait" (the end of the wait for the host) or "release" (the reserve is releasing the lease and pushed
// the stamp out). Empty = a stamp an older writer made, which was always the wait's. Taken off with the stamp by admission.
// Additive and omitempty: an older reader ignores it.
HostRAMHoldPhase string `json:"host_ram_hold_phase,omitempty"`
// HolderGaveUpMs is when the lease's hidden holder gave up releasing it (unix milliseconds; 0 = it has not), and
// HolderGaveUpWhy the clipped reason. Written best effort by a holder whose own release failed after its retries and which then
// exits: from then on nothing polls the lease, and `gpu status` says so instead of promising a release at "its next poll".
// Additive and omitempty: an older reader ignores both.
HolderGaveUpMs int64 `json:"holder_gave_up_ms,omitempty"`
HolderGaveUpWhy string `json:"holder_gave_up_why,omitempty"`
// Devices are the GPU UUIDs this lease claims. Empty = the whole node.
Devices []string `json:"devices,omitempty"`
// Group labels leases taken together for one job; informational.
Group string `json:"group,omitempty"`
// WrapperVersion is the build of the process that holds the lease.
WrapperVersion string `json:"wrapper_version,omitempty"`
// State is "granting" while a v2 grant is in flight under the epoch lock and
// "active" once every card claim exists. Empty on a whole-node record. It is the
// FENCE's word and nothing else: whether the lease's term was renewed is Expired
// below, never a third State, because a reader that predates terms (checkV2,
// render/gpu-lock.mjs) fences out any state but "active".
State string `json:"state,omitempty"`
// TermMs is the renewal term: how far a renewal moves the declared end. It is the
// request capped at the installed gpu_max_term (24 h with a progress contract), never
// more than the declared window.
TermMs int64 `json:"term_ms,omitempty"`
// RequestedMs is the window the caller asked for when that is above the cap on a term.
// The declared window (ExpiresAtMs) is still the whole request: a request is
// recorded, warned about and accepted, never shortened. Zero when the request was at or
// under the cap.
RequestedMs int64 `json:"requested_ms,omitempty"`
// MaxTotalMs is how long after AcquiredAtMs the lease may be renewed at all (gpu_max_total,
// never less than the declared window). Past it a lease that is still held reads
// overdue however healthy its owner and progress look; it is still not freed.
MaxTotalMs int64 `json:"max_total_ms,omitempty"`
// Expired is stamped by the holder's own tick when the lease's term ended and was NOT
// renewed (term.go). It is a LABEL: the heartbeat goes on, the claim stays, the lease is
// still fenced and still current, and a later tick that finds the term renewable again
// clears it. Nothing is freed or killed by it.
Expired bool `json:"expired,omitempty"`
// ExpiredWhy is the sentence behind Expired, recorded with it.
ExpiredWhy string `json:"expired_why,omitempty"`
// Owner is who asked for the lease (a session, a process, or a remote host).
Owner *Owner `json:"owner,omitempty"`
// Unattended: nobody is expected at the desk; the lease is judged by its progress
// contract and its window, never by whether its owner is still around.
Unattended bool `json:"unattended,omitempty"`
// Progress is the progress contract: a file the job appends to and the window in
// which it must move.
Progress *Progress `json:"progress,omitempty"`
// YieldGraceMs and OnYield are the job's own terms for being asked to stop (how long
// it needs, and the command that makes it stop at a clean boundary). The HOLDER reads
// them: when it is asked to yield (yield.go) it runs its own copy of OnYield, once. No
// takeover command exists that reads them.
YieldGraceMs int64 `json:"yield_grace_ms,omitempty"`
OnYield string `json:"on_yield,omitempty"`
// OnYieldDir is the working directory of the process that took the lease, recorded
// with OnYield: a reader that looks at the record later does not share it, and a
// relative command ("touch work/STOP") means a different file from another directory.
// The holder that runs the command is the process that recorded it, so it runs it in its own.
OnYieldDir string `json:"on_yield_dir,omitempty"`
// Yields is stamped by a holder that runs the yield request (yield.go): "wrapper" for the
// `gpu reserve -- <command>` form and "detached" for the hidden holder of --detach. A record
// without it was written by a build from before the request, or by a holder that never ticks it
// (the media pipeline acquires in process), so no request can be made of its holder.
Yields string `json:"yields,omitempty"`
// Format is the record format of the binary that WROTE the record (RecordFormat). A
// record without it was written by a binary that predates card-scoped leases: it cannot
// declare cards, so a reader may INFER what it holds (infer.go). A record that carries it
// is a statement by a binary that could have declared cards, so a whole-node record
// carrying it means the whole node and is never narrowed by inference.
Format int `json:"format,omitempty"`
// Tree is the process tree the wrapper started, recorded by the wrapper (plan P10): pid and
// start identity of each member, rewritten when the set changes. See tree.go.
Tree []TreeMember `json:"tree,omitempty"`
// contains filtered or unexported fields
}
Meta is the on-disk lease record (<root>/gpu/lease/meta.json).
type NoCardsError ¶
type NoCardsError struct {
Want int
Have int
Skipped []Skip
// HostReason is set when the HOST (RAM headroom), not the cards, is what is short.
HostReason string
// HostImpossible: the host's memory could never admit the declared need however long a caller
// waits (HostReason says so). Waiting does not help, so a caller that would poll returns instead.
HostImpossible bool
// Waitable lists, in allocation order, the cards a queued request can be given: the
// cards that are free right now first, then the cards skipped ONLY because a live
// lease claims them (and that would otherwise fit). A caller that must wait queues
// FIFO on the first Min of them, so an idle card is held as part of the set instead
// of being thrown away while the request waits for busy ones. A card skipped for
// any other reason (display, quarantine, foreign process, VRAM) is never listed:
// waiting does not fix it.
Waitable []string
}
NoCardsError says no allocation of at least Min cards exists right now. It carries the reasons, so a caller can print them and decide whether waiting can help.
func (*NoCardsError) Error ¶
func (e *NoCardsError) Error() string
type OnOverdue ¶
type OnOverdue string
OnOverdue is the policy for a lease that outlived its window while someone waits for its cards (config gpu_on_overdue).
const ( // OnOverdueUnset: the key is not set. The harness behaves as it did before the request existed: // nobody is asked. OnOverdueUnset OnOverdue = "" // OnOverdueHold: the holder is never asked; the lease is held until its holder ends it. OnOverdueHold OnOverdue = "hold" // OnOverdueRequest: the holder is asked to yield and runs the job's own recorded on_yield. OnOverdueRequest OnOverdue = "request" )
func InstalledOnOverdue ¶
func InstalledOnOverdue() OnOverdue
InstalledOnOverdue is the policy in force.
func ParseOnOverdue ¶
ParseOnOverdue reads a configured policy. Matching trims and lower-cases, as the other policy validators do. A value that is neither request nor hold is an error naming both, and comes back as hold: the permissive direction is never the fallback.
type Options ¶
type Options struct {
Reason string
Origin string
JobID string
// TTL is how long the holder declares it will need the card. Stamped into
// ExpiresAtMs. Zero uses DefaultTTL.
TTL time.Duration
// Wait is how long Acquire keeps retrying while the card is legitimately held by
// someone else. Zero means try exactly once. Only contention is waited out; a
// configuration fault is returned immediately, because waiting cannot fix it.
Wait time.Duration
// Exclusive stamps Meta.Exclusive on a TEXT lease: the holder is clearing the
// cards and the text-load gate must keep them clear. Ignored for media, whose
// holder already blocks loads by class.
Exclusive bool
// WaitOut keeps Acquire polling for the whole Wait even when a TEXT holder's
// declared window outlasts it. The short-circuit in Acquire is right for a tool
// call with a 90 s budget, and wrong for a caller that would otherwise give the
// job up: a declared window is a ceiling the holder usually releases before —
// the wrapper form releases the moment its command ends. Measured live
// 2026-09-09: a `gpu reserve --wait 2m` behind a `--for 3m` holder was refused
// at once, and the holder released six seconds later.
WaitOut bool
// Draining stamps Meta.Draining (see Meta.Draining). Both classes: a media
// holder that drains (`gpu reserve --class media --drain`) must let the runs
// in flight finish exactly as a text holder does. Until 2026-09-22 the stamp
// was dropped on a media lease, so the media class fenced those runs from
// acquire and the drain waited on work it was itself blocking.
Draining bool
// Command is recorded as Meta.Command (clipped to commandClip runes).
Command string
// HostRAMGiB is the host RAM the holder declares it will touch: its working set (stamped as Meta.HostRAMGiB). The
// grant is admitted against it (hostram.go): the available RAM less this and what leases already granted have yet
// to touch must stay at or above the headroom (and see HostRAMCommitGiB for the commit side). 0 declares
// nothing and is never read against the host. The callers resolve it: an explicit `gpu reserve
// --ram`, else an estimate from the model files of the render call, else a class default
// (internal/hostneed).
HostRAMGiB float64
// HostRAMCommitGiB is the commit the holder STATES it will be charged (stamped as Meta.HostRAMCommitGiB), admitted against the
// OS commit limit where the OS enforces one. 0 = nothing stated: the commit is the same figure as HostRAMGiB and is admitted
// against physical RAM less the headroom, the line a caller that declares one figure has always been held to. Above 0 it is
// stated, even when it equals HostRAMGiB. The two differ for a job that commits more than it touches (a process tree measured
// at 27.8 GiB touched and 58.1 GiB charged), and a stated commit is how such a job is judged on what it measured. A job whose
// commit is smaller than its working set (mapped files count in the working set and not in the commit) cannot say so by leaving
// this at 0, which reads as the touched figure; a commit stated below the working set is taken as stated.
HostRAMCommitGiB float64
// OnHostRAMWait, when set, is called ONCE per Acquire, at the first refusal on host-RAM grounds
// of a request that will keep waiting (Wait > 0): the CLI prints the "waiting for host RAM" line
// from it. Once, because a line per poll is a notification per second in the session that wraps
// the reserve.
OnHostRAMWait func(*ErrHostRAM)
// HostRAMWaitGiB (F82) is host RAM the holder will ask for after it has cleared the agent seat itself, for a lease
// that unloads the seat (`gpu reserve --unload-seat`): the grant neither compares it to the host nor declares it
// (HostRAMGiB is 0 for it), because the memory it would wait for is held by the seat the lease's own unload frees.
// It is stamped on the record (Meta.HostRAMWaitGiB) and admitted afterwards by Manager.AwaitHostRAM, by the one
// rule, while the cards are still held. A caller sets either this or HostRAMGiB, not both: HostRAMGiB wins (the
// grant admits it as always) and this is then ignored.
HostRAMWaitGiB float64
// HostRAMWaitCommitGiB is the commit twin of HostRAMWaitGiB (0 = the same figure, nothing stated; above 0 it is stated).
HostRAMWaitCommitGiB float64
// Devices names the cards the lease holds, by GPU UUID (plan invariant I2). Empty
// is a WHOLE-NODE lease, the only kind that existed before record v2. A non-empty
// set writes a v2 lease (per-card claims) and is refused unless the host has
// enabled card-scoped leases (Manager.SetCardScoped).
Devices []string
// Group names a set of leases taken for one job (a fan-out batch); informational.
Group string
// WrapperVersion is the build that holds the lease. Whether the holder honours a yield
// request is Yields, not this: every 0.18x build stamps a version and none of the older
// ones ticks the request.
WrapperVersion string
// Owner is who asked for the lease; the zero Owner records none (unknown).
Owner Owner
// Unattended declares that nobody is expected at the desk. It requires a declared
// TTL and a progress contract (ProgressFile and Stall), or the acquisition is refused
// (ErrUnattendedContract).
Unattended bool
// ProgressFile and Stall are the progress contract: the file the job appends to and
// how long it may go without that file moving. Both or neither.
ProgressFile string
Stall time.Duration
// YieldGrace and OnYield are the job's terms for being asked to stop; recorded on the
// lease, and run by the holder when it is asked to yield (yield.go).
YieldGrace time.Duration
OnYield string
// Yields says this holder runs the yield request (YieldsWrapper or YieldsDetached); it is
// stamped on the record. Leave it empty for a holder that never ticks the request.
Yields string
// QueuedSince, when set, is the arrival time the waiter this call registers carries instead
// of now: a call that is handed a place in line keeps the position that place had.
QueuedSince time.Time
// ResumeToken names a place-keeping token (tokens.go) this call resumes. If the token can
// still be resumed the waiter carries its original arrival time and the token is consumed;
// if not, the call is a new arrival. LeaveToken reuses the id, so a caller keeps one name for
// its place across re-calls.
ResumeToken string
// MaxTerm and MaxTotal override the installed term limits (config gpu_max_term_min and
// gpu_max_total_min, SetDefaultTerms) for this acquisition; zero means the installed
// value. See PlanTerm for what each one bounds. Neither shortens the window asked for.
MaxTerm time.Duration
MaxTotal time.Duration
// GrantCheck, when set, is asked of a QUEUED acquire at the moment the cards are granted to it
// (VetGrant): an error gives the grant back and ends the wait with ErrGrantRefused instead of
// handing the cards over. It is how a caller whose admission rested on readings that can change
// while it waits (the display card's cap and the VRAM in use on it) re-asks them at
// the grant and not only at the enqueue. It runs with the cards already claimed by this request,
// so a reader of the lease directory sees its own claim.
GrantCheck func() error
// Cancel, when closed, ends a queued Acquire at its next poll with ErrCancelled: the waiter record leaves the line
// through Acquire's own defer and nothing is claimed. It is for a caller that is told to stop while it stands in
// line (the `gpu reserve` wrapper on a console close or a kill, which may stand there for --wait 8h): without it
// the only way out of the wait was to end the process and leave its record in the line for a later reader to
// prune. nil = never. It is checked before the waiter registers and before every attempt, so a request cancelled
// before it began asks for nothing, even on a free card; a lease already granted when it closes is returned and
// is the caller's to release.
Cancel <-chan struct{}
}
Options configure an acquisition.
type Owner ¶
type Owner struct {
// Session is the session id (LOCAL_OFFLOAD_ORIGIN or CLAUDE_CODE_SESSION_ID).
Session string `json:"session,omitempty"`
// PID and StartMs identify one process by pid and start identity (the same pair a
// lease holder is judged by), so a recycled pid reads as gone.
PID int `json:"pid,omitempty"`
StartMs int64 `json:"start_ms,omitempty"`
// Remote marks a lease asked for from another host. Its owner cannot be probed from
// here, so it is treated as unattended (its progress contract is what judges it).
Remote bool `json:"remote,omitempty"`
// Tracked records that the session was in the registry when the lease was taken. A
// session that was tracked and now has no live registered process is GONE; one that
// never was (an MCP server that predates the registry) is UNKNOWN, never orphaned.
Tracked bool `json:"tracked,omitempty"`
}
Owner names who asked for a lease. The zero Owner is "unknown".
func ResolveOwner ¶
ResolveOwner builds the owner of a lease from what a caller said and what the environment says. Flags win: an explicit session or process is the caller naming its owner (a launcher that detaches before the lease is taken must, or the owner is lost). The environment supplies only a SESSION (envSession, resolved by the caller through the ledger's process origin), never a pid: the process a wrapper happens to be run from is usually a short-lived shell, and recording it would read every lease as abandoned the moment the shell exits. With neither, the owner is unknown.
type OwnerState ¶
type OwnerState string
OwnerState is what the registry and the recorded process say about an owner.
const ( OwnerAlive OwnerState = "alive" OwnerGone OwnerState = "gone" OwnerUnknown OwnerState = "unknown" OwnerRemote OwnerState = "remote" )
type ProcImage ¶
type ProcImage struct {
PID int
Path string
// ReadPath is what to open to read the image (on Linux /proc/<pid>/exe, which reads
// a replaced or deleted binary too). Empty = Path.
ReadPath string
// Why is what made it interesting: "harness process", "lease holder", "waiter".
Why string
}
ProcImage is the image of one running process worth auditing.
func RunningImages ¶
RunningImages lists the image of every running process for which want returns a non-empty reason (see the Windows variant). The image is read through /proc/<pid>/exe, which opens a binary that was replaced or deleted after the process started: that is exactly the copy that matters.
type Progress ¶
Progress is a lease's progress contract: the file the job appends to as it works and how long it may go without that file moving before the lease reads as stalled.
type ProgressView ¶
type ProgressView struct {
// Declared: the lease carries a progress contract.
Declared bool
File string
// State is advancing, stalled or unknown (the file is missing or unreadable). A missing
// file is UNKNOWN, never stalled: the job may not have written its first line yet, and
// a status call must not invent a stall.
State string
// Age is how long since the last sign of life: the later of the file's modification
// and the lease's acquisition. Counting from the lease's start at the earliest means a
// log left over from an earlier run does not make a fresh lease read as stalled, and
// it is why the surfaces say "last activity", not "last moved".
Age time.Duration
Stall time.Duration
Detail string
// Problem says why State is unknown: "does not exist", "is a directory, not a file" or
// "cannot be read: <error>" (a permission error and the rest are not "not written yet").
Problem string
// PastStall: the file is still unknown (missing or unreadable) after the lease has outlived
// its stall window. The verdict does not change (unknown is never stalled); the reading
// says so, because by then a wrong path is as likely as a slow job.
PastStall bool
}
ProgressView is the reading of a lease's progress contract.
type RecordState ¶
type RecordState int
RecordState is what the record of one lease epoch says about whether that lease is held, as far as a release can tell.
const ( // RecordAbsent: no record of this epoch (a card lease's e/<epoch>.json, or a whole-node meta.json naming it) exists. Gone. RecordAbsent RecordState = iota // RecordHeld: the record exists and could be read. RecordHeld // RecordUnreadable: the record exists, or may exist, and could not be read (an access error while it is replaced, a sharing // violation, an I/O error, a directory where the file was). The lease is HELD for every decision that matters: never gone. RecordUnreadable )
func (RecordState) String ¶
func (s RecordState) String() string
type RecordUnreadableError ¶
RecordUnreadableError is what Lease.Check answers when the lease's record exists as far as anyone knows and could not be READ (an access error while it is replaced, a sharing violation, an I/O error): not "the lease is gone" and not "fenced out", which are verdicts, but a failure that may pass. A caller that would let go of its lease on a failed fence can tell the two apart.
func (*RecordUnreadableError) Error ¶
func (e *RecordUnreadableError) Error() string
func (*RecordUnreadableError) Unwrap ¶
func (e *RecordUnreadableError) Unwrap() error
type Repin ¶
type Repin struct {
// Var is the variable that is rewritten: "COMFY_CUDA_DEVICE" or "COMFY_CARD_UUID".
Var string
// Old is the value the command carried (whitespace trimmed); New is the value it starts with.
Old, New string
// From are the lease ids the old pin named, empty when it could not be resolved (see Unresolved).
From []string
// To are the held cards the new pin names.
To []string
// Unresolved is the reason the old pin named no card, when it named none.
Unresolved error
}
Repin is one environment pin of a command that moves onto the cards its lease holds.
type RepinPlan ¶
type RepinPlan struct {
// Repins are the pins to rewrite, in the order the variables are listed above.
Repins []Repin
// NotMoved says, for each pin that is outside the lease but cannot be moved, why not.
NotMoved []string
// Inside lists the variables whose pin was read in the child's order and found inside the lease.
Inside []string
}
RepinPlan is what PlanRepin decided about a command's own environment pins.
func PlanRepin ¶
PlanRepin decides which of the command's own environment pins sit outside held (or cannot be told to sit inside) and what each becomes. pci is the order a device index is read in by the child (ReadsPCIOrder, or true when the wrapper itself sets CUDA_DEVICE_ORDER=PCI_BUS_ID for the child). A blank value is no pin: a uuid-bound launch blanks COMFY_CUDA_DEVICE on purpose.
type ResidentInfo ¶
type ResidentInfo struct {
Seats []string
CostGiB float64 // estimated cost of evicting them (their footprint)
}
ResidentInfo is what is loaded on one card that taking it would evict.
type ScopeEvent ¶
type ScopeEvent struct {
AtMs int64 `json:"at_ms"`
Epoch uint64 `json:"epoch"`
Kind string `json:"kind"`
From []string `json:"from,omitempty"`
To []string `json:"to"`
Source string `json:"source,omitempty"`
Why string `json:"why,omitempty"`
}
ScopeEvent is one line of the scope ledger: a legacy lease's inferred scope established ("scoped") or grown ("widened").
type ScopeSource ¶
type ScopeSource string
ScopeSource says where a lease's effective card set came from.
const ( // ScopeDeclared: the record names its cards (record v2). ScopeDeclared ScopeSource = "declared" // ScopeInferred: a legacy whole-node record scoped by the evidence rule. ScopeInferred ScopeSource = "inferred" // ScopeWholeNode: no declared cards and no evidence: every card. ScopeWholeNode ScopeSource = "whole-node" )
type Scoper ¶
type Scoper struct {
// Dir is the lease directory; seen.<epoch> lives in it and the scope ledger beside it.
Dir string
// Now is the clock (time.Now when nil).
Now func() time.Time
// Cards reads the card table, ComfyOrder included.
Cards func() ([]gpuprobe.Card, error)
// Tree returns the wrapper's process and its descendants (ProcessTree when nil).
Tree func(root int) ([]TreeProc, error)
// Marker reads the ComfyUI launch marker, if one is on disk.
Marker func() (Marker, bool)
// TreeCards returns the lease ids of the cards the processes hold memory on; ok is false
// when the driver names no process (WDDM) or cannot be read.
TreeCards func(pids []int) ([]string, bool)
// Present reports whether the operator may be at the desk (nil = yes).
Present func() bool
// Audit receives each ledger line (a line in <gpu dir>/scope-ledger.jsonl when nil).
Audit func(ScopeEvent)
// ReadOnly makes the scoper an INSPECTOR: it gathers the evidence and reports the scope
// it implies (the sidecar's sticky set included), and writes nothing: no sidecar, no
// sample, no ledger line. The status surfaces read this way.
ReadOnly bool
// Live reports whether the lease with this epoch is still held; a sidecar is written only
// for a live lease (InspectDir when nil).
Live func(epoch uint64) bool
// Warn receives one line for each failure the scope would otherwise hide (log.Printf
// when nil), each at most once per scopeWarnEvery.
Warn func(string)
// StartUnixMs converts a TreeProc.StartMs, an opaque platform-specific process-start
// identity, to Unix milliseconds; false when the platform cannot (the recycled-pid check
// is then skipped). nil is the platform's own (startUnixMs).
StartUnixMs func(startMs int64) (int64, bool)
// contains filtered or unexported fields
}
Scoper infers the effective card set of legacy whole-node leases. Every member but Dir is a seam; nil is the conservative default (no card table, no marker, no sample, present).
type Skip ¶
type Skip struct {
ID string `json:"id"`
Index int `json:"index"`
Reason string `json:"reason"`
Detail string `json:"detail,omitempty"`
// Display marks the operator's screen card (the card table's rule), so a one-line summary of why cards
// were skipped can say "vram (display card)" when it is the cap that refused it, not just "vram".
Display bool `json:"display,omitempty"`
}
Skip is one card the allocator did not take, and why.
func DesktopRefusals ¶
func DesktopRefusals(in AllocInput, ids []string) []Skip
DesktopRefusals is the desktop rule alone, put again to cards a request already chose: of ids, the cards that rule refuses on this reading. A queued request is chosen at enqueue, against the display card's cap and the VRAM in use as they were then; when its turn comes the caller builds a fresh AllocInput and asks this before the claim (Options.GrantCheck), so a card the allocator would no longer open is not handed over because it was open once.
It judges the desktop's reasons only, which are the ones that change while a request waits: the display card once the operator has closed it (cap 0), a card that may be the display card on a reading that could not say, and the display card past its cap because the desktop or a game has grown on it. Other skips are not repeated here: a card another lease has taken since is the claim's to refuse (ErrHeld), and the rest were never a reason the FIFO position could be lost over. Each refusal is a Skip with the allocator's own reason and detail.
type Standing ¶
type Standing struct {
Epoch uint64
Owner OwnerState
OwnerSession string
// OrphanedSince is when the owner was first seen gone (zero when it is not gone).
OrphanedSince time.Time
// Orphaned: an ATTENDED lease whose owner has been gone for the grace. An unattended
// lease, a remote one and an unknown owner are never orphaned: the first two are
// judged by their progress contract and window, the last by its window alone.
Orphaned bool
Unattended bool
// Overdue: the declared window has ended and the lease is still held. Informational
// about the holder, never a release: a wrapper that is alive and heartbeating keeps its
// claim past its window.
Overdue bool
OverdueBy time.Duration
Progress ProgressView
// Stalled: a progress contract exists and its file did not move inside its window.
Stalled bool
// OwnerNote says why an owner that IS recorded cannot be told apart (the session was not
// in the registry when the lease was taken, or the registry could not be read).
OwnerNote string
// OrphanMarkErr is set when the orphan marker could not be recorded or cleared.
OrphanMarkErr string
// TreeOrphan: the lease's wrapper is gone but a process of the job it started is alive
// (plan P10); TreeLive are those processes and TreeWhy the evidence. The claim is kept.
TreeOrphan bool
TreeLive []TreeMember
TreeWhy string
}
Standing is the derived reading of one live lease. Verdict words are chosen from it by one function (gpuactivity.Assess), so every consumer reads the same lease the same way.
func (Standing) Escalation ¶
Escalation is the standing verdict word of a lease that is not healthy, in precedence order (tree-orphan, then stalled, then orphaned, then overdue), or "" for a lease that is. The words are the verdicts `gpu status` prints (held-stalled and so on).
type TermOutcome ¶
type TermOutcome string
TermOutcome says what one tick of the term check did.
const ( // TermNotDue: the term has not ended; nothing was read beyond the record and nothing written. TermNotDue TermOutcome = "not-due" // TermExtended: the term ended and was renewed by one term; the end moved. TermExtended TermOutcome = "extended" // TermExpired: the term ended and was not renewed; the lease was labelled expired now. TermExpired TermOutcome = "expired" // TermStillExpired: the lease was already labelled and still is not renewable; nothing written. TermStillExpired TermOutcome = "still-expired" )
type TermPlan ¶
type TermPlan struct {
// Window is the declared window: always the whole request.
Window time.Duration
// Term is how far one renewal moves the end: the request, capped at Cap.
Term time.Duration
// Requested is the request when it is above Cap, else zero.
Requested time.Duration
// Cap is the cap on a term this request was judged against.
Cap time.Duration
// MaxTotal is the longest the lease is renewed from its acquisition: the limit, never
// less than Window (a request is never shortened, so it is never judged past its end).
MaxTotal time.Duration
// Warning is the sentence for the caller to print when the request is above a limit;
// empty when it is not.
Warning string
}
TermPlan is what a request for a window comes to.
func PlanTerm ¶
PlanTerm is what a lease asking for window comes to. hasProgress says the lease carries a progress contract (24 h is then the least cap). maxTerm and maxTotal override the installed limits; zero means the installed value. The window is never changed: a request above a limit is recorded and warned about, and the caller gets the sentence to print.
type TermResult ¶
type TermResult struct {
Outcome TermOutcome
// PrevEnd and End are the declared end before and after (equal unless extended).
PrevEnd time.Time
End time.Time
// Why is the sentence behind the outcome: what renewed the lease, or what kept it from
// renewing.
Why string
}
TermResult is what one tick found and did.
type TermSignals ¶
type TermSignals struct {
// Cards looks at the lease's cards (the display card excluded). It is called only for an
// attended lease whose owner is alive and whose progress is not already advancing, the one
// case where it can change the answer. nil reads as "could not be read": a holder that
// supplies no look has not seen the cards, so it must not claim they are idle.
Cards func() CardsReading
}
TermSignals is the evidence the holder's tick supplies beyond what the lease directory holds.
type Token ¶
type Token struct {
ID string `json:"id"`
Class Class `json:"class"`
// Reason is what the call was for, as the line shows it.
Reason string `json:"reason,omitempty"`
// Devices are the cards the call wants (lease ids); empty = the whole node.
Devices []string `json:"devices,omitempty"`
// SinceMs is when the call first joined the line: the arrival time every resume keeps.
SinceMs int64 `json:"since_ms"`
// PolledMs is when the call last proved it was there: the clock the grace and the TTL run on.
PolledMs int64 `json:"polled_ms"`
// WaitingFor is WaitHostRAM while the call's last reading of the lane found only host RAM in its way (its cards free,
// nobody ahead), as a waiter's record says it (MarkToken). Empty for any other wait.
WaitingFor string `json:"waiting_for,omitempty"`
}
Token is one place in line left by a call that could not wait any longer.
func (Token) HoldsItsCardsAgainst ¶
HoldsItsCardsAgainst is Waiter.HoldsItsCardsAgainst for a place in line: a place whose call waits only on host RAM does not hold its cards against a request that declares none (G6). Measured 2026-10-20 on the reference 3-card box: two image tickets waiting for 46.8 GiB of host RAM kept their places on a card for three hours, and a 0 GiB two-card pooled render queued behind them for 36 minutes with every card idle, because this rule covered waiters and not places.
type TreeMember ¶
TreeMember is one process of the job a wrapper started: its pid and its start identity (the platform's own, opaque, compared only for equality on the same box: ProcessStart). A member recorded without a start identity is held by its pid alone.
type TreeProc ¶
TreeProc is one process of the wrapper's tree. Cmdline is "" when it cannot be read.
func ProcessTree ¶
ProcessTree lists root and every descendant of it, each with its start time and, where the operating system lets this process read it, its command line. A process whose command line cannot be read (another security context) is listed with an empty one: it is reported, not skipped. The error is non-nil only when the process table itself cannot be read.
type Waiter ¶
type Waiter struct {
PID int `json:"pid"`
StartTimeMs int64 `json:"start_time_ms,omitempty"`
Class Class `json:"class"`
Reason string `json:"reason,omitempty"`
SinceMs int64 `json:"since_ms"`
// Devices are the cards the waiter wants (GPU UUIDs); empty = the whole node. A
// pre-v2 reader ignores the field, which reads the waiter as whole-node: the
// conservative direction.
Devices []string `json:"devices,omitempty"`
// Token names the place-keeping token this waiter resumed (tokens.go), so it never queues
// behind its own. An older reader ignores the field.
Token string `json:"token,omitempty"`
// DeadlineMs is when the waiter's own wait ends (registration time plus the wait it declared),
// 0 when it declared none. The debris cap reads it (waiterOutlived): a waiter that asked for
// 20 h must not be reaped as debris at 12 h while it is alive and heartbeating. An older reader
// ignores the field and keeps its flat cap, the conservative direction for a record it cannot
// read the wait of.
DeadlineMs int64 `json:"deadline_ms,omitempty"`
// HostRAMGiB is the host RAM the waiter declared (Options.HostRAMGiB), and WaitingFor what it is
// waiting on when that is not the cards: WaitHostRAM once the cards are free and the host's memory
// is what is short (hostram.go). Both ride the record the waiter already rewrites every tick, so
// `gpu status` can say "waiting for host RAM". Additive and omitempty; an older reader ignores them.
HostRAMGiB float64 `json:"host_ram_gib,omitempty"`
WaitingFor string `json:"waiting_for,omitempty"`
// contains filtered or unexported fields
}
Waiter is one process queued for the card.
func (Waiter) BlocksArrival ¶
BlocksArrival reports whether this waiter holds back a request that wants devices (nil = the whole node) and declares hostRAMGiB of host RAM, when that request arrives after it. FIFO among waiters whose cards CONFLICT, with one exception decided on purpose (G6 of the P0 plan, from the 2026-10-10 review): a waiter that waits ONLY on host RAM (WaitingFor == WaitHostRAM: its cards are free, the memory is not) does not hold back a request that declares none. That request adds nothing to the memory the waiter is short of, so it cannot make the shortage worse, and the cards stand idle meanwhile; held for the length of a --wait (eight hours by default) such a waiter was a barrier nothing on the box could pass, and a whole-node one stopped a 0 GiB text bench on a free card with "which has not claimed the card".
The cost, stated: the request that passes takes the cards the waiter wanted, so when the memory recovers the waiter waits for them. That delay is bounded, not a stream: the instant the waiter finds its cards held it stops being a waiter on memory (Acquire clears WaitingFor on ErrHeld), and from then on it is an ordinary front waiter that nothing passes, so the wait is at most the lease of the request that passed it. A request that DOES declare host RAM does not pass: its memory competes with the waiter's, which is how a stream of small declaring requests could starve a large one, so it queues behind the waiter like any other. One limit stays and is named: nothing reserves the waiter's memory against a declaring request on DISJOINT cards, which this line never held back (disjoint backfill), so such a request can still take the memory the waiter is waiting for (docs/systems/gpu-lease.md, "Host RAM").
func (Waiter) HoldsItsCardsAgainst ¶
HoldsItsCardsAgainst says whether this waiter's cards are spoken for from the point of view of a request that does (declaresHostRAM) or does not declare host RAM: every waiter holds them, except one that waits only on host RAM, which does not hold them against a request that declares none. The card allocator reads it (gpualloc.QueuedClaims) to decide which cards a newcomer may treat as free, so it does not steer a request that would pass the waiter away from a card that is free to it.
type YieldAsker ¶
type YieldAsker struct {
// contains filtered or unexported fields
}
YieldAsker decides, on a holder's tick, whether the holder of one lease is to be asked to yield. It is not safe for concurrent use: one holder loop owns one asker.
func (*YieldAsker) Tick ¶
func (a *YieldAsker) Tick() (YieldRequest, bool, error)
Tick makes the decision. It reports the request it wrote and true on the one tick that asked; an error means the request could not be recorded (and so was not made: the next tick tries again).
type YieldRequest ¶
type YieldRequest struct {
Epoch uint64 `json:"epoch"`
AskedMs int64 `json:"asked_ms"`
ByPID int `json:"by_pid"`
// Basis says why the lease was overdue when it was asked.
Basis string `json:"basis"`
// Waiters names up to three of the waiters that wanted the lease's cards; Queued counts them all.
Waiters []YieldWaiter `json:"waiters,omitempty"`
Queued int `json:"queued,omitempty"`
Policy string `json:"policy"`
// GraceMs is the time the job declared it needs to stop cleanly (--yield-grace); 0 = none declared.
GraceMs int64 `json:"grace_ms,omitempty"`
// ActedMs, Action and Exit are what the holder did about it (a second write, under the same lock).
ActedMs int64 `json:"acted_ms,omitempty"`
Action string `json:"action,omitempty"`
Exit int `json:"exit,omitempty"`
}
YieldRequest is the content of the yield.<epoch> sidecar.
func ReadYield ¶
func ReadYield(leaseDir string, epoch uint64) (YieldRequest, bool)
ReadYield reads the sidecar of one epoch; false when the holder was never asked. It writes nothing. The sidecar is replaced by a rename over the live name (an action recorded on a request already made), so it is read through the shared open and an absence is only an answer once it is settled (gate.go).
func (YieldRequest) QueuedCount ¶
func (r YieldRequest) QueuedCount() int
QueuedCount is the number of waiters the ask found.
type YieldRunner ¶
YieldRunner runs the job's own on_yield line to its end and reports the exit status. An error is a failure to start it.
type YieldTicker ¶
type YieldTicker struct {
// contains filtered or unexported fields
}
YieldTicker is the holder side of the request: ask when due, then run the job's own on_yield once. The runner is started in a goroutine so the holder's heartbeat goes on, and it is never waited out or cut short: a helper that takes an hour is left to take it.
func (*YieldTicker) Tick ¶
func (t *YieldTicker) Tick()
Tick is called on every holder tick, after the term check.
func (*YieldTicker) Wait ¶
func (t *YieldTicker) Wait()
Wait blocks until the on_yield this ticker started has ended.
type YieldTickerOptions ¶
type YieldTickerOptions struct {
// OnYield is the holder's OWN in-memory --on-yield value; the record is never re-read for it, so a
// record rewritten after the acquire cannot make the holder run something else.
OnYield string
Run YieldRunner
// Out is the holder's stderr, the notification stream of the session that wraps it.
Out io.Writer
// Label leads the holder's lines ("gpu reserve", "gpu hold").
Label string
// Settle is how long a lease must have read overdue, on every tick of this holder, before the holder is
// asked. The holders pass the interval at which their term check looks again at a lease it has labelled
// expired, so a label is asked about only after it survived a look. Zero asks on the first overdue tick
// that has a waiter.
Settle time.Duration
}
YieldTickerOptions configure a holder's yield ticker.
type YieldView ¶
type YieldView struct {
// Capable: the holder's record says it runs the request.
Capable bool
// File is the sidecar path; "" for a holder that cannot be asked.
File string
// Asked: the sidecar exists.
Asked bool
Req YieldRequest
// Unanswered: the lease still holds its cards past the job's declared grace (or past a display-only
// threshold when it declared none). Nothing is stopped or taken because of it.
Unanswered bool
// Sentence is the wording for a waiter or a status line; "" when there is nothing to say.
Sentence string
}
YieldView is what a read-only surface says about the request on one lease.
type YieldWaiter ¶
type YieldWaiter struct {
PID int `json:"pid"`
Class Class `json:"class"`
Reason string `json:"reason,omitempty"`
}
YieldWaiter is one waiter that was queued for the lease's cards when its holder was asked.
Source Files
¶
- allocator.go
- audit.go
- cmddevices.go
- devices.go
- effective.go
- explain.go
- gate.go
- gpulease.go
- grantcheck.go
- helperscan.go
- hostram.go
- infer.go
- keeper.go
- openshared_other.go
- owner.go
- proc.go
- proc_other.go
- procimages_linux.go
- procmem.go
- procmem_linux.go
- procstart_linux.go
- proctree.go
- proctree_linux.go
- progressdir.go
- renamesafe.go
- renamesafe_other.go
- repin.go
- settled.go
- term.go
- tokens.go
- tree.go
- waiters.go
- yield.go