modelaffinity

package
v0.207.0 Latest Latest
Warning

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

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

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

Documentation

Overview

Package modelaffinity is the process-local admission gate that stops two text lanes from thrashing one llama-swap by asking it for different models at once.

THE INCIDENT. The agent seat (qwen3.8-27b) degraded ~4x — 72s to 307s per call — because llama-swap was loading a DIFFERENT model into the same serving slot while it worked. Every text seat in the default config points at one endpoint (agent_model, model, reasoning_model, escalation_model, triage_model, vision_model, all on http://127.0.0.1:11436), and llama-swap serializes model residency: two lanes naming different models force an evict-and-reload. The harness had nothing that serialized by model — the media slot set is media-only, gpulease's ClassMedia never covers interactive text, sttclient's inferMu guards a different process, pipeline's swapMu guards a timestamp map, and internal/mcpserver has no limiter at all.

WHAT THIS DOES. It converts thrash into ordered batching:

  • Requests naming the SAME model on the SAME base proceed concurrently. llama-swap already queues those harmlessly (see pipeline.breakerFailure's design note: "llama-swap QUEUES incoming requests while it loads a model"), so serialising them would be a pure regression. The expensive event is the SWITCH, not the overlap.
  • A request naming a DIFFERENT model on a base that has in-flight requests parks until they drain, then proceeds. N interleaved switches become one switch per batch.

KEYED ON THE RESOLVED BASE, NEVER ON THE MODEL ALONE. llamaclient's resolveEndpoint (internal/llamaclient/lanes.go) can return a different base per model — a seat_endpoints pin, a busy-aware cascade_remote_lane, or the default. Two models served by two llama-swap instances do not contend at all. Keying on the model would serialise lanes that never conflicted; keying on the base is what makes the gate match the physical resource. Callers pass the base resolveEndpoint already decided — this package never re-decides it.

WHAT IT IS NOT. This is not a GPU lease. internal/gpulease deliberately excludes ordinary interactive text ("thousands per day at ~46ms, and leasing them is untenable... a known limit, not an oversight"), and that judgement stands: a filesystem lease per text request is off the table. This gate is two uncontended mutex acquisitions and no allocation on the fast path.

IT DOES, HOWEVER, READ THAT LEASE — never acquire it. Arbitrating text against text still let a text lane load a multi-GB model into VRAM a media render had just been handed, because the lease's text carve-out left nothing on this side to observe it. gpuwait.go closes that: the admissions that can CHANGE llama-swap residency (an idle base, a promoted switch) wait for a ClassMedia holder to finish, while a request joining the resident model's in-flight batch — which cannot move VRAM — never looks at the lease at all. Reading costs one ReadFile, not an epoch bump, so the carve-out's reasoning is untouched. Details, and the ClassText and pid decisions, live in gpuwait.go.

CROSS-PROCESS LIMIT — STATED PLAINLY, AND ACCEPTED (ADR 0025, Amendment 2026-10-14). This gate's registry lives in this process, so the swap itself stays per process: two harness processes on one box (an MCP server and a CLI invocation, two MCP servers under two editors) that name different models on one base cannot see each other's in-flight set, and can still make llama-swap switch between them. Making that machine-wide would put the fenced, pid-recycle-safe, machine-wide state root gpulease uses on EVERY text call's admission path, the cost gpulease refused for text. It is not built, and it reopens on a measurement, not a process count: processes with in-flight requests naming different models on one base at once, set against the switches llama-swap logged for it (the amendment names the sources and the shape).

Two halves of this package do answer to the machine, and the limit stops at them: the run cap and its line (seatslot.go, over the gpuactivity run registry) counts the agent runs of every process on a seat, and the card fence (gpuwait.go) reads the lease directory, so a text load waits instead of landing on a card a render in another process holds. internal/seatinflight counts in-flight requests across processes too, but only for PAIR's display; nothing admits or parks on it. What the gate fixes by itself is the common case: one harness process with several concurrent lanes inside it (delegate's fan-out, the MCP server's concurrent tool calls, the agent loop running beside a cascade call).

THE /upstream ROUTES. llama-swap's per-model passthrough (/upstream/{model}/…) starts the model it names, and the probes that use it — internal/agent's window and pin probes, internal/tokclient's /tokenize, the warm-up, the STT client, the KV-slot lane — are not generation requests and do not take this gate's per-base admission (a tokenize is a separate request from the generation after it, so it could not batch with it anyway). They DO pass the machine-wide half since 2026-09-22: upstream.go's AwaitUpstream is the one builder of that URL, and under a media or exclusive lease it refuses a request for a model that is not resident (ADR 0026, extended 2026-09-22).

gpuwait.go — the half of this gate that answers to the MACHINE rather than to this process: an admission that would make llama-swap CHANGE what it holds resident waits while a MEDIA render owns the card.

THE DEFECT. internal/gpulease is machine-wide and fenced, and its ClassMedia holder unloads llama-swap once per lease so the card is clear for the render. Ordinary interactive text was deliberately left outside that lease — "thousands per day at ~46ms, and leasing them is untenable" — so nothing stopped the very next text call from making llama-swap pull a multi-GB model straight back into the VRAM the render had just been given. Observed as the box becoming unusable under a render: the media job and the text tier both resident, both thrashing. A lease that one side reads and the other ignores is not mutual exclusion, which is the same sentence gpulease was written to stop being true.

WHY THIS DOES NOT REOPEN THE COST gpulease REFUSED. That carve-out is about ACQUIRING a lease — an epoch bump, a claim file, a heartbeat, a release, all on the write path, per request. This never acquires and never writes. It READS the lease with gpulease.InspectDir, the one inspection path (the vision gate and delegate.LocalBusy read it the same way), and only on the admissions that can change residency — never on a request joining an in-flight batch of the model already loaded. On an idle box that is one ReadFile of a path that does not exist, tens of microseconds against a call the harness budgets 46ms for.

WAITING, NOT REFUSING. A held card is congestion, not a fault: an image render clears in tens of seconds and the caller then gets the answer it asked for. So a blocked admission polls until the card frees, bounded by the caller's OWN budget (its http.Client.Timeout) and by ctx — the same two bounds the in-process park in affinity.go uses, for the same reason. One admission gets ONE such deadline for all its waiting, so a caller that waits, parks, and is promoted onto a card that has been taken again cannot spend that budget twice. It is deliberately NOT bounded by the holder's declared TTL: gpulease stamps DefaultTTL = 1h on essentially every media lease as a reservation, not an estimate, so treating it as an ETA would turn every wait into an instant refusal.

scoper.go — the production wiring of legacy-lease inference (gpulease/infer.go).

A lease that an OLDER binary wrote is a whole-node claim whose record names no cards. When the host has turned the inference on (config gpu_legacy_scope_inference, SetLegacyInference), a read of the lease carries the cards the evidence rule scoped it to, or the reason it stayed whole-node. Off, every legacy lease fences every seat, exactly as it always did.

TWO KINDS OF READER, and only one of them writes:

  • The OBSERVER (InspectLease): the load gate, the delegation door and the agent_run door read the lease because a process wants a card. They remember what they see: the sticky set (seen.<epoch>) and one ledger line when a scope is established or grows. They unload nothing; a seat whose card the scope has spread onto yields on its own release (seatyield.go).
  • The INSPECTOR (PeekLease, ScopeInfo, ScopeFunc, ScopeLeases, CardsHeld, and the delegator's own reads): gpu status, offload_status, the placement table and the delegator's routing read the same evidence and report the same scope, and write nothing at all: no sidecar, no ledger line, no call to llama-swap.

Each Scoper is built once per lease directory and kind (its throttle memo has to outlive one read) over this package's armed state: the card table (memoised, ComfyUI order from config gpu_comfy_order), the ComfyUI install directory (config comfy_dir) for the launch marker, and the driver's per-process card listing for the sampled-cards evidence. Presence is not armed here: an unreadable presence is "present", so an inferred scope always keeps the display card (the conservative reading; a reader that can tell the operator is away installs gpulease.Scoper.Present).

seatscope.go — which leases matter to WHICH seat (plan P4, register C-86).

THE DEFECT. The gate asked "is a lease held", so a render on card 2 made every text load on the box wait, cards 0 and 1 included. Now it asks the narrower question: does a held lease sit on a card THIS seat is pinned to. The seat's pin is declared in the box's layers (config: LayerSeat.Device, PCI-order indices, the same pin the seat is launched with) and, for a model no layer declares, in the serving config it is launched from (the env CUDA_VISIBLE_DEVICES of its entry; register C-86a), so it is ARMED from config.Load (SetSeatPins, with Config.ModelPins) rather than imported: config imports this package, and a second resolution order is how a gate and a launcher come to disagree.

THE DIRECTION OF EVERY DOUBT IS "FENCE". A model nobody declared a pin for, a pin the card table cannot place, a card table that cannot be read, a whole-node lease: each reads as every card, which is the answer this gate gave before card-scoped leases existed (plan invariant I7). Narrowing happens only on a positive resolution.

COST. The card table is an nvidia-smi exec, so it is read only when a held lease actually names cards (a whole-node lease or an idle box never need it) and memoised for cardTableTTL; the unfenced path still pays one ReadFile, as before. The fence's own readers (ScopeToModel, which Admit, AwaitUpstream, AwaitRunSlot, the seat yield and SeatLease all go through, and SeatCards) look a seat's pins up on the same condition, and no sooner: they include the serving config, which costs a Stat of the file, and an idle box or a whole-node lease has no use for them. That is the fence's cost and not every reader's. PinsFor, and the callers of Config.ModelPins that never read a lease (the agent run's recorded cards, the text and vision auto routes, the delegator's run-cap line), ask on every call, an idle box included, and pay that Stat each time (a parse only on the first call, after an edit and within three seconds of one).

seatyield.go — the seat race rule (plan P4, register C-86).

THE RACE. A lease claims its cards FIRST and then unloads the seats resident on them (gpu reserve --unload-seat, the render lane's freeLlamaSwap). A text load that passed the gate a moment BEFORE the claim finishes loading AFTER that unload, so its model lands on cards the lease now holds, beside a render, and stays until its own idle ttl: the very residency switch the gate exists to prevent. The check-then-act window cannot be closed at the gate (the load is llama-swap's, one request later), so it is closed from the other side: once a model is resident, the seat re-reads the lease, and if one that this process does not hold now sits on the seat's cards, THE SEAT UNLOADS ITSELF. The seat always yields; the long job never does.

THE INFERRED SCOPE OF A LEGACY LEASE reaches a seat the same way and no other. The scope is learned, not declared, so it can grow after a seat was admitted onto a card that looked free: a ComfyUI that started on card 2 and later spread to card 0. The next reading of the lease carries the wider scope, and the seat re-reads it when its own request completes (Release, or the delegation door's warm-up), finds the lease on its card, and unloads itself. NOTHING ELSE UNLOADS A SEAT FOR AN INFERENCE: a read of the lease (a status, a poll, a gate check) never touches llama-swap, because it is not the action of a process that wants the card (plan I5), and an inference is a guess about a foreign job. A seat that is resident and idle on a card the scope has just spread onto keeps it until its own idle ttl (five minutes), or its next request.

WHAT NEVER YIELDS. The memory stack (register C-87: mem0 never yields to a lease); a model with requests in flight (the engine's own gauge: it is pulled only once idle, and the next release picks it up); a process running UNDER the lease (insideLease); a model on a card the lease does not touch. Unloading goes through the vendored llama-swap client, whose keep-set refuses a protected member by id and by alias.

upstream.go — the fence in front of llama-swap's per-model passthrough.

THE DEFECT (2026-09-22, the 3-card agent seat on a video render). llama-swap answers ANY request under /upstream/<model>/… by STARTING that model when it is not loaded (llama-swap v251 internal/server/api.go handleUpstream: the request is pinned to the model and handed to the local router, which swaps it in; only a path matching the operator's upstream.ignorePaths is refused with 409). The harness's generation requests were fenced — Admit waits for the card under a media or exclusive lease (gpuwait.go) — but four families of harness requests reached /upstream without passing any gate:

  • the served-window probe (internal/agent window.go: /props, /v1/models),
  • the seat-pin probe (internal/agent props.go: /props, /version, /v1/models),
  • the real tokenizer (internal/tokclient: /tokenize),
  • the warm-up, the whisper transcription and the KV-slot lane.

An agent run admitted a moment before a render kept issuing them. A client with a short timeout (the seat pin gives up after 3 s) hangs up mid-load and llama-swap logs the start as aborted; the window probe waits out a cold start and completes one. The render's card took 14.3 GB of seat weights mid-video and the render ran 895 s against its usual 228-324 s.

The same holds for llama-swap's MODEL-DISPATCHED routes (/v1/chat/completions, /v1/embeddings, …), which load the model named in the body: the fleet chat lane forwarded another box's cascade call there with no gate at all, and the embedder posted there outside Admit. AwaitModelRoute is their builder.

THE INVARIANT. While blocksLoad holds — a media lease, or a text lease stamped exclusive, that this process does not inherit — no harness request may make llama-swap load a model. AwaitUpstream is the one builder of an /upstream URL in the harness (TestUpstreamURLsAreBuiltOnlyBehindTheFence pins that no other non-test file spells the route), so a new probe cannot reach the route without passing the fence.

WHAT PASSES A FENCE. A request for a model llama-swap already lists as READY cannot start anything: it is served by the resident process. So under a fence the gate reads /running (never /upstream, which is the thing it guards) and lets a ready model through. A model that is absent, starting or stopping is not resident; its request waits for the card, bounded by the caller's own deadline, and on exhaustion returns the same *LeaseError a generation admission returns — typed, naming the holder, carrying "timeout" so the ledger files it as congestion. A caller that must not wait (the post-run pin, the per-step tokenizer) passes a deadline of now and gets one inspection.

The residency read is taken ONLY when a fence is up, so an unfenced box pays what it paid before: one ReadFile of a lease record that usually does not exist. The same check-then-act window ADR 0026 names for Admit remains (a lease taken microseconds after the read), and a ready model evicted by its own ttl between the read and the request is the same window from the other side; both are one read wide.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoUpstreamRoot = errors.New("modelaffinity: endpoint has no llama-swap root for an /upstream request")

ErrNoUpstreamRoot is returned when the endpoint names no llama-swap root.

Functions

func AwaitModelRoute

func AwaitModelRoute(ctx context.Context, endpoint, model, route string, deadline time.Time) (string, error)

AwaitModelRoute is AwaitUpstream for llama-swap's MODEL-DISPATCHED routes — /v1/chat/completions, /v1/embeddings, /v1/completions, /completion, /infill, /v1/rerank, /v1/audio/*, … — where the model is named in the request body rather than the path, and which load that model exactly as /upstream does (llama-swap v251 internal/server/server.go modelPostJSONRoutes: the request is dispatched to the local router, which swaps the named model in). It returns endpoint's root + route once the fence (the same rule, the same residency exemption, the same typed refusal as AwaitUpstream) lets the request through.

It is the builder for a request that does NOT take a per-base admission (Admit): the fleet chat lane, which leaves queueing to the node's llama-swap by design, and the embedder. Clients that do take Admit — agent.LLMClient, llamaclient — are already fenced by it, which is why TestModelDispatchedRoutesAreBuiltOnlyBehindAGate lists them by name and checks that each still takes Admit.

func AwaitRunSlot

func AwaitRunSlot(ctx context.Context, base, model string, deadline time.Time) error

AwaitRunSlot is awaitCard for the START of an agent run (0.117.0, register D-93): it also waits out a text holder that is DRAINING the seat. The two predicates differ on purpose — see BlocksNewRun. A launcher calls this once, before admission, with its admission budget as the deadline, so a run refused at the cordon defers with the holder named and never spends its wall waiting.

func AwaitSeatSlot

func AwaitSeatSlot(ctx context.Context, runs SeatRuns, seat, canonical, selfID string, cap int, deadline time.Time) error

AwaitSeatSlot waits until fewer than cap runs other than selfID are registered on seat (or canonical), or the deadline passes. cap <= 0 or a nil reader disables the gate.

func AwaitSeatSlotReporting

func AwaitSeatSlotReporting(ctx context.Context, runs SeatRuns, seat, canonical, selfID string, cap int, deadline time.Time, tick func(ahead int)) error

AwaitSeatSlotReporting is AwaitSeatSlot with a heartbeat: tick (when set) is called once when the run joins the line and after every poll while it stays there, with the number of runs still ahead of it. A run that waits in line publishes it so a remote delegator follows the wait on evidence (register C-60) instead of giving up a job the node still holds.

func AwaitUpstream

func AwaitUpstream(ctx context.Context, endpoint, model, path string, deadline time.Time) (string, error)

AwaitUpstream returns the URL of llama-swap's per-model passthrough for model (endpoint's root + "/upstream/" + model + path) once sending a request there cannot load a model onto a fenced card.

Unfenced (no lease, a plain text reservation, a draining hold, the caller's own inherited lease, or a gate that config.Load never armed) it returns at once. Fenced, it lets the request through when llama-swap lists the model as ready, and otherwise waits for the fence to lift until deadline or ctx ends, returning a *LeaseError when it does not.

path is appended verbatim (it may carry a query); a missing leading slash is added. The model name is path-escaped.

func BlocksLoadFor

func BlocksLoadFor(info gpulease.Info, pins []string) bool

BlocksLoadFor is blocksLoad for a seat on the cards pins name.

func BlocksNewRun

func BlocksNewRun(info gpulease.Info) bool

BlocksNewRun decides whether info describes a card no NEW agent run may start on: everything blocksLoad refuses, plus a holder that is DRAINING the seat (0.117.0, register D-93; either class since 2026-09-22). The distinction is the whole fix: a drain must stop new work from landing (or it never converges under K sessions) while letting the runs already in flight finish their remaining steps (or it blocks the very work it is waiting for — the 2026-09-14 deadlock, resolved only by the run's 600 s wall). Requests of a registered run pass blocksLoad under a draining lease; a run's first admission passes through here.

func BlocksNewRunFor

func BlocksNewRunFor(info gpulease.Info, pins []string) bool

BlocksNewRunFor is BlocksNewRun for a seat on the cards pins name.

func CardsHeld

func CardsHeld(pins []string) (held bool, why string)

CardsHeld reports whether a lease this process does not hold sits on any card the pins name, and says which. It reads the armed lease directory, so the unarmed gate (no config.Load) holds nothing, and it is the placement table's reader of "is the home seat's card taken". No pins is an unknown seat: every card, so any live foreign lease holds it. It is an inspection (PeekLease): it writes nothing.

func DisarmGPULease

func DisarmGPULease()

DisarmGPULease turns the text-load gate off for this process: AwaitRunSlot, awaitCard and GPULeaseDir then read as "not armed". config.Load calls it when the endpoint is another box's engine.

func EndpointHost

func EndpointHost(base string, selfNames ...string) string

EndpointHost returns the lower-cased host of base when base names another box's engine, and "" when base is this box (loopback, "localhost", this machine's hostname or its short form, or any of selfNames — the config's fleet_node_id, which names this box on the tailnet and need not equal the OS hostname) or unparseable.

func GPULeaseDir

func GPULeaseDir() string

GPULeaseDir reports the lease directory this gate is armed at, or "" when it is not armed. It exists so the wiring is OBSERVABLE: the gate is armed process-wide from config.Load, and without a way to read it back "we armed it" would be an unfalsifiable claim rather than something a test can pin.

func HolderUpstreamURL

func HolderUpstreamURL(endpoint, model, path string) (string, error)

HolderUpstreamURL builds the same URL with NO fence. It exists for exactly one caller: the lease HOLDER warming its own seat back at the end of `gpu reserve --drain --unload-seat -- <cmd>`. That process holds the lease it would otherwise wait on (it does not carry GPU_LEASE_EPOCH itself; its child did), and the warm-back is the load the lease was taken to schedule. TestUpstreamURLsAreBuiltOnlyBehindTheFence restricts its callers.

func InsideLease

func InsideLease(info gpulease.Info) bool

InsideLease reports whether this process runs under the very lease info describes (see insideLease): the epoch comparison every consumer of a lease must use for its own holder.

func InspectLease

func InspectLease(dir string) gpulease.Info

InspectLease is gpulease.InspectDir with the evidence rule applied to every legacy whole-node lease in it, as the OBSERVER: it remembers what it sees (the sticky set and the ledger line). Use it where a process reads the lease because it wants a card. A directory that holds nothing, or only leases that are not legacy, costs exactly what InspectDir costs.

func IsLeaseRefusal

func IsLeaseRefusal(err error) bool

IsLeaseRefusal reports whether err is (or wraps) a refusal by the GPU-lease gate — a *LeaseError from Admit, AwaitRunSlot or AwaitUpstream. Callers that fail open on a probe use it to tell "the card is held" from "the endpoint is broken", which must never be counted against the endpoint.

func IsSeatSlotError

func IsSeatSlotError(err error) bool

IsSeatSlotError reports whether err is a seat-cap refusal.

func LegacyInference

func LegacyInference() bool

LegacyInference reports whether the inference of legacy leases is on for this process.

func PeekLease

func PeekLease(dir string) gpulease.Info

PeekLease is InspectLease as an INSPECTOR: the same scope, and nothing written.

func PinsFor

func PinsFor(model string) ([]string, bool)

PinsFor reports the device pins the gate has armed for model (PCI-order indices or UUID prefixes); ok is false for a model nobody declared, which the gate reads as every card.

func ScopeFunc

func ScopeFunc(gpuLockPath, stateDir string) func(gpulease.Info) gpulease.Info

ScopeFunc is ScopeInfo bound to a lease directory, for a reader (the activity snapshot) that is handed the evidence rule without importing this package. A directory that cannot be resolved gives nil: the reader then sees only declared devices.

func ScopeInfo

func ScopeInfo(dir string, info gpulease.Info) gpulease.Info

ScopeInfo applies the evidence rule to an inspection a caller already holds (the status surfaces read the lease through a Manager), as an INSPECTOR: every legacy whole-node lease in it gets its inferred scope, and nothing is written.

func ScopeLeases

func ScopeLeases(dir string, leases []gpulease.Info) []gpulease.Info

ScopeLeases is ScopeInfo for a list of leases, one Info per lease.

func ScopeToModel

func ScopeToModel(info gpulease.Info, model string) gpulease.Info

ScopeToModel is ScopeToPins for the seat serving model. The pins are looked up only for a lease that names cards: nothing else narrows, and the lookup reads the serving config.

func ScopeToPins

func ScopeToPins(info gpulease.Info, pins []string) gpulease.Info

ScopeToPins narrows info to the leases that sit on the cards pins name (PCI-order indices or UUID prefixes, a layer seat's Device split by DeviceList). No pins, an unresolvable pin or an unreadable card table returns info unchanged: unknown is every card.

func SeatCapDeadline

func SeatCapDeadline(ctx context.Context, now time.Time, wall time.Duration, admissionEnd time.Time) time.Time

SeatCapDeadline is how long a run may wait in line at the seat cap (register C-60, 0.143.0): as long as its own wall, never less than the admission deadline the cap wait used to share, never past the caller's context deadline. Waiting in line is queueing, not admission — the shared 300 s budget refused 88 of the 2026-09-29 cap waits after exactly 5m0s, most with the seat about to free — and INV-4 queues rather than refuses. Callers move the admission deadline out by the time spent in line, so the pre-flight, the cold load and the probes keep their whole budget.

func SeatCards

func SeatCards(model string) []string

SeatCards names the cards (lease ids) the seat serving model sits on, resolved by the same pins and the same card table ScopeToModel narrows a lease with, so the cards a blocked admission WAITS on are the cards it was blocked on. nil means "cannot be said": an undeclared model, a pin the card table cannot place, a card table that cannot be read. The caller reads that as the whole node, the direction of every doubt in this file. It reads the card table (an nvidia-smi exec, memoised) exactly as ScopeToPins does, so the caller asks it only under the condition ScopeToPins reads it under: a held lease that names cards (namesCards). It is asked once, on the blocked path, to register the admission's place in line, never on the unfenced fast path and never for a whole-node lease, which needs no card table.

func SeatLease

func SeatLease(model string) gpulease.Info

SeatLease reads the armed lease directory and returns what it holds against model's cards: the leases that sit on them, and nothing else. The zero Info when the gate is not armed (no config.Load ran in this process) or nothing relevant is held.

func SetCardOrder

func SetCardOrder(order string)

SetCardOrder arms config gpu_comfy_order for the card-table reads this package makes.

func SetCardTableReader

func SetCardTableReader(fn func(ctx context.Context, comfyOrder string) ([]gpuprobe.Card, string, error)) (restore func())

SetCardTableReader replaces the card-table reader (nvidia-smi by default) and returns a function that puts the previous one back. A fleet node that already holds a background VRAM sample, and a test with a synthetic box, install their own.

func SetComfyDir

func SetComfyDir(dir string)

SetComfyDir arms config comfy_dir: where the ComfyUI launch marker is read from. The lease readers look in the same directory when a lease's wrapper is gone: a marker ties a ComfyUI instance to the lease it was launched under, so that lease keeps its claim while the instance runs (gpulease/tree.go). Arming both here keeps the directory one setting with one call site (config.loadArmed).

func SetGPULease

func SetGPULease(lockOverride, stateDir string) error

SetGPULease arms the machine-wide half of this gate at the lease directory the operator's gpu_lock_path/state_dir resolve to, and is called from config.Load.

ARMED FROM CONFIG LOAD, ON PURPOSE — the same wiring, for the same reason, as netguard.SetTailnetSuffix beside it. The lease location is a property of the MACHINE, not of any one client, and it is decided by two config fields. Passing it down instead would mean threading it through llamaclient.New and agent.NewLLMClient at 60-odd construction sites, where the ONE site that forgot would be an ungated text lane with nothing to report it. Arming it in the same act that resolves the overrides means a second resolution order cannot exist — which is the whole of gpulease.LeaseDir's doctrine, applied one layer up.

A resolution failure DISARMS rather than degrades to a guess: gpulease.LeaseDir refuses a cloud-synced root, and inventing a different directory here is exactly the silent lease split it refuses it to prevent. Disarming is safe rather than merely tolerable — the same refusal reaches gpulease.OpenAt on the media path, so no media lease can be taken on such a box and there is nothing to protect. The error is returned so the caller can say so out loud.

func SetLegacyInference

func SetLegacyInference(on bool)

SetLegacyInference arms config gpu_legacy_scope_inference: whether a legacy whole-node lease (one an older binary wrote) is scoped by the evidence rule at all. Off (the default), every legacy lease fences every seat, exactly as it always did.

func SetSeatPins

func SetSeatPins(fn func(model string) ([]string, bool))

SetSeatPins arms the seat-to-cards map: for a model name it returns the device pins of the seat(s) that serve it (PCI-order indices or UUID prefixes; read from the layers, else from the serving config) and whether the model is placed at all. config.Load arms it, beside SetGPULease. nil disarms it, which reads every model as unknown: every lease fences every seat.

func SetYieldProtect

func SetYieldProtect(protect []string)

SetYieldProtect arms the models that never yield (config memory_stack). config.Load arms it beside the lease directory.

func SetYieldSeams

func SetYieldSeams(s YieldSeams) (restore func())

SetYieldSeams installs fakes for the yield path and returns the function that puts the previous ones back.

func WouldBlockUpstream

func WouldBlockUpstream(ctx context.Context, endpoint, model string) bool

WouldBlockUpstream reports, without waiting and without sending anything to a model route, whether a request for model through AwaitUpstream (or AwaitModelRoute) would be held at the fence right now: a lease that fences the card over model is held, this process does not inherit it, and llama-swap does not already list model as ready. It is the fence's own first inspection (awaitUpstream calls it), so a caller that chooses between waiting here and going elsewhere (the stt route's auto mode spills to a fleet node) reads the verdict the request itself would meet: a resident model is served at once and does not block. The residency read is taken only when a fence is up, as in the fence.

func YieldIfFenced

func YieldIfFenced(ctx context.Context, endpoint, model string) (yielded bool, why string)

YieldIfFenced is the seat race rule for one seat: when a lease this process does not hold sits on named cards (declared or inferred, never a whole-node lease) that model is pinned to, and fences loads (a media lease, or an exclusive text one), and the model is resident with nothing in flight, it unloads the model. yielded is true only when the unload succeeded; why says what happened either way when it matters (a yield, a yield that failed, a seat whose state could not be read and so stayed where it was). It never waits and never touches a lease.

Types

type LeaseError

type LeaseError struct {
	Base    string         // the resolved llama-swap base the admission was for
	Want    string         // the model this request named
	Class   gpulease.Class // the holder's lease class (media, or an exclusive text hold)
	PID     int            // the holder's pid
	Reason  string         // the holder's declared reason
	Origin  string         // the holder's declared origin
	JobID   string         // the holder's job id, when it declared one
	HeldFor time.Duration  // how long the holder has owned the card
	Waited  time.Duration
	Bound   time.Duration
	// Draining: the holder is a text lease draining the seat (BlocksNewRun) — the
	// refusal is of a NEW run, not of a load; running work was never touched.
	Draining bool
	// ExpiresAt is the end the holder DECLARED when it acquired the lease; zero
	// when it declared none. Rendered by window() — see there for why a number
	// this package refuses to wait on is still worth reporting.
	ExpiresAt time.Time
	// Epoch is the holder's lease epoch. Explain, when non-empty, says what is wrong
	// with a holder that is held but not healthy (its owner gone, its progress stalled,
	// its window long past) and the command that frees it; it is appended to Error() and
	// is empty for a lease that is fine.
	Epoch   uint64
	Explain string
	// contains filtered or unexported fields
}

LeaseError is the outcome of an exhausted wait for the GPU. Like WaitError it is a distinct type carrying WHO held the card, because "timeout" alone sends the reader to the model and the endpoint when the answer is a render.

func (*LeaseError) Error

func (e *LeaseError) Error() string

Error names the render, not the model. It contains the word "timeout" because pipeline.classifyErr buckets infra errors by substring and a held card is congestion, which that classifier spells "timeout"; the wording is pinned by test so a reword cannot silently reclassify it in the ledger.

func (*LeaseError) Unwrap

func (e *LeaseError) Unwrap() error

Unwrap exposes the cause so errors.Is(err, context.DeadlineExceeded) and errors.Is(err, context.Canceled) keep working for callers that branch on them.

type SeatRuns

type SeatRuns func(now time.Time, names ...string) []gpuactivity.Run

SeatRuns is what AwaitSeatSlot reads: the registered runs on the named seats (gpuactivity.Registry.OnSeat satisfies it).

type SeatSlotError

type SeatSlotError struct {
	Seat   string
	Cap    int
	Ahead  int
	Waited time.Duration
	// contains filtered or unexported fields
}

SeatSlotError is a run refused at the seat cap: the deadline passed with the seat still full.

func (*SeatSlotError) Error

func (e *SeatSlotError) Error() string

func (*SeatSlotError) Unwrap

func (e *SeatSlotError) Unwrap() error

type Ticket

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

Ticket is the admission a caller holds while its request is in flight. The zero Ticket is a no-op, so `defer tk.Release()` is safe on the error path.

end closes the request's seatinflight marker (on-box admissions only): the machine-wide count of the harness's own seat requests that fleet-serve's PAIR seat watcher subtracts, so a harness job never shows twice in PAIR.

func Admit

func Admit(ctx context.Context, base, model string, budget time.Duration) (Ticket, error)

Admit takes an admission for one generation request against base naming model, and blocks only when admitting it now would force llama-swap to swap models out from under work already in flight.

budget is how long ONE request against this base is allowed to take end-to-end — in production the resolved http.Client's Timeout. It is not how long the caller waits; it is the unit the wait bound is built from (see waitBound). ctx bounds the wait too, and in production it is usually the tighter of the two.

On success the caller MUST call Release on the returned Ticket exactly once. On failure the error is always a *WaitError. Admit is the admission for THIS box's llama-swap: the in-process per-base queue below, and before it the machine-wide GPU lease (gpuwait.go), because a load here can move VRAM a render or a measurement is using.

func AdmitOffBox

func AdmitOffBox(ctx context.Context, base, model string, budget time.Duration) (Ticket, error)

AdmitOffBox is Admit for an endpoint that is NOT this machine's llama-swap — a cascade remote lane riding a fleet node's door, or a seat pinned to another box (register C-41c). The request loads nothing into this box's VRAM, so the machine-wide GPU lease has no say over it: it keeps the in-process per-base queue (two callers of one remote base still take turns) and skips the card wait. Measured 2026-09-15 on 0.125.0: the lane fired and the send then sat the full two-minute lease bound at home, and the node never saw a request.

func (Ticket) Release

func (t Ticket) Release()

Release ends the caller's in-flight window and, when it was the last of its batch, hands the base to whoever is parked. It is safe on a zero Ticket and must be called exactly once per successful Admit.

type WaitError

type WaitError struct {
	Base         string // the resolved llama-swap base the wait was on
	Want         string // the model this request named
	Held         string // the model whose batch held the base when we parked
	InFlight     int    // how many requests that batch had, when we parked
	BatchesAhead int    // model switches that had to happen before ours
	Waited       time.Duration
	Bound        time.Duration
	// contains filtered or unexported fields
}

WaitError is the outcome of an exhausted admission wait. It is a distinct type, with the base, the model wanted, and the model that held the slot, because "timed out" alone sends the reader looking at the model instead of at the contention that actually happened.

func (*WaitError) Error

func (e *WaitError) Error() string

Error names the contention. It deliberately contains the word "timeout": internal/pipeline.classifyErr buckets infra errors by substring and files anything unrecognised as "other", and an exhausted affinity wait is congestion, which that classifier spells "timeout". The wording is pinned by test so a reword cannot silently reclassify it in the ledger.

func (*WaitError) Unwrap

func (e *WaitError) Unwrap() error

Unwrap exposes the cause so errors.Is(err, context.DeadlineExceeded) and errors.Is(err, context.Canceled) keep working for callers that branch on them.

type YieldSeams

type YieldSeams struct {
	Read   func(ctx context.Context, endpoint, model string) (seatload.Reading, error)
	Unload func(ctx context.Context, endpoint, model string) error
}

YieldSeams are the llama-swap read and the unload the seat-yield path makes. A nil member keeps the production one. A caller outside this package that needs to prove its wiring (a test of the cold-load warm-up) installs fakes; nothing in production does.

Jump to

Keyboard shortcuts

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