fleetnode

package
v0.209.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 53 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

The fleet "chat" lane (C-41b): this node forwards ONE OpenAI chat completion, for a model its own llama-swap serves, on behalf of a delegator whose local seat would make the call wait.

Why it exists at all. The cascade lane (internal/llamaclient/lanes.go) was written to send a cascade tier at a fleet node that serves the identical GGUF while the local 27B seat holds this box's cards. It probed the lane base's llama-swap directly — and BOTH fleet nodes bind llama-swap to 127.0.0.1:11436 and nothing else (<node-a> since the 2026-08-24 native cutover, <node-c> by design), so from another box that base is unreachable, every residency probe fails, and the lane silently never fires. Binding llama-swap to the tailnet would be a NEW unauthenticated listener, which is exactly what the vision lane refused to do in 0.116.0 (ADR 0040): it put a bearer-gated route on the node's own :18811 that proxies to the node's loopback llama-swap. This is that same door for text.

What it is NOT. It is not a job: no job_id, no queue, no polling, no admission band. A cascade tier is a single short synchronous call whose caller already holds a deadline, and wrapping it in the job store would add a poll loop to a request that finishes in seconds. Queueing still happens — on the node's llama-swap, which is where it belongs.

Auth is the agent and vision lanes' rule, verbatim: fleet_auth_token required beyond loopback, loopback + no token stays open (AgentLaneSafelyReachable). The check runs FIRST, before the body is even read, because nothing about the decision depends on the body (the vision lane checks first too) — so an unauthorized caller gets the auth verdict and nothing else.

claimloop.go — the node side of the Option B pull queue (ADR 0030, dark by default): a background loop that PULLS eligible work from the config-elected holder, runs it through the SAME BuildRequest + jobs.Accept surface a pushed dispatch uses, and acks the holder with the result. Started by the serve verb only when BOTH fleet_queue_holder and fleet_queue_claim are set.

gpuinfo.go — the GPU memory PROVIDER seam (J3). fleet-serve historically hard-required nvidia-smi: the startup probe, the 2s health sampler, and the vendor/arch advertisement all shelled to it, so a working AMD/Vulkan box (the amd-rdna3 tier) could not join the fleet at all — and the refusal text blamed the GPU rather than the probe. This file makes the memory source a resolved PROVIDER: nvidia-smi where it works, else the Windows-generic WDDM source (registry capacity + PDH adapter usage, vram_windows.go), with vendor/arch read from the installer's manifest instead of re-derived from NVIDIA product names. The serve gate becomes "no working GPU memory source", which is the fact the contract actually cares about.

ingress.go is the object-storage seam AND the SSRF boundary for pipeline jobs (Task 6's buildPipelineJob calls FetchRefs with a job's image_refs): it turns the dispatch payload's bare URLs into local files a pipeline CLI can read. Every ref is checked against the allowlist BEFORE any network dial — the threat is a compromised/malicious dispatcher, or a crafted job_spec, using this node as an open proxy into its private network or the wider internet. No hostname is ever DNS-resolved to make that check: only a literal IP address can pass via the tailnet CGNAT range or loopback: a hostname passes ONLY by an exact "host:port" match against extraAllow. Resolving a hostname to inspect its IP and then dialing that same hostname again is the classic DNS-rebinding bypass this design avoids by construction.

Package fleetnode implements the node side of fleet-dispatcher CONTRACT.md v2: health / ack-then-poll dispatch / job status, with measured VRAM footprints. This file is the job store — the ack-then-poll heart of the dispatch contract: a POST acks in milliseconds (202 accepted) and the render runs in a tracked goroutine; pollers read state until it turns terminal (done|error). Once acked, a job is OURS FOREVER (never re-dispatched), so shutdown marks survivors terminal rather than losing them — pollers always reach a terminal state.

ADMIT-THEN-SCHEDULE (0.100.0). Accept used to BE start: it wrote the record and immediately launched the run, so `accepted` lasted microseconds, nothing ever waited, and the node's one cap (fleet_max_queue_depth) bounded SIMULTANEOUS EXECUTION while being named, documented and read as a backlog. A node at "depth 31" was 31 inferences at once against a single llama-swap endpoint. Accept now ADMITS — a record plus a place in a FIFO — and a single scheduler goroutine claims jobs only while a slot is free, so `accepted` is a real state a job can sit in and the two limits are independent:

backlog     — Jobs never enforces it. Admission is the SERVER's gate
              (fleet_max_queue_depth over QueueDepth), unchanged from
              0.99.0, so the refusal boundary did not move.
concurrency — maxConcurrent here, and only here. <= 0 = unlimited, which
              reproduces the pre-0.100.0 goroutine-per-job behaviour
              through this same code path (no second branch that only the
              unlimited config would ever execute).

Poll semantics are UNTOUCHED: same ids, same idempotent re-ack, same write-once terminal states, same TTL janitor. The only difference a poller can observe is that `accepted` may now legitimately last a while.

Package fleetnode implements the node side of fleet-dispatcher CONTRACT.md v2: health / ack-then-poll dispatch / job status, with measured VRAM footprints. See the private development record (2026-07-17).

vram.go is the two-source VRAM sampler's portable half: the nvidia-smi global snapshot (feeds /fleet/health every 2s) and the pure helper ParseSmiMemory. The Windows-only PDH per-process source lives in vram_windows.go.

vram_linux_amdgpu.go — the Linux GPU memory provider ADR 0014 left as "a future seam". Off-Windows, a non-NVIDIA box had NO generic source, so an AMD APU that detect classified into a MEASURED tier (amd-gcn) and that llama-swap already served could not fleet-serve at all: "no working GPU memory source: nvidia-smi (…); windows-generic (windows-generic GPU memory source requires WDDM)" — <node-f>, Ryzen 5 5625U / Vega 7, 2026-09-20.

The amdgpu kernel driver publishes exactly the two numbers the provider needs, per card, under /sys/class/drm/card*/device:

mem_info_vram_total / mem_info_vram_used   the carve-out ("VRAM") and its use
mem_info_gtt_total  / mem_info_gtt_used    the GTT pool: system RAM the GPU
                                           may map — on an APU this IS the
                                           shared budget ADR 0014 approximates
                                           with RAM/2 on Windows

So the UMA composition is the same as the Windows-generic one (capacity = carve-out + shared budget, usage = dedicated + shared), but with the driver's own budget instead of a heuristic. A discrete AMD card (uma=false) reports its VRAM alone, exactly like nvidia-smi does for an NVIDIA card.

The file has no build tag on purpose: it reads plain files under an injected root, so the parser and the probe are unit-tested on every OS; main.go wires it only on linux.

vram_uma_meminfo.go — the GPU memory provider for a unified-memory SoC (the rockchip-rk3588 tier). fleet-serve refused to start there: the only Linux source was AmdgpuSysfsProbe, which needs a PCI vendor id and mem_info_vram_total, and an RK3588's Mali GPU and NPU expose neither — they allocate from the same RAM as the CPU, so there is no VRAM counter to read.

The honest capacity of such a node is not MemTotal. The box has another job (a home-automation stack on the reference board) that must keep its memory, so the operator names a reserve (uma_reserve_gib) and the node advertises what is left:

total = MemTotal     - reserve   the inference budget
free  = MemAvailable - reserve   clamped to [0, total]
used  = total - free

free is conservative on purpose. Memory the host workload already holds is subtracted from MemAvailable AND the reserve stays set aside, so it is counted twice: the node may under-advertise what inference could take, and can never over-advertise it. Nothing here caps what a seat actually allocates — the budget is what /fleet/health tells the dispatcher, as with every other provider.

The file has no build tag on purpose: it reads one plain file under an injected root, so the parser and the probe are unit-tested on every OS, like AmdgpuSysfsProbe; main.go names the source only for the rockchip-rk3588 tier.

Index

Constants

View Source
const (
	BandSheddable = core.BandSheddable
	BandNormal    = core.BandNormal
	BandUrgent    = core.BandUrgent
)

Scheduling bands (0.113.18). A band is an integer priority the CALLER stamps on the dispatch (`priority` in the envelope); the store orders its backlog by band first. The bands are deliberately few:

BandSheddable (-1)  measurement / gate traffic. Admitted only into an IDLE
                    execution slot (the server's shed rule, IdleSlot) and,
                    once admitted, claimed after every band-0 job — unless
                    it has waited bandAgingAfter, at which point it is
                    treated as band 0 so a busy node cannot starve it forever.
BandNormal (0)      production digests, reviews, research: the default, and
                    what every pre-0.113.18 delegator sends (no field).
BandUrgent (+1)     reserved for an interactive caller; claimed first.

Anything outside [BandSheddable, BandUrgent] is clamped (ClampBand): a caller cannot buy an arbitrarily high band, and a typo cannot shed itself.

The vocabulary is core's (core.Band*, core.ClampBand) — the delegator stamps it and this store reads it; the aliases keep this package's own text honest.

View Source
const (
	// ErrWithdrawn: the job's own delegator asked for it back (Withdraw).
	ErrWithdrawn = "withdrawn: its delegator gave the job up before it started"
	// ErrReaped: nobody polled the job for the poll lease (reap).
	ErrReaped = "reaped: nothing polled this accepted job within the poll lease, so it never started"
)

The wire's two terminal errors for a job that was taken out of the backlog without ever running. Like ErrNeverStarted they are DIFFERENT FACTS from "interrupted": nothing ran, so a delegator that reads one may re-place the work with no risk of a double run. Stable prefixes: a delegator or an operator may key on them.

View Source
const (
	ErrInterrupted  = "interrupted"
	ErrNeverStarted = "not started: node shut down while this job was queued"
)

ErrInterrupted / ErrNeverStarted are the two shutdown verdicts. They are DIFFERENT FACTS about the node and must never be collapsed: "interrupted" means this node began the work and was cut off — the result may be partially materialized, and a caller re-dispatching elsewhere is redoing work that was underway. "not started" means the job sat in the backlog and no inference ever ran for it, which is the cheapest possible thing to re-dispatch and the clearest thing to tell an operator. Before 0.100.0 the second case could not exist (Accept was start), so every survivor honestly said "interrupted"; now that jobs really do wait, reporting a never-run job as interrupted would be the store inventing history.

View Source
const (
	KVSlotSavePath    = "/fleet/kvslot/save"
	KVSlotRestorePath = "/fleet/kvslot/restore"
)
View Source
const (
	// PowerProfileOK: a profile was applied since this boot began, whole.
	PowerProfileOK = "ok"
	// PowerProfileSkipped: the boot apply did not take, or took in part. Reason says how.
	PowerProfileSkipped = "skipped"
	// PowerProfileUnknown: the node cannot say. A node with no state file is here, with the reason "no_state":
	// a node that applies no profile is not a node in trouble.
	PowerProfileUnknown = "unknown"
)

The values of PowerProfileHealth.State.

View Source
const ChatBodyCap = 8 << 20

ChatBodyCap bounds the forwarded request. A cascade call carries the document it is summarizing or extracting from, so this is sized from the largest context the tiers are configured for (a 128k-token prompt is ~0.5 MB of UTF-8) with room for a grammar and the JSON framing — not from dispatch's 1 MiB envelope cap, which is right for a job descriptor and wrong for a prompt.

View Source
const ChatLanePath = "/fleet/chat"

ChatLanePath is this lane's route. llamaclient.FleetChatPath is the caller's copy of the same string; their equality is pinned by a test in this package (fleetnode may import llamaclient — the reverse would be an import cycle).

View Source
const ChatProxyTimeout = 10 * time.Minute

ChatProxyTimeout bounds the forwarded call end to end on the NODE's side: a cold swap on this node (a llama.cpp cascade seat loads in 10-30 s, and llama-swap will not swap while another model's requests are in flight) plus the generation itself. The caller's own deadline is normally shorter and cancels first through the request context; this is the backstop that keeps a forgotten connection from pinning a proxy goroutine forever.

View Source
const ComposeProjectPath = "/fleet/compose-project"

ComposeProjectPath is the door's route.

View Source
const ComposeProjectTask = "compose-project"

ComposeProjectTask is the fleet task type the project door admits.

View Source
const ComposeTask = "compose-video"

ComposeTask is the fleet task_type of the composition lane (ADR 0059): one HyperFrames render of a VETTED template on this node, returned exactly the way image-gen returns its PNG — the result's video_path lands under this node's media_dir (the default out) and the delegator fetches it by bare name from GET /fleet/media/{name}.

Advertised iff config.ComposeRouteConfigured() — the same predicate the pipeline gates on, so health never promises a lane dispatch would defer.

Template-only, deliberately. A composition is trusted code: HyperFrames' Chrome runs with --no-sandbox and site isolation off. Dispatch needs the fleet bearer like every lane, and this door renders only the node's own vetted templates (render/compose-templates) with typed, escaped variables: a free-form `html` or a node-local `project_dir` sent here would be arbitrary code in an unsandboxed browser on this node, so both are refused at ack time. A whole project goes through the project door (ADR 0071) instead, which a node opts in to (fleet_compose_projects) and which takes it from a holder of the fleet bearer. png-sequence is refused too: it writes a DIRECTORY, which /fleet/media (bare file names only) cannot serve back.

A caller's `out` is dropped for the same trust-boundary reason (see the media-builder comment in tasks.go): the node writes to <media_dir>/compose-<hash8>.<ext>, with the snapshots beside it, and never to a path a tailnet peer named.

View Source
const DefaultPollLease = 60 * time.Second

DefaultPollLease is the poll lease a store built by NewJobs starts with: five times the slowest healthy poll gap (a long poll parks up to MaxJobWaitSec and the delegator sleeps a few seconds between polls), so a job that is being polled can never be mistaken for a ghost.

View Source
const FleetBusyLeaseSecDefault = 120

FleetBusyLeaseSecDefault is the remaining-time threshold above which a held lease of ANY class makes the node a non-target. Two minutes: longer than any ordinary render arbitrated on the node, far shorter than a measurement window or a training run.

View Source
const ForecastBodyCap = 32 << 20

ForecastBodyCap is the request-body ceiling of POST /fleet/forecast: 32 MiB, the size of a long multi-series request with covariates (the forecast server's own limit is the binding one; this only bounds what the door will buffer).

View Source
const ForecastTask = "forecast"

ForecastTask is the lane's fleet task_type: what health lists in supported_task_types and what the job feed shows as `task`.

View Source
const HostPeakPercentile = hostPeakPercentile

HostPeakPercentile is hostPeakPercentile for the callers that word it (the media admission's declaration says which percentile it read).

View Source
const MaxJobWaitSec = 12

MaxJobWaitSec caps `GET /fleet/jobs/{id}?wait=<seconds>`.

TWELVE, and the ceiling is not a taste: it MUST stay below the delegator's pollRequestTimeout (15 s, internal/delegate/run.go), which bounds ONE poll exchange client-side. A server-side wait at or above it cancels every long poll from the client end — the delegator would abandon a connection this node was about to answer, and the feature would read as a transport failure rather than as the completion event it is. 12 + jobWaitWriteSlack (2 s) = 14 s, one second inside that bound, and the pairing is pinned by a test in the external test package (which can read the delegator's own source).

View Source
const MediaJobPath = "/fleet/media-job"

MediaJobPath is the door's route.

View Source
const MediaJobTask = "media-job"

MediaJobTask is the fleet task type the media-job door admits.

View Source
const MeminfoSource = "linux-meminfo"

MeminfoSource is the provider's label in the serve banner and the gate error.

View Source
const PairRelayTask = "pair-relay"

PairRelayTask is the relay door's name in tokenGated; it is not a job type and never reaches the job store.

View Source
const RefusalNotCapable = "not_capable"

RefusalNotCapable is the value of the "refusal" member in the body of a 503 that says "not THIS request" and not "not now": the node is not full and not out of route, it lacks a file this graph names (graphFilesRefusal). A delegator reads the member and not the sentence, so that a node that cannot run one graph is marked not-capable for that ticket alone and is not left alone as a busy one (ADR 0083 Amendment 1). Every other 503 of the dispatch door (queue full, a route that is not CONFIGURED) leaves the member out: those are the node's state, and a delegator is right to look elsewhere for a while.

View Source
const STTUploadPath = "/fleet/stt"

STTUploadPath is the door's route.

View Source
const STTUploadTask = "stt-upload"

STTUploadTask is the door's fleet task_type: what health lists in supported_task_types and what the job feed shows as `task`. The legacy path-taking lane keeps "stt".

View Source
const TenantHeader = core.TenantHeader

TenantHeader carries the delegator's tenant id on a dispatch (0.113.18). A header rather than an envelope field because dispatchEnvelope is decoded with DisallowUnknownFields: a new field would 400 on every node one release behind, and a mixed-version fleet is the normal state of a staggered deploy.

View Source
const TextBodyCap = 1 << 20

TextBodyCap is the request-body ceiling of POST /fleet/text: dispatch's own 1 MiB. The payload is one text plus a label list or a schema, so it never needs more, and the node's max_input_chars trims the text before it reaches the model.

View Source
const TextTask = "text"

TextTask is the lane's fleet task_type: what health lists in supported_task_types and what the job feed shows as `task`.

View Source
const VisionTask = "vision"

VisionTask is the lane's fleet task_type — what health lists in supported_task_types and what the job feed shows as `task`.

View Source
const WithdrawnState = "withdrawn"

WithdrawnState is the `state` a successful DELETE /fleet/jobs/{id} answers with. It is a wire answer only: the job's stored state is the terminal error ErrWithdrawn, which is what a later poll of the id reads.

Variables

This section is empty.

Functions

func AgentLaneAdmissible added in v0.206.0

func AgentLaneAdmissible(cfg config.Config, loopbackListener bool) bool

AgentLaneAdmissible is THE ONE predicate behind the fleet "agent" lane (multi-node delegation, Task 4). Both sides of the lane consult it — the ADVERTISEMENT (health's supported_task_types AND its four agent_* fields) and the ADMISSION (server.go's ack-time guard) — because when those two disagree the delegator does everything right and still fails: it reads health, passes the capability gate, mints a job, dispatches, and eats a 403 into Summary.Failed. Advertising a lane that will refuse is a mis-route by construction, so the two must be the SAME function of the SAME inputs, not two hand-kept-in-sync condition lists (they drifted once already, and health advertised a lane dispatch would 403).

Three conditions, all required:

  1. cfg.FleetAgentEnabled — an explicit operator opt-in, unlike every other task here (see the config field's doc: the BINDING exists on every tier, the worker ROLE is a per-box decision), so default-off keeps the advertisement byte-identical for nodes that never opted in.
  2. A resolvable agent seat (config.AgentPlannerModel's fallback chain). Roster LIVENESS is deliberately NOT checked here — this function feeds ack-time 400s and health advertisement, both of which must stay cheap and network-free; whether the seat is actually served is health's roster-probe job (Task 5) and runAgentTask's own probe at run time.
  3. Safe reachability: a loopback listener, or a bearer token for anything beyond it — an agent lane drives a coding-agent loop, so a tokenless one past loopback is an RCE-class surface.

loopbackListener is a PARAMETER, not derived from cfg, because the two callers know different things: the server holds the RESOLVED listen address (Options.LoopbackListener, computed by the verb from where the bind actually landed) and must use it, while config-only callers pass ConfigLoopbackListen(cfg). Deriving it internally is what let the two sides key on different notions of "loopback" in the first place.

Making it a parameter was not enough on its own: the ADMISSION path reached this function through BuildRequest, which hardcoded ConfigLoopbackListen — so with `fleet_listen: "0.0.0.0:18811"` and `--listen 127.0.0.1:18811` and no token, health (resolved: loopback) advertised the lane while dispatch (config: not loopback) answered 400 `unsupported task_type "agent"`. Both sides now pass the SAME resolved answer down: BuildRequest takes it as an argument rather than deriving one.

func AgentLaneSafelyReachable added in v0.206.0

func AgentLaneSafelyReachable(cfg config.Config, loopbackListener bool) bool

AgentLaneSafelyReachable is condition 3 of AgentLaneAdmissible standing alone: a loopback listener, or a bearer token for anything beyond it.

It is its own function because the dispatch handler needs exactly this condition — and only this one — to pick its refusal: a tokenless lane past loopback is a 403 naming the missing token, while a lane that is merely off or seatless is a plain 400 "unsupported task_type" like any other unbound task. The handler used to re-implement the expression inline, so condition 3 existed twice under a doc claiming ONE predicate governs the lane.

func BuildRequest

func BuildRequest(ctx context.Context, cfg config.Config, loopbackListener bool, taskType string, payload json.RawMessage) (core.Request, func(), error)

BuildRequest translates a fleet dispatch (task_type + opaque payload) into the core.Request the pipeline runs, mirroring the MCP handlers' param mapping exactly. cleanup is ALWAYS non-nil (defer it unconditionally); for run-graph it removes the materialized temp files. Errors are caller mistakes (the server's 400s): unknown/unconfigured task_type (listing this box's supported set), malformed payload JSON, or a missing/invalid required field.

ctx is threaded through to the pipeline-job family's ack-time ref fetch (buildPipelineJob -> FetchRefs): the caller is server.go's handleDispatch, which passes r.Context(), so a dispatch whose client vanishes mid-ack stops fetching refs instead of racing to completion against context.Background().

loopbackListener is the RESOLVED serve listener's verdict, threaded from Options.LoopbackListener — the SAME value health advertises from — so admission and advertisement are one predicate over one input. It is a required argument rather than a defaulted one precisely because it was derived internally before: BuildRequest called ConfigLoopbackListen while health used the resolved listener, and the two disagreed for every node whose --listen flag diverges from fleet_listen in the loopback dimension. The agent lane is the only task whose verdict depends on it; every other task ignores it entirely.

func ChatLaneAdmissible added in v0.206.0

func ChatLaneAdmissible(cfg config.Config, loopbackListener bool) bool

ChatLaneAdmissible is THE predicate behind the chat lane, on both sides of the wire — the health advertisement (`chat_lane`) and this handler's own gate — exactly as AgentLaneAdmissible and VisionLaneAdmissible are for theirs. Health must never advertise a lane the handler would refuse: the delegator reads `chat_lane` alone to decide a lane base is usable, and a lane advertised past a tokenless non-loopback listener would send every cascade call into a 403.

Two conditions: a bound llama-swap `endpoint` to forward to, and safe reachability (loopback listener, or a fleet_auth_token for anything beyond it). There is deliberately no model condition — the lane serves whatever this node's roster serves, checked per call.

func ClampBand added in v0.206.0

func ClampBand(b int) int

ClampBand is core.ClampBand.

func ComposeProjectBodyCap added in v0.206.0

func ComposeProjectBodyCap(cfg config.Config) int64

ComposeProjectBodyCap is the largest body the door reads: the bundle cap in base64 plus room for the rest of the payload.

func ConfigLoopbackListen added in v0.206.0

func ConfigLoopbackListen(cfg config.Config) bool

ConfigLoopbackListen is the CONFIG-side view of the bind, for callers with no resolved listener to consult. An empty fleet_listen means the operator never overrode config.Default()'s loopback bind, so it counts as loopback (netguard.LoopbackAddr itself fails closed on ""). Anything the server decides keys on Options.LoopbackListener instead, which stays authoritative when a --listen flag diverges from the config.

func DedicatedVramTotalGiB added in v0.206.0

func DedicatedVramTotalGiB() (float64, error)

DedicatedVramTotalGiB is a WDDM registry read — off-Windows it always errors (the UMA heuristic in fleet-serve then simply doesn't fire).

func Families

func Families(cfg config.Config) []string

Families returns the loadable model families for the advertised tasks, deduplicated, in task order. nil when nothing is bound.

func FetchRefs added in v0.206.0

func FetchRefs(ctx context.Context, refs map[string]string, destDir string,
	extraAllow []string, capMB int) (paths map[string]string, cleanup func(), err error)

FetchRefs downloads each ref into destDir (created if needed) and returns ref key -> absolute local path. Any failure aborts the whole set (the returned cleanup removes destDir). Fetches are refused unless the URL host is a tailnet CGNAT address (100.64.0.0/10), loopback, or in extraAllow ("host:port" entries). Each body is capped at capMB MiB and must start with PNG/JPEG/WebP magic bytes.

func ForecastLaneAdmissible added in v0.206.0

func ForecastLaneAdmissible(cfg config.Config, loopbackListener bool) bool

ForecastLaneAdmissible is THE predicate behind the forecast lane, on both sides of the wire (health advertisement AND ack-time admission, the vision lane's discipline): the node binds a forecast model, and the listener is safely reachable (loopback, or a fleet_auth_token for anything beyond it).

func InstalledJSONPath added in v0.206.0

func InstalledJSONPath() string

InstalledJSONPath resolves where the installer wrote its manifest: $OFFLOAD_HOME/installed.json, defaulting OFFLOAD_HOME to ~/offload-stack exactly like install.ps1 does.

func MediaJobBodyCap added in v0.206.0

func MediaJobBodyCap(cfg config.Config) int64

MediaJobBodyCap is the largest body the door reads: the bundle cap in base64 plus room for the rest of the payload.

func PairRelayAdmissible added in v0.206.0

func PairRelayAdmissible(cfg config.Config, loopbackListener, localIdentity bool) bool

PairRelayAdmissible is THE predicate behind the relay door, on both sides of the wire (the health advertisement and the handler): this node has a PAIR identity of its own, and the lane's reachability rule holds (a loopback listener, or a fleet_auth_token for anything beyond it).

func ParseSmiMemory

func ParseSmiMemory(out string) (totalGiB, usedGiB float64, err error)

ParseSmiMemory parses `nvidia-smi --query-gpu=memory.total,memory.used --format=csv,noheader,nounits` output ("16384, 1234", MiB) into GiB values. Whitespace and CRLF are tolerated (nvidia-smi emits \r\n on Windows); on a multi-GPU box the first line (GPU 0) wins. A total <= 0 or a negative used is an error: the contract treats vram_total_gb <= 0 as a failed probe, so a zero-total parse must never become a publishable snapshot.

func ProcessNames added in v0.206.0

func ProcessNames() (map[int]string, error)

ProcessNames is the non-Windows stub; the caller falls back to nvidia-smi's own process_name column, which needs no separate lookup.

func ResetMediaRoutesCache added in v0.206.0

func ResetMediaRoutesCache()

ResetMediaRoutesCache drops every cached verdict, so the next read goes to the disk again.

func STTUploadAdmissible added in v0.206.0

func STTUploadAdmissible(cfg config.Config, loopbackListener bool) bool

STTUploadAdmissible is THE predicate behind the door, on both sides of the wire (the health advertisement and the ack-time gate): a bound whisper model and safe reachability, the vision lane's rule — a loopback listener, or a fleet_auth_token for anything beyond it.

func STTUploadBodyCap added in v0.206.0

func STTUploadBodyCap(cfg config.Config) int64

STTUploadBodyCap is the request-body ceiling of POST /fleet/stt for cfg: the node's upload cap in base64 plus slack.

func SetMediaRoutesSourceForTest added in v0.206.0

func SetMediaRoutesSourceForTest(fn func(config.Config) []mediacap.Route) (restore func())

SetMediaRoutesSourceForTest replaces the route derivation and returns the function that restores it. It is for tests in OTHER packages that drive the real advertiser (Families, SupportedTasks) with a fixture config binding scripts that do not exist on the test machine: such a config is BOUND-BUT-MISSING to the real derivation, and the advertisement honestly drops it. Production never calls it.

func SupportedTasks

func SupportedTasks(cfg config.Config) []string

SupportedTasks returns the fleet task_types this machine's config actually serves, in stable order. nil when nothing is bound. The agent lane's listener condition is judged from the config (ConfigLoopbackListen); a server with a resolved listen address calls SupportedTasksFor instead.

func SupportedTasksFor added in v0.206.0

func SupportedTasksFor(cfg config.Config, loopbackListener bool) []string

SupportedTasksFor is SupportedTasks with the RESOLVED listener answer supplied — what /fleet/health advertises, so supported_task_types and the agent_* block can never disagree with what dispatch will admit.

func SweepKVSlotDir added in v0.206.0

func SweepKVSlotDir(dir string, capBytes int64, keep string) error

SweepKVSlotDir is kvslot.SweepDir, kept under its old name for this package's callers.

func SweepOrphanedInputDirs added in v0.206.0

func SweepOrphanedInputDirs(cfg config.Config, now time.Time) (swept int, err error)

SweepOrphanedInputDirs removes extracted media inputs no job holds any more: fleet-serve calls it at startup, so a crash never leaves them for good. Only directories older than the longest media timeout plus an hour go, so a second process sharing the media dir keeps the ones it is rendering from. Every failure is collected and none stops the rest of the sweep.

func SweepOrphanedPipelineJobs added in v0.206.0

func SweepOrphanedPipelineJobs(cfg config.Config) (swept, kept int, err error)

SweepOrphanedPipelineJobs removes the orphaned entries directly under cfg.BaseDir()/pipeline-jobs/ and reports how many it removed and how many it kept. Missing pipeline-jobs/ (nothing configured yet, or a fresh install) is not an error — (0, 0, nil).

Called ONCE at fleet-serve startup, BEFORE listening (main.go's runFleetServe). Jobs are in-memory (internal/fleetnode/jobs.go's Jobs store) — an ungraceful stop (crash, kill -9, power loss) loses every in-flight job's state, but its materialized directory on disk survives. Left in place, that orphaned directory would permanently refuse every FUTURE dispatch that reuses its job_spec.id: buildPipelineJob's exclusive os.Mkdir collision guard has no way to distinguish "a real still-running job" from "a directory nobody is ever going to finish or clean up".

What fleet-serve itself materializes here (BuildRequest's agent-<n>, accel-<n> and pipeline job-id dirs) carries no owner marker, and at startup, before this process has accepted a single dispatch, every one of them is orphaned by definition. But fleet-serve is not the only writer in this root: the delegator's in-process local placement (pipeline.RunAgentContract) mints agent-local-* dirs here from processes that are not fleet-serve — the MCP server, the delegate and research commands, the fleet smoke — and that outlive its restarts, so a run's dir can be on disk, and in use, at this very instant. Sweeping those out from under their runs failed every local run in flight on the box at each fleet-serve restart (register C-78). So each entry is judged by who owns it (internal/jobdir):

  • a MARKED entry is orphaned iff its owner process is gone (gpulease.PIDAlive, which reads a process it cannot inspect as alive, the conservative direction; the id is probed in THIS process's process-id space, which is why one base directory must not be shared across spaces, see internal/jobdir) or the entry is older than jobdir.MaxRunLifetime, which bounds a process id recycled by an unrelated process;
  • an UNMARKED agent-local-* entry was made by a delegator older than the marker (a long-lived MCP process keeps its old binary for days after a deploy, so this case is live on the day the marker ships) and has no owner to ask: orphaned iff older than jobdir.MaxRunLifetime;
  • every other UNMARKED entry is fleet-serve's own: orphaned.

Age is the entry's modification time, which a run leaves alone after its first moments (everything it writes goes inside context/). A marker that cannot be read (caught half written, garbled) counts as no marker, which for an agent-local-* entry means "young, keep" — the same conservative direction, and the reason the unmarked rule exists beside the marked one: a sweep can list a delegator's dir between its creation and its marker.

A removal decided by age alone is the one the sweep can make against a run that is still going (its owner alive, or no owner to ask), so it logs the dir, its age and what is known of its owner before removing it. The ordinary removals (a dead owner, fleet-serve's own) and the keeps are in the counts only.

A kept entry is a decision, never an error. An entry the sweep cannot judge (its modification time cannot be read) is kept and reported as an error, and a removal that fails is reported the same way; both are counted as neither removed nor kept. Every such failure is collected (errors.Join) and none aborts the sweep of the REST of the entries — one bad directory blocking one job_spec.id forever is a much smaller failure than a startup crash over it.

func SweepOrphanedProjectDirs added in v0.206.0

func SweepOrphanedProjectDirs(cfg config.Config, now time.Time) (swept int, err error)

SweepOrphanedProjectDirs removes extracted project trees no job holds any more: fleet-serve calls it at startup, so a crash never leaves them for good. Only trees older than the compose timeout plus an hour go, so a second process sharing the compose cache keeps the ones it is rendering. Every failure is collected and none stops the rest of the sweep.

func SweepOrphanedSTTUploads added in v0.206.0

func SweepOrphanedSTTUploads(cfg config.Config, now time.Time) (swept int, err error)

SweepOrphanedSTTUploads removes upload files no job holds any more: fleet-serve calls it at startup, so a crash between the write and the cleanup never leaves audio on disk for good. Only files older than the longest transcription plus an hour go, so a second process sharing the media dir keeps the ones it is running. Every failure is collected and none stops the rest of the sweep.

func SweepSTTTranscripts added in v0.206.0

func SweepSTTTranscripts(cfg config.Config, now time.Time) (swept int, err error)

SweepSTTTranscripts removes the transcript files of stt upload jobs that are older than the node's transcript TTL (fleet_stt_transcript_ttl_min; a negative value keeps them for good). Only names the upload door's outputs can have are touched, directly under media_dir. Every failure is collected and none stops the rest of the sweep.

func Terminal added in v0.206.0

func Terminal(s JobState) bool

Terminal reports whether a state is one a job never leaves (write-once).

func TextLaneAdmissible added in v0.206.0

func TextLaneAdmissible(cfg config.Config, loopbackListener bool) bool

TextLaneAdmissible is THE predicate behind the text lane, on both sides of the wire (health advertisement AND ack-time admission, the vision lane's discipline): the node's tier declares at least one text task, and the listener is safely reachable (loopback, or a fleet_auth_token for anything beyond it).

func TreeDedicatedGiB

func TreeDedicatedGiB(rootPid int) (float64, error)

TreeDedicatedGiB is the non-Windows stub for the PDH per-process tree sampler (vram_windows.go): the "\GPU Process Memory" counter set is a WDDM facility, so off-Windows it always errors and callers fall back to the nvidia-smi global-delta source. Present so portable callers (the pipeline's sampler composition) compile everywhere; sampler mode "auto" never selects the tree source off-Windows anyway.

func TreeDedicatedPlusSharedGiB added in v0.206.0

func TreeDedicatedPlusSharedGiB(rootPid int) (float64, error)

TreeDedicatedPlusSharedGiB (fleet_sampler "pdh-shared", J3) is likewise a WDDM/PDH facility — off-Windows it always errors.

func UMAFromProfile added in v0.206.0

func UMAFromProfile(profile string) (uma, ok bool)

UMAFromProfile reports whether the profile is a unified-memory iGPU class — which changes BOTH capacity composition (carve-out + WDDM shared budget) and usage composition (Dedicated + Shared). An SoC (rockchip-rk3588) is unified through and through: it has no carve-out at all, and its provider (MeminfoUMAProbe) composes from RAM alone. Pure; unit-tested. ok is false when the profile carries no UMA signal (caller falls back to a capacity heuristic).

func VendorArchFromProfile added in v0.206.0

func VendorArchFromProfile(profile string) (vendor, arch string)

VendorArchFromProfile maps an installer profile id to the (vendor, arch) pair the health payload advertises. Pure; unit-tested. Unknown/empty profiles return ("unknown", "unknown") — honest, never a guessed vendor.

func VisionBodyCap added in v0.206.0

func VisionBodyCap(cfg config.Config) int64

VisionBodyCap is the request-body ceiling of POST /fleet/vision for cfg: the node's vision_max_image_bytes inflated by base64 (4/3) plus slack. A config that never set the cap gets the default's 6 MB, the same number the pipeline loader applies to the decoded bytes.

func VisionLaneAdmissible added in v0.206.0

func VisionLaneAdmissible(cfg config.Config, loopbackListener bool) bool

VisionLaneAdmissible is THE predicate behind the vision lane, on both sides of the wire (health advertisement AND ack-time admission, the same discipline as AgentLaneAdmissible): a bound vision_model, and safe reachability — a loopback listener or a fleet_auth_token for anything beyond it.

Types

type AccelPayload added in v0.206.0

type AccelPayload struct {
	Accelerator string         `json:"accelerator"`
	Tool        string         `json:"tool"`
	Args        map[string]any `json:"args,omitempty"`
	ImageB64    string         `json:"image_b64,omitempty"`
	ImageName   string         `json:"image_name,omitempty"`
}

AccelPayload is the wire shape of a fleet "accel" job (Coral design Phase B): one accelerator tool call for a box that lacks the device (never the Hailo-8L, which is local-only — register E-08, see buildAccel). The image, when the tool takes one, travels INSIDE the job as base64 — the caller's image_path is on the caller's disk, which this node cannot read — and lands in a job-scoped directory that lives exactly as long as the job.

type AcceptSpec added in v0.206.0

type AcceptSpec struct {
	// Agent marks a job created by an AGENT dispatch, which the server's
	// poll-auth gate keys on. The marker lives ON the job record — not in a
	// server-side id set — so it is written atomically with creation (no window
	// where a poller can observe the job before it is marked) and is evicted
	// WITH the record (an id set would outlive the janitor and leak forever).
	Agent bool
	// Gated applies the agent lane's poll-auth rule to a job that is NOT an
	// agent run (JobView.Gated) — the vision lane sets it.
	Gated bool
	// Uncapped exempts this job's EXECUTION from maxConcurrent. The exemption
	// is for lanes that already serialize themselves and whose work never
	// touches the shared llama-swap text endpoint the cap exists to protect —
	// see the server's concurrencyCapped for the rule and the reasoning. An
	// uncapped job still occupies backlog (queue_depth) exactly like any other,
	// so the node's admission ceiling still bounds it.
	Uncapped bool
	// OnDropped is invoked EXACTLY ONCE if this job is admitted and then never
	// runs — today, only when drain marks it ErrNeverStarted. It is the seam
	// that keeps the server's "temp files live exactly as long as the job"
	// promise true now that admission and execution are separate. Never called
	// for a job that was claimed: the run's own defer owns cleanup from then on.
	OnDropped func()
	// OnEvict is invoked once, outside the store's lock, when the janitor evicts this job's record
	// after its terminal state outlived the ttl. It is where a job releases what it left on disk for
	// its poller (an stt upload's transcript files), so the record and its outputs do not outlive
	// one another by more than a janitor tick.
	OnEvict func()
	// Task/Model are the /fleet/jobs feed's metadata (see JobView). Task is
	// the dispatch's task_type verbatim; Model is the agent seat for
	// core.TaskAgentRun (the seat is the meaningful "model" for an agent run,
	// not the caller's model_family) and env.ModelFamily otherwise. Both are
	// display-only — nothing in this package branches on them.
	Task, Model string
	// Band is the scheduling band (BandSheddable / BandNormal / BandUrgent;
	// callers pass it through ClampBand). The backlog is claimed highest band
	// first; a sheddable job ages into band 0 after bandAgingAfter.
	Band int
	// Tenant identifies the DELEGATOR (one MCP server = one Claude session, or
	// one CLI process) so the claim order can round-robin across tenants within
	// a band. Empty = one anonymous tenant, which is exactly the pre-0.113.18
	// behaviour (pure arrival order) for a fleet of older delegators.
	Tenant string
	// PollLeased marks a job whose dispatcher polls for its result: a pushed
	// agent dispatch. The store then treats a job that sits `accepted` with
	// nobody polling it for the poll lease as abandoned, and skips, reaps and
	// stops counting it (ADR 0064). It is NOT set for a job the pull queue
	// claimed (its result travels by ack, nobody polls this node for it), nor
	// for media and vision jobs, whose pollers are other clients with cadences
	// this node does not control.
	PollLeased bool
}

AcceptSpec carries the per-admission facts the store needs but cannot infer from the run closure. It exists so the three flags stay ORTHOGONAL: there is no Accept-method-per-combination to keep in sync, and adding a fourth fact later does not multiply the API surface.

type Artifact added in v0.206.0

type Artifact struct {
	Name   string `json:"name"`
	Bytes  int64  `json:"bytes"`
	SHA256 string `json:"sha256"`
}

Artifact is one output file of a media job: its bare name in media_dir, its size and its sha256.

type BaselineTracker added in v0.206.0

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

BaselineTracker records the idle baseline over time. Safe for concurrent use: the sampler writes it while /fleet/health reads it.

func (*BaselineTracker) Baseline added in v0.206.0

func (b *BaselineTracker) Baseline() (gib float64, at time.Time, ok bool)

Baseline returns the last idle observation.

func (*BaselineTracker) Observe added in v0.206.0

func (b *BaselineTracker) Observe(usedGiB float64, oursLoaded bool, now time.Time)

Observe feeds one sample. Only idle moments (nothing of ours loaded) move the baseline, so a busy node keeps the last honest measurement instead of drifting upward as our own models load.

func (*BaselineTracker) Verdict added in v0.206.0

func (b *BaselineTracker) Verdict(usedGiB float64, oursLoaded bool) ReclaimVerdict

Verdict evaluates the current sample against the tracked baseline.

type ComposeProjectPayload added in v0.206.0

type ComposeProjectPayload struct {
	JobID        string    `json:"job_id"`
	Bundle       string    `json:"bundle"`        // base64 (standard encoding) of a gzip-compressed tar
	BundleSHA256 string    `json:"bundle_sha256"` // hex sha256 of the decoded bundle bytes
	Composition  string    `json:"composition,omitempty"`
	Format       string    `json:"format,omitempty"`
	FPS          float64   `json:"fps,omitempty"`
	Quality      string    `json:"quality,omitempty"`
	Resolution   string    `json:"resolution,omitempty"`
	Workers      float64   `json:"workers,omitempty"`
	Strict       *bool     `json:"strict,omitempty"`
	Snapshots    []float64 `json:"snapshots,omitempty"`
}

ComposeProjectPayload is the POST /fleet/compose-project body.

type DeviceProbe added in v0.206.0

type DeviceProbe func() ([]GPUDevice, error)

DeviceProbe returns the full per-device VRAM breakdown (nvidia-smi only today — vram_windows.go's GenericWindowsProbe documents why the windows-generic WDDM source cannot produce one: its PDH reads sum blindly across adapter instances with no per-adapter identity preserved). Unlike MemProbe, a DeviceProbe never collapses to a single number itself — HeadlineDevice does that deliberately, once, in the sampler, so there is exactly one place in the codebase that decides which device is "the" device for the health payload's headline pair.

func AmdgpuSysfsDeviceProbe added in v0.206.0

func AmdgpuSysfsDeviceProbe(drmRoot string, uma bool) DeviceProbe

AmdgpuSysfsDeviceProbe is the per-device sibling (gpu_devices[] in health): every amdgpu card under drmRoot, VRAM-only capacity/usage plus the GTT pool folded in when uma is true — the same composition as the MemProbe so the headline pair and the device list never disagree.

func SmiDeviceProbe added in v0.206.0

func SmiDeviceProbe(run func() (string, error)) DeviceProbe

SmiDeviceProbe adapts the nvidia-smi multi-device CSV runner (index, name, memory.total, memory.used) to a DeviceProbe via ParseSmiMemoryDevices — the devices-aware sibling of SmiProbe/ParseSmiMemory. run must invoke the index+name query (a different nvidia-smi invocation than the plain memory.total,memory.used one SmiProbe/ParseSmiMemory expect); the two are kept separate rather than reusing one query so ParseSmiMemory's existing 2-field CSV contract (and its other caller, the pipeline's per-process footprint delta sampler) never breaks.

type FootprintEntry

type FootprintEntry struct {
	ModelFamily string  `json:"model_family"`
	Quant       string  `json:"quant,omitempty"`
	TaskType    string  `json:"task_type,omitempty"`
	VramPeakGiB float64 `json:"vram_peak_gb"`
	// HostPeakGiB / HostResidentPeakGiB are the measured peaks of the render's process tree (private bytes,
	// resident set). Additive: a reader that does not know them ignores them.
	HostPeakGiB         float64 `json:"host_peak_gb,omitempty"`
	HostResidentPeakGiB float64 `json:"host_resident_peak_gb,omitempty"`
}

FootprintEntry is the wire shape /fleet/health advertises (contract v2).

type Footprints

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

Footprints is a concurrency-safe, file-backed footprint store. Every Record persists synchronously via an atomic temp+rename write; a corrupt or missing file opens as empty (logged once, never a crash) so a bad disk state can only cost history, never availability.

func OpenFootprints

func OpenFootprints(path string) *Footprints

OpenFootprints loads the store at path (missing → empty; corrupt → empty with one log line).

func (*Footprints) Entries

func (f *Footprints) Entries() []FootprintEntry

Entries returns the wire-shaped entries with vram_peak_gb > 0, sorted by (family, quant, task) for stable health output.

func (*Footprints) HostPeak added in v0.206.0

func (f *Footprints) HostPeak(family, quant, task string) (HostPeaks, bool)

HostPeak reports what the key's renders were measured to hold on the host, and false when none was measured.

func (*Footprints) Path

func (f *Footprints) Path() string

Path returns the store's backing file path (fleet-measure prints the on-disk records — vram_peak_gb plus the raw observed_peak_gb/samples state the Afterburner validation procedure compares against).

func (*Footprints) Record

func (f *Footprints) Record(family, quant, task string, observedGiB float64)

Record folds one observed per-render peak (GiB) into the (family, quant, task) entry: max-keep on the observation, vram_peak_gb = raw max observed rounded 0.1 (no padding), samples++, then persist. Non-positive observations are dropped — a zero/negative "peak" is a sampling failure, and the contract forbids advertising vram_peak_gb <= 0.

func (*Footprints) RecordHost added in v0.206.0

func (f *Footprints) RecordHost(family, quant, task string, privateGiB, residentGiB float64)

RecordHost folds one render's host peaks into the (family, quant, task) entry: the max of each, runs++, then persist. A non-positive private peak is a sampling failure (an unreadable process table, a runner that exited before the first tick) and is dropped, so a run that measured nothing is never counted as a run that held nothing. The resident peak is kept as the max of whatever was read.

func (*Footprints) ReloadIfChanged

func (f *Footprints) ReloadIfChanged()

ReloadIfChanged re-reads the backing file when its mtime moved past the last load, MAX-MERGING disk records into memory (higher observed peak wins per key) so a record written by ANOTHER process — fleet-measure priming the store while fleet-serve is up was the live-found case — becomes visible to this process's Entries() without a restart, and an in-memory observation is never regressed by an older on-disk one. Cheap (one stat) when nothing changed; safe to call from the health accessor (no locks beyond the store's own, no spawns).

type ForecastPayload added in v0.206.0

type ForecastPayload struct {
	JobID   string          `json:"job_id"`
	Request json.RawMessage `json:"request"`
}

ForecastPayload is the wire body of POST /fleet/forecast. job_id is the caller-minted id exactly as on /fleet/dispatch; request is the forecast server's payload object (series, prediction_length, quantiles, covariates, switches), passed through to the pipeline as-is.

type GPUDevice added in v0.206.0

type GPUDevice = gpuprobe.Device

GPUDevice is one parsed nvidia-smi device line — an ALIAS of gpuprobe.Device since 0.116.0, when the parser moved into that leaf so the composite tier's placement guards and this health sampler read every card through ONE parser (a second reader could disagree with the first about a card's free memory, and the display-card guard fails closed on that number). The alias keeps every caller, the gpu_devices[] JSON shape (docs/FLEET-NODE.md) and every existing test compiling unchanged. UUID is what primary_gpu_uuid pins against (config.Config.PrimaryGPUUUID / SelectHeadlineDevice) — an operator reads it straight off a running node's /fleet/health gpu_devices[] to fill that config key in.

func HeadlineDevice added in v0.206.0

func HeadlineDevice(devices []GPUDevice) GPUDevice

HeadlineDevice picks which parsed device the health payload's single vram_total_gb/vram_free_gb pair describes: the LARGEST-total card (ties broken by free memory), never enumeration order — a render binds to one CUDA device and nvidia-smi's PCI-bus order says nothing about which. It is a thin wrapper over gpuprobe.HeadlineDevice (the rule, its rationale and its near-twin-card limitation are documented there) so the fallback the health sampler applies is the same function the placement package sees. This is the FALLBACK rule — SelectHeadlineDevice applies it only when no primary_gpu_uuid is pinned (or the pinned UUID isn't present).

devices must be non-empty — callers only reach this after a successful parse, which never returns an empty slice.

func ParseSmiMemoryDevices added in v0.206.0

func ParseSmiMemoryDevices(out string) ([]GPUDevice, error)

ParseSmiMemoryDevices parses the per-device nvidia-smi query (index, uuid, name, memory.total, memory.used[, utilization.gpu]) into an ordered []GPUDevice. It is a thin wrapper over gpuprobe.ParseSmiMemoryDevices — see that function for the full contract (skip-not-fail per line, used > total skipped, zero valid devices is an error) — kept here so the health sampler's callers and the pins in vram_test.go name the fleetnode symbol they always did. ParseSmiMemory (above) stays separate and unchanged: it serves the pipeline's per-process footprint delta sampler over a different (2-field) query, and its behavior cannot change out from under that caller.

func SelectHeadlineDevice added in v0.206.0

func SelectHeadlineDevice(devices []GPUDevice, primaryUUID string) (head GPUDevice, warning string)

SelectHeadlineDevice is the full headline-selection rule the health sampler uses: an operator-pinned primary_gpu_uuid (config.Config.PrimaryGPUUUID) takes priority over HeadlineDevice's largest-total heuristic, because UUID is the ONLY identifier this codebase can rely on across a reboot/reseat. Canonical guidance (CMP tier notes): pin by GPU UUID, NEVER index — verified live on <node-b> 2026-08-04: nvidia-smi's own index 0 is the RTX 5060 Ti, but ComfyUI's CUDA ordering (CUDA_DEVICE_ORDER=FASTEST_FIRST) binds cuda:0 to the RTX 5070 Ti at index 1, and the two cards can't be told apart by total VRAM either (16311 vs 16303 MiB — HeadlineDevice's rule picks whichever has 8 MiB more, not whichever is faster). A UUID survives all of that: it is burned into the card, unaffected by enumeration order, CUDA ordering, or which PCI slot it's currently seated in.

Behavior:

  • primaryUUID == "": HeadlineDevice(devices), no warning — today's behavior, byte-identical.
  • primaryUUID set and found among devices: that device wins outright, regardless of its total/free VRAM — no warning.
  • primaryUUID set but NOT found (typo, or the pinned card is actually gone): falls back to HeadlineDevice(devices), AND returns a non-empty warning naming the missing UUID. A silent fallback here would hide a typo'd config (or a genuinely missing card) forever, which is worse than the original enumeration-order bug this whole file fixes — at least that one was consistently wrong in a discoverable way. The caller (Sampler.sampleDevices) is responsible for actually emitting the warning (once, not once per 2s tick) — this function stays pure and side-effect-free so it's trivially unit-testable.

devices must be non-empty, same precondition as HeadlineDevice.

The match is case-INsensitive (strings.EqualFold) and primaryUUID itself is trimmed by config.Load before it ever reaches here — an operator is expected to copy the UUID straight out of /fleet/health's gpu_devices[], and a copy/paste can pick up a trailing newline/space or a different-cased-but-identical UUID (nvidia-smi lowercases; some tools that display UUIDs don't) without the operator noticing either difference. Neither should be enough to silently drop a correct pin to the fallback rule and its warning.

type GenericProvider added in v0.206.0

type GenericProvider struct {
	Probe  MemProbe
	Source string
}

GenericProvider names the OS's generic memory source so the serve banner and the gate error say which one was tried — "windows-generic" on Windows, "linux-amdgpu" on Linux — instead of hardcoding the Windows name.

type HostPeaks added in v0.206.0

type HostPeaks struct {
	PrivateGiB, ResidentGiB       float64
	Runs                          int
	MaxPrivateGiB, MaxResidentGiB float64
	Window                        int
}

HostPeaks is what the renders of one key were measured to hold on the host: the private and the resident memory of the render's process tree (GiB).

PrivateGiB and ResidentGiB are the CALIBRATION figures: the hostPeakPercentile-th percentile of the last hostRecentRuns runs' peaks, so one inflated run is not the answer and a bad run leaves the window after hostRecentRuns more (F56). The all-time maxima ride beside them (MaxPrivateGiB, MaxResidentGiB: what the wire still advertises as host_peak_gb and host_resident_peak_gb). Runs counts every run ever recorded and Window the ones the store still holds.

type ImageFamily added in v0.206.0

type ImageFamily struct {
	Name          string  `json:"name"`
	Family        string  `json:"family"`
	Engine        string  `json:"engine"`
	License       *string `json:"license"`
	CommercialUse *bool   `json:"commercial_use"`
	Default       bool    `json:"default"`
}

ImageFamily is one image binding a fleet dispatcher can select with the image-gen payload's `family`, as /fleet/health publishes it. License and CommercialUse are null when the binding declares none (UNKNOWN, never "commercial-safe"); a dispatcher must not route brand work to a family whose commercial_use is false.

func ImageFamilies added in v0.206.0

func ImageFamilies(cfg config.Config) []ImageFamily

ImageFamilies lists this node's image bindings — the default first (when there is one — a family-only node has none, D1), then every named family — whenever this node has at least one NAMED family bound. A default-only node (no families) keeps health's pre-0.134 shape (no image_families key at all): the old gate here also required ImageRouteConfigured() (the DEFAULT binding), which made this nil for a family-only node even though its families were fully configured and reachable through the CLI door (<node-f> wave session 5d227d30 §2a) — the two binding sets (default vs. named) are independent, so only the family count gates this. Config-derived like the task list; the per-family file verdicts live in offload_status/doctor on the node itself.

type ImageRecipeHealth added in v0.206.0

type ImageRecipeHealth struct {
	Name    string `json:"name"`
	Default bool   `json:"default"`
	Digest  string `json:"digest"`
	mediacap.Recipe
}

ImageRecipeHealth is one row of /fleet/health image_recipes: a binding a payload's `family` can select, and what it is. Name is the family's request-facing name (the default binding's own family name, which may be empty on a node whose default is the generic graph); Default marks the default binding. Digest is empty while any of the family's files has no content fingerprint yet (their `fingerprint` says "pending" or "unreadable"): such a row names what it will be and is not an identity.

func ImageRecipes added in v0.206.0

func ImageRecipes(cfg config.Config) []ImageRecipeHealth

ImageRecipes lists the recipes of this node's ComfyUI image bindings, the default first, then every named family in name order (config.ImageFamilies' order). A binding is listed only when its recipe names a checkpoint: a binding that leaves the file to the runner's own default has nothing to identify, and a node must not be matched on a name alone. An sd.cpp binding has no recipe. Missing files are listed (with bytes -1) so a delegator can say which file a node lacks; such a recipe never matches. It never waits for a hash (see the file header).

type InstalledInfo added in v0.206.0

type InstalledInfo struct {
	Profile string `json:"profile"`
	Backend string `json:"backend"`
	// Accelerators are the additive devices the installer detected (ADR 0024);
	// advertised (minus local-only devices, config.FleetVisibleAccelerators) so a
	// delegator can route NPU-owned work here.
	Accelerators []string `json:"accelerators,omitempty"`
	// AltBackends are the extra serving backends THIS install rendered beside the
	// primary one (today: ["cpu"] when install.sh was given --llama-bin-cpu). The
	// installer writes only what it rendered, so health never advertises a route
	// the box cannot serve.
	AltBackends []string `json:"alt_backends,omitempty"`
}

InstalledInfo is the slice of the installer's manifest ($OFFLOAD_HOME/ installed.json) the fleet node needs: the hardware profile detect.ps1 classified (the vendor/arch/UMA truth — no re-derivation from product-name regexes) and the serving backend.

func ReadInstalledInfo added in v0.206.0

func ReadInstalledInfo(path string) (InstalledInfo, error)

ReadInstalledInfo loads InstalledInfo from an installed.json path. A missing or unparsable manifest returns a zero value and the error — callers treat that as "no manifest" (pre-installer box), never fatal by itself.

func (InstalledInfo) Backends added in v0.206.0

func (i InstalledInfo) Backends() []string

Backends is the ordered list health advertises: the primary backend first, then the alternates the install rendered. Empty (omitted from health) when the manifest carries no backend — every pre-manifest node stays byte-identical.

type JobState

type JobState string

JobState is the contract's job lifecycle: accepted → running → done|error.

const (
	JobAccepted JobState = "accepted"
	JobRunning  JobState = "running"
	JobDone     JobState = "done"
	JobError    JobState = "error"
)

type JobView

type JobView struct {
	ID    string
	State JobState
	Data  json.RawMessage
	Error string
	// ErrClass is the err_class the failed run's lane filed its deferral under (core.Meta.ErrClass: gpu_busy,
	// gpu_queued, timeout, ...), "" for a job that did not fail or whose failure carried none. It rides the
	// poll beside Error as `err_class`, so the box that asked can tell a call another job held back from one
	// that ran and broke without reading the reason's words (see classedError).
	ErrClass string
	// Agent marks a job created by an AGENT dispatch (AcceptAgent). The server
	// keys /fleet/jobs/{id} bearer auth on it, together with Gated (a job of
	// any other task type is gated too); Agent alone says which rows of the
	// jobs feed are agent runs. Never serialized to the wire: jobWire's shape
	// is unchanged.
	Agent bool
	// WallSec (register D-116) is the wall the RUNNING job is executing under,
	// as the executing lane reported it (core.ReportWall). 0 = not reported
	// yet, or a lane that reports none. It rides the per-job poll payload so a
	// delegator polling a timeout_auto contract can bound its own clock by the
	// node's sized wall instead of by the wire cap — the node's wall is
	// authoritative, and a delegator must never abandon a job the node is
	// still running inside it.
	WallSec int
	// Progress (0.131.0, liveness walls) is the run's last liveness report
	// (core.ReportProgress), published WHILE THE JOB RUNS so the delegator
	// polls on progress rather than on a clock. nil until the lane reports one.
	Progress *core.LiveProgress
	// Gated marks a job whose poll rides the SAME bearer rule as an agent
	// job without being one (0.116.0: the vision lane — its result is the
	// caller's image judged in prose; every task type since, see tokenGated). Kept apart from Agent so the jobs feed
	// still says truthfully which rows are agent runs. Never serialized.
	Gated bool
	// Task/Model/AcceptedAt/StartedAt/FinishedAt are the /fleet/jobs feed's
	// metadata — populated for Recent's callers only. /fleet/jobs/{id} (Get)
	// does not fill them: that route's shape (jobWire) is unchanged, so they
	// stay zero there rather than grow a wire field nothing reads.
	Task                              string
	Model                             string
	AcceptedAt, StartedAt, FinishedAt time.Time
}

JobView is a read-only copy of a job's externally visible state (the wire's `state` / `data` / `error` fields are shaped by the server layer).

type Jobs

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

Jobs is the concurrency-safe ack-then-poll job store AND its scheduler. Terminal results are retained for ttl (contract: ≥ a few minutes; we run 1h) and swept by a janitor goroutine. DrainAndStop is the shutdown path.

Every mutable field is guarded by mu — there is exactly one mutex here, and cond locks that same one, so no lock ordering exists to get wrong. Three goroutine kinds touch this struct: the janitor (sweep), the scheduler (schedule), and one execute per running job. The only lock-free read is maxConcurrent, which is written once in the constructor before any of them is started and never again.

func NewJobs

func NewJobs(ttl time.Duration, maxConcurrent int) *Jobs

NewJobs builds a store whose terminal entries live for ttl, with the janitor sweeping every 5 minutes (the spec's cadence). maxConcurrent bounds how many admitted jobs execute at once (<= 0 = unlimited); the rest wait in accepted.

func (*Jobs) Accept

func (j *Jobs) Accept(id string, run func(context.Context) (json.RawMessage, error)) (created bool)

Accept ADMITS id — it records the job as `accepted` and queues it for the scheduler — returning immediately (the ack). It does NOT start the run: that happens when an execution slot frees, which may be at once or may be a while (see schedule). Before 0.100.0 this function was the start, which is exactly why the node had no queue.

Idempotent: an id already present — in ANY state — returns false and never starts a second run (the contract's duplicate-POST rule). During drain it refuses all new work (false; the server maps that to 503 via Draining()). Accept never enforces a backlog limit; admission is the server's gate.

func (*Jobs) AcceptAgent added in v0.206.0

func (j *Jobs) AcceptAgent(id string, run func(context.Context) (json.RawMessage, error)) (created bool)

AcceptAgent is Accept for a job created by an AGENT dispatch.

func (*Jobs) Admit added in v0.206.0

func (j *Jobs) Admit(id string, spec AcceptSpec, run func(context.Context) (json.RawMessage, error)) (created bool)

Admit is Accept with the full per-job spec; Accept/AcceptAgent are its two common shapes. OnDropped is deliberately NOT invoked when Admit returns false. A refusal (drain, duplicate id) never took ownership of anything, and the caller is still holding its own cleanup at that point — handleDispatch calls it right there on the refusal path, and has since before this store had a queue. Firing the hook here as well would free the same temp files twice and split ownership across two layers for one resource; "admitted and then never ran" stays the hook's ONLY meaning.

func (*Jobs) Counts added in v0.206.0

func (j *Jobs) Counts() (queued, running int)

func (*Jobs) CountsCapped added in v0.206.0

func (j *Jobs) CountsCapped() (queued, running int)

CountsCapped is Counts restricted to jobs that COUNT AGAINST fleet_max_concurrent_jobs — the same set RunningCapped/runningCappedLocked and IdleSlot measure against the cap. A queue-wait ESTIMATE (register S-04) must be computed from this, not from Counts' all-jobs split: an uncapped job (a render, an stt, a pipeline route) never waits behind maxConcurrent, so mixing it into the numerator the same way saturationOf's fix and IdleSlot's fix both already avoid would inflate the estimate for backlog that was never contending for a capped worker slot. 4 idle agent slots behind 10 running uncapped renders must read as an idle agent lane, not a 90s wait.

func (*Jobs) DrainAndStop

func (j *Jobs) DrainAndStop(timeout time.Duration)

DrainAndStop stops accepting, waits up to timeout for in-flight runs, marks every non-terminal survivor terminal — the contract's shutdown obligation (once acked, a job is never re-dispatched, so pollers must still reach a terminal state) — then cancels their context and waits (bounded by killDeliveryGrace) for the released run goroutines to actually return, so the cancel-triggered kill of child process trees lands before the process exits. The mark happens BEFORE the cancel so a run released by the cancel can never race its late completion past the mark (finish never overwrites a terminal state). Total bound: timeout + killDeliveryGrace. Also stops the janitor and the scheduler. Safe to call once per store.

Survivors are marked by STATE, which is exactly the distinction the scheduler's atomic claim makes available: still `accepted` = the scheduler never took it (ErrNeverStarted); `running` = a real execution was cut off (ErrInterrupted). The pending FIFO is emptied up front so nothing new can start during the wait — drain lets running work finish, it does not work through the backlog.

func (*Jobs) Draining

func (j *Jobs) Draining() bool

Draining reports whether DrainAndStop has begun (the server's 503 gate).

func (*Jobs) FinishedAgentWalls added in v0.206.0

func (j *Jobs) FinishedAgentWalls(n int) []time.Duration

FinishedAgentWalls is the wall (finish − start) of the last n AGENT jobs to finish, newest first — the completion signal `recent_agent_wall_sec` is the median of (register S-36). It walks the same map /fleet/jobs walks, under the same read lock, and reads only fields that map already carries: no clock, no probe, and nothing a node without samples has to invent.

func (*Jobs) Get

func (j *Jobs) Get(id string) (*JobView, bool)

Get returns a copy of the job's visible state; false = unknown/evicted (404).

func (*Jobs) IdleSlot added in v0.206.0

func (j *Jobs) IdleSlot() bool

IdleSlot reports whether a job admitted RIGHT NOW would start at once: the CAPPED backlog is empty and a capped execution slot is free (or execution is unlimited). It is the server's shed predicate for BandSheddable dispatches — measurement traffic takes only capacity nobody is queued for — and health publishes it as saturation.idle_slot so a delegator can read the same answer before it dispatches.

Only a CAPPED queued job counts (register S-20), mirroring claimLocked's own "jb.capped && full" skip: an uncapped job (AcceptSpec.Uncapped — a render, an stt, a pipeline route whose work never touches the shared llama-swap endpoint the cap protects) never waits behind maxConcurrent, so one sitting in the backlog does not mean a NEW sheddable job would queue behind it either.

func (*Jobs) MaxConcurrent added in v0.206.0

func (j *Jobs) MaxConcurrent() int

MaxConcurrent reports the store's execution limit; 0 = unlimited. Published in health so a delegator can see a node's CAPACITY, not just its depth. Lock-free by construction: maxConcurrent is immutable once NewJobs returns.

func (*Jobs) OnFinish added in v0.206.0

func (j *Jobs) OnFinish(fn func())

OnFinish registers fn to run after every job reaches a terminal state. It is called outside the store's lock and must return quickly; anything slow (the steward's directory scan) is the callee's job to move off the goroutine.

func (*Jobs) OnSweep added in v0.206.0

func (j *Jobs) OnSweep(fn func())

OnSweep registers fn to run after every janitor sweep (the 5-minute tick, and any direct sweep). It is called outside the store's lock and must return quickly.

func (*Jobs) PollLease added in v0.206.0

func (j *Jobs) PollLease() time.Duration

PollLease reports the poll lease in force; 0 = the abandoned-job rules are off. It exists so the serve verb's wiring of fleet_poll_lease_sec can be read back.

func (*Jobs) QueueDepth

func (j *Jobs) QueueDepth() int

QueueDepth counts accepted+running jobs (the health field). Terminal entries are results awaiting pollers, not load. Its meaning is UNCHANGED across the 0.100.0 queue split — it is now expressed as queued+running so the wire's queue_depth and the jobs_queued/jobs_running pair beside it are arithmetic, not two independent walks that could disagree.

func (*Jobs) Recent added in v0.206.0

func (j *Jobs) Recent(n int) []JobView

Recent returns up to n jobs (n <= 0 = all), newest by acceptedAt first, WITHOUT payloads: this is the cluster jobs feed, and a listing must never leak an agent job's result past the per-job bearer gate on /fleet/jobs/{id} — so Data is never populated here, only Get's copy does that. The input comes from ranging j.m, so tie order among equal AcceptedAt values (two Admits landing in the same clock tick) is not deterministic — SliceStable only stops the sort from RESHUFFLING that already-arbitrary order; it does not make ties arrival-ordered.

func (*Jobs) RunningCapped added in v0.206.0

func (j *Jobs) RunningCapped() int

Counts splits the in-flight population health used to report as one number: queued = admitted but not yet executing (state accepted), running = executing (state running). Terminal entries are results awaiting pollers, not load, and count as neither. QueueDepth is defined as their sum, so the published queue_depth can never drift from the split published beside it. RunningCapped is the count of executing jobs that COUNT AGAINST fleet_max_concurrent_jobs — the same set IdleSlot measures against the cap (runningCappedLocked). Saturation's score must be computed from this, not from Counts' all-jobs running: the two disagree whenever an uncapped job (a render, an stt, a pipeline route) is executing, and a node could then publish score 1.0 and idle_slot true in one payload (2026-09-07 audit).

func (*Jobs) SetPollLease added in v0.206.0

func (j *Jobs) SetPollLease(d time.Duration)

SetPollLease sets the poll lease (see DefaultPollLease); <= 0 turns the abandoned-job rules off.

func (*Jobs) SetProgress added in v0.206.0

func (j *Jobs) SetProgress(id string, p core.LiveProgress)

SetWall records the wall (seconds) the job's run reported it is executing under (register D-116). Unknown ids and non-positive walls are ignored, and a TERMINAL job is never rewritten: the result carries its own wall from there on, and a late report must not edit a finished record. The last report before a job turns terminal wins — a wall is stamped once today. SetProgress records the run's latest liveness report on a RUNNING job (0.131.0). A terminal job ignores it, as SetWall does: a late report must not resurrect a record the delegator has already read as done.

func (*Jobs) SetWall added in v0.206.0

func (j *Jobs) SetWall(id string, sec int)

func (*Jobs) TakenBack added in v0.206.0

func (j *Jobs) TakenBack() (withdrawn, reaped int)

TakenBack reports how many jobs this process has taken out of the backlog without running them: withdrawn at a delegator's request, and reaped for want of a poller. Counts since the process started, published on /fleet/health so the reaper — the one unattended state change ADR 0064 makes — can be counted by anyone polling the node.

func (*Jobs) Touch added in v0.206.0

func (j *Jobs) Touch(id string)

Touch records that a poller looked at the job just now (the poll route calls it after the bearer gate; the feed listing never does, so an observer cannot keep a ghost alive). A terminal job is left alone: see job.polledAt.

func (*Jobs) WaitTerminal added in v0.206.0

func (j *Jobs) WaitTerminal(ctx context.Context, id string, d time.Duration) (*JobView, bool)

WaitTerminal is Get with a completion EVENT: it returns at once when the job is already terminal (or unknown), and otherwise blocks until the job reaches a terminal state, `d` elapses, or ctx is done — whichever comes first. The returned view is always the job's state at that moment, terminal or not, so a caller that timed out still answers its own caller with the truth.

It is the server's long-poll primitive (register S-19). The store already had everything needed: `finish` writes the terminal state and broadcasts, and the drain's mark does the same — nothing new observes the job, and no goroutine is spawned per job. Before this, the only way to learn a job had finished was to ask again in three seconds, and 236 measured contract rows spent exactly 300 s doing nothing but that.

A cond wait cannot be cancelled, so ONE goroutine per waiter broadcasts when the wait's own context ends; every waiter then re-checks its own predicate and this one returns. That is the standard shape, and it is bounded by d.

func (*Jobs) Withdraw added in v0.206.0

func (j *Jobs) Withdraw(id string) WithdrawResult

Withdraw takes an `accepted` job back out of the backlog at its delegator's request. It is the one route by which a delegator that gives a job up can make sure the node does not run it later for nobody (ADR 0064).

It succeeds ONLY for a job that has never started, and it decides that under the same mutex claimLocked flips accepted→running under, so exactly one of the two wins a race and no job can both run and be reported withdrawn. A RUNNING job is never touched (the operator's Option A, ADR 0028: running work stays recoverable), and neither is a finished one.

The job is marked terminal (ErrWithdrawn), not deleted: terminal states are write-once and every poller always reaches one, a duplicate dispatch of the id meets the known-job path (409, never a second run), and the feed keeps the row for the ttl so an operator can see what became of it. Its parked resources are released through OnDropped, outside the lock, exactly as drain does.

type KVSlotRequest added in v0.206.0

type KVSlotRequest struct {
	Seat string `json:"seat"`
	Key  string `json:"key"`
	// SeatPinSHA256 is the caller's expectation of the seat's config pin
	// (agent.ProbeSeatPin over /props). When set, a live pin that differs is a
	// 409: the file would be restored into a different seat shape.
	SeatPinSHA256 string `json:"seat_pin_sha256,omitempty"`
}

KVSlotRequest is the body of both endpoints.

type KVSlotResponse added in v0.206.0

type KVSlotResponse = kvslot.Response

KVSlotResponse is the JSON answer of both endpoints (the shared core's Response).

type LeaseEntry added in v0.206.0

type LeaseEntry struct {
	Epoch uint64 `json:"epoch"`
	Class string `json:"class"`
	// Devices are the cards the lease sits on, as lease ids (lower-cased GPU UUIDs): the
	// record's declared cards, else the cards the evidence rule inferred for a legacy lease.
	// ABSENT means the whole node, and a reader must take absence as every card.
	Devices []string `json:"devices,omitempty"`
	// Scope says where Devices came from: declared, inferred or whole-node.
	Scope string `json:"scope"`
	// Until is the lease's declared term end (RFC3339); absent when it declares none.
	Until        string `json:"until,omitempty"`
	RemainingSec int    `json:"remaining_sec,omitempty"`
	Busy         bool   `json:"busy,omitempty"`
	Overdue      bool   `json:"overdue,omitempty"`
	Exclusive    bool   `json:"exclusive,omitempty"`
	Draining     bool   `json:"draining,omitempty"`
	// LeaseStanding is embedded so orphaned and stalled sit flat on the entry.
	LeaseStanding
	// Verdict is one word for what the lease is doing, in the precedence `gpu status` uses:
	// tree-orphan, held-stalled, held-orphaned, held-overdue, else held. "held" is the absence of news and
	// does not claim the holder is working.
	Verdict string `json:"verdict"`
}

LeaseEntry is the wire shape of ONE live lease in /fleet/health leases[].

type LeaseHealth added in v0.206.0

type LeaseHealth struct {
	Held   bool   `json:"held"`
	Class  string `json:"class"`
	PID    int    `json:"pid"`
	Reason string `json:"reason,omitempty"`
	Until  string `json:"until"` // RFC3339
	// LeaseStanding is embedded so its keys sit flat in the lease block (orphaned, stalled).
	LeaseStanding
	// RemainingSec and Busy are additive (0.113.27). RemainingSec is how much
	// longer the card is spoken for; Busy is THIS NODE'S OWN verdict that the
	// reservation is long enough to make it a non-target (fleet_busy_lease_sec).
	//
	// The verdict travels rather than the threshold so a delegator never has to
	// know a remote box's config, and a node one release behind simply omits
	// both — decoding to false, i.e. exactly the pre-0.113.27 behaviour.
	RemainingSec int  `json:"remaining_sec,omitempty"`
	Busy         bool `json:"busy,omitempty"`
	// Overdue is additive (GPU routing P1): the lease is HELD and its declared
	// window has already ended, so the holder is still using the cards past what
	// it asked for. It travels beside Busy rather than being folded into it,
	// because the two answer different delegator questions: Busy says "do not
	// count on this card" (and hard-excludes a non-text lease from placement),
	// Overdue says "the declared end is no evidence about when it frees", which a
	// delegator uses to rank the node last without excluding it. A node one
	// release behind omits it, which decodes to false.
	Overdue bool `json:"overdue,omitempty"`
	// Expired is additive (plan P9): the holder's own tick labelled the lease because its
	// term ended and was not renewed (its owner gone, or nothing running under it). It is
	// still HELD, and Busy and Overdue still say so; the key is the fact that nobody vouches
	// for it. A node one release behind omits it, which decodes to false.
	Expired bool `json:"expired,omitempty"`
}

LeaseHealth is the wire shape of a HELD lease in /fleet/health.

type LeaseStanding added in v0.206.0

type LeaseStanding struct {
	// Orphaned: an attended lease whose owner has been gone past the grace.
	Orphaned bool `json:"orphaned,omitempty"`
	// Stalled: the lease's progress file did not move inside its stall window.
	Stalled bool `json:"stalled,omitempty"`
	// TreeOrphan: the lease's wrapper is gone but the job it started is still running, so the
	// claim is kept (plan P10). The card is in use, and the lease layer never frees it by a clock. On this wire it is
	// busy and refuses work for its cards exactly as any held lease does: within its declared window it closes them, and
	// past the window it is ranked last (overdue) and is not a refusal, because dispatch queues behind it instead of
	// turning work away (the 0.113.27 rule for every overdue lease, kept: a tree-orphan is no exception to it).
	TreeOrphan bool `json:"tree_orphan,omitempty"`
}

LeaseStanding is what a held lease is DOING, published beside the fact that it is held (plan P8). Each key is absent unless true, so a healthy lease puts nothing new on the wire and a node one release behind simply omits them: a delegator decodes them as false. They describe the lease, they never refuse work on their own: ranking a node whose lease is orphaned or stalled behind one whose lease is healthy is the delegator's call.

There is deliberately NO Overdue here. "The declared window ended while the holder still renews" is the lease block's own expiry-based `overdue` key (the routing change, P1), read from the same record: a second field under the same JSON key would be shadowed by the shallower one when the two merge, leaving this one dead, and two sources for one wire key is a defect whichever wins. The overdue standing is still computed and shown by `gpu status` and offload_status; only the wire key has a single owner.

type MediaJobPayload added in v0.206.0

type MediaJobPayload struct {
	JobID    string `json:"job_id"`
	TaskType string `json:"task_type"`
	// Payload is the inner task's payload exactly as POST /fleet/dispatch takes it.
	Payload json.RawMessage `json:"payload"`
	// Bundle is base64 (standard encoding) of a gzip-compressed tar of the input files; BundleSHA256 is
	// the hex sha256 of the decoded bytes. Inputs maps a payload field to a bare file name in the bundle.
	Bundle       string            `json:"bundle,omitempty"`
	BundleSHA256 string            `json:"bundle_sha256,omitempty"`
	Inputs       map[string]string `json:"inputs,omitempty"`
}

MediaJobPayload is the POST /fleet/media-job body.

type MediaRecipeHealth added in v0.206.0

type MediaRecipeHealth = mediacap.LaneRow

MediaRecipeHealth is one row of /fleet/health media_recipes (mediacap.LaneRow).

func MediaRecipes added in v0.206.0

func MediaRecipes(cfg config.Config) []MediaRecipeHealth

MediaRecipes lists the rows of this node's video, animation and audio bindings (mediacap.LaneRows): the family each binding names, its weight files and their sizes here, -1 for a file the node does not hold. No file is read: a row carries no content fingerprint and no digest in this release, so it is a statement of what the binding names and what is on disk, never an identity, and building it costs a stat per file.

type MediaRouteHealth added in v0.206.0

type MediaRouteHealth struct {
	Route  string `json:"route"`
	Engine string `json:"engine"`
	State  string `json:"state"`
}

MediaRouteHealth is one row of /fleet/health's media_routes: a task route this node derives and its verdict. Detail is deliberately not published (it holds local paths).

func MediaRoutesHealth added in v0.206.0

func MediaRoutesHealth(cfg config.Config) []MediaRouteHealth

MediaRoutesHealth lists the node's task routes (shared prerequisites such as the node runtime and the ComfyUI install are left out) from the same cached derivation the admission predicate reads.

type MemProbe added in v0.206.0

type MemProbe func() (totalGiB, usedGiB float64, err error)

MemProbe returns the current GPU memory capacity/usage in GiB. It is the unit both the startup gate and the health sampler consume; every provider (nvidia-smi, windows-generic) reduces to one of these.

func AmdgpuSysfsProbe added in v0.206.0

func AmdgpuSysfsProbe(drmRoot string, uma bool) MemProbe

AmdgpuSysfsProbe returns a MemProbe over the FIRST amdgpu card under drmRoot (/sys/class/drm in production; a temp tree in tests). uma selects the memory model: true (amd-gcn, amd-rdna3 APUs) adds the GTT pool to both capacity and usage; false (amd-rdna3-dgpu) reports VRAM alone. Every read is one small sysfs file; the probe is safe to call from the 2 s health sampler.

func GenericWindowsProbe added in v0.206.0

func GenericWindowsProbe(uma bool) MemProbe

GenericWindowsProbe (the windows-generic health source, J3) has no off-Windows implementation: the stub returns a probe that always errors, so ResolveProvider's fallback fails honestly and the gate reports "no working GPU memory source" instead of pretending.

func MeminfoUMAProbe added in v0.206.0

func MeminfoUMAProbe(root string, reserveGiB float64) MemProbe

MeminfoUMAProbe returns a MemProbe over <root>/proc/meminfo (root is "/" in production, a temp tree in tests) with reserveGiB held back for the host. A zero reserve advertises all of RAM. Every read is one small procfs file, so the probe is safe to call from the 2 s health sampler.

func SmiProbe added in v0.206.0

func SmiProbe(run func() (string, error)) MemProbe

SmiProbe adapts the nvidia-smi CSV runner (the historical source) to a MemProbe via ParseSmiMemory.

type Options

type Options struct {
	NodeID     string
	Snapshot   func() (Snapshot, bool)
	Footprints func() []FootprintEntry
	// Version is advertised as harness_version. Empty = omitted.
	Version string
	// Reclaim reports how much VRAM this node could free right now. nil (or an
	// unknown verdict) omits the reclaim fields entirely rather than guessing.
	Reclaim   func(freeGiB, totalGiB float64) ReclaimVerdict
	GpuVendor string
	GpuArch   string
	// Backends is the serving-backend list from the installer's manifest
	// (InstalledInfo.Backends: primary first, then the alternates this install
	// rendered — a dual-route node advertises ["vulkan","cpu"]). nil omits the
	// field, so every node without a manifest backend is byte-identical.
	Backends []string
	// Accelerators is the additive-device list from the installer's manifest
	// (installed.json `accelerators`, ADR 0024) — advertised in health so a
	// delegator can route NPU-owned work to this node, minus the devices that
	// stay on the box that carries them (config.FleetVisibleAccelerators,
	// register E-08: the standalone Hailo-8L is never advertised, whatever this
	// list says). Empty = omitted.
	Accelerators []string
	// LoopbackListener reports whether the serve listener is bound to a
	// loopback address. The verb computes it from the RESOLVED listen address
	// (netguard.LoopbackAddr) — NOT from --listen-trusted-network, which is
	// permission to bind beyond loopback, not where the bind actually landed.
	// The agent lane keys on it: with no Cfg.FleetAuthToken configured, agent
	// dispatches on a non-loopback listener are refused 403 at ack time. The
	// zero value (false) fails CLOSED for the agent lane — a constructor that
	// forgets to set it gets the refusal, never an open agent surface; the
	// media lane never consults it.
	LoopbackListener bool
	Cfg              config.Config
	// Pair is this node's PAIR emitter (pairworkloads.New(FromConfig(cfg))). The node uses it for ONE
	// thing: the card of a job whose asker signalled core.PairCardHeader = "node" because it will not
	// card the job itself. nil, or an emitter that is not Enabled, cards nothing.
	Pair *pairworkloads.Emitter
	// KVSlotDir is the directory the seats' --slot-save-path points at (ADR 0056
	// Layer 2); empty = the kvslot lane answers 501. KVSlotCapGiB bounds it (0 = 8).
	KVSlotDir    string
	KVSlotCapGiB int
	// Host reports the last host CPU/RAM sample (hostsample.Sampler.Load).
	// nil omits the host_* fields; the handler never samples itself.
	Host func() (hostsample.Sample, bool)
	// Lease reads this node's machine-wide GPU lease (gpulease.InspectDir over
	// the config's lease dir). nil = not advertised, never refused.
	Lease func() gpulease.Info
	// LeaseStanding derives what the held lease is doing (orphaned, overdue, stalled) so
	// /fleet/health can publish it beside "held". nil = the lease block carries held,
	// class and window only, as before.
	LeaseStanding func(gpulease.Info) gpulease.Standing
	// Store returns the store steward's last status; nil = no steward.
	Store func() storesteward.Status
	// ServingConfig reports the rendered serving config's provenance: its spec
	// hash and its state (MATCH/STALE/UNSTAMPED/HAND-EDITED). nil, or an empty
	// state, omits both health fields.
	//
	// It is a func and not a path because the re-derive needs the tier table and
	// the serving templates, which are embedded in the COMMAND (install_render.go)
	// -- this package serves health, it does not own the seeds.
	ServingConfig func() (specSHA256, state string)
	// PowerProfile reports whether the GPU power profile this node applies at boot took (the state file the boot-apply
	// tool writes, found by LOCAL_OFFLOAD_POWER_PROFILE_STATE). Like ServingConfig it is a func: the reader and its
	// judgement live in the command, which also owns the doctor row that prints the same reading. nil omits the
	// power_profile health field; a func that returns nil does too. It must answer from memory or one small local
	// file read, because health never blocks.
	PowerProfile func() *PowerProfileHealth
	// GpuFaults is this node's driver fault summary (gpuactivity.FaultSummary): each card's incidents over 30 days and
	// NVSentinel's repeat rule where it is met. A func for the same reason as PowerProfile: the command owns the
	// reader, its background refresh and the retention file. nil, or a func that returns nil (no reading yet, or no
	// NVIDIA card), omits gpu_faults. It answers from memory, because health never blocks.
	GpuFaults func() *gpuactivity.FaultSummary
}

Options is the server's static identity + read-only data feeds. Snapshot and Footprints are functions (not values) so health always reads live state without the handler owning any sampling machinery.

type PowerProfileHealth added in v0.206.0

type PowerProfileHealth struct {
	State     string `json:"state"`
	Reason    string `json:"reason,omitempty"`
	LimitW    []int  `json:"limit_w,omitempty"`
	ClockLock bool   `json:"clock_lock,omitempty"`
	AppliedAt string `json:"applied_at,omitempty"`
}

PowerProfileHealth is /fleet/health's power_profile block: whether the GPU power profile this node applies at boot (a power limit, a clock lock) took, read from the state record the boot-apply tool writes. It is the doctor's `power:` row in a form a delegator can read; it reports the record, not the card, so a limit changed after the apply still reads ok.

State is "ok", "skipped" or "unknown" (the PowerProfile constants). Reason is a short token: the reason a node is not ok ("no_state", "unreadable", "bad_state", "bad_schema", "not_due", "boot_unknown", "stale_boot", "partial", "dry_run", "unrecognised"), or the applier's own outcome word for a run that ended without applying ("failed", "refused", "cookie_blocked", "plan_empty": lower-case letters, digits and underscores, 32 at most). It is never free text and never a path. LimitW is the driver's power limit of each card as the record read it, in the record's card order, and ClockLock says a step that locked the clocks returned success; both are published only when State is ok, so a skipped run never advertises a limit it did not set. AppliedAt is the record's own time, RFC 3339 in UTC, of the most recent run (the one the state describes), omitted when the record could not be read.

type ProcessDedicated added in v0.206.0

type ProcessDedicated struct {
	PID int
	MiB int
}

ProcessDedicated is one \GPU Process Memory(pid_*)\Dedicated Usage instance, raw: no tree filter, no summing, no name resolution — the return shape of AllProcessDedicatedMiB (vram_windows.go's real implementation, vram_other.go's always-erroring stub). Declared here, in the portable file, so a non-Windows build can still name the type its own stub returns.

func AllProcessDedicatedMiB added in v0.206.0

func AllProcessDedicatedMiB() ([]ProcessDedicated, error)

AllProcessDedicatedMiB is the non-Windows stub for the foreign-GPU-holder read (D-1xx-4, 2026-09-23): the "\GPU Process Memory" counter set is a WDDM facility. Off-Windows the caller (internal/gpuactivity) falls back to nvidia-smi's compute-apps query, which DOES report real per-process names and memory on Linux — the gap this exists to close is Windows-only (on WDDM, nvidia-smi's own per-process memory is `[N/A]`).

type ReclaimInputs added in v0.206.0

type ReclaimInputs struct {
	UsedGiB float64
	// OursLoaded is true when llama-swap has any model resident or this node holds
	// the GPU lease — i.e. when there is something we could actually free.
	OursLoaded bool
	// BaselineGiB is the last used-VRAM observed with nothing of ours loaded.
	BaselineGiB  float64
	HaveBaseline bool
}

ReclaimInputs is one evaluation's worth of facts.

type ReclaimVerdict added in v0.206.0

type ReclaimVerdict struct {
	ReclaimableGiB float64
	Known          bool
	Source         string
}

ReclaimVerdict is the answer plus how it was reached, so a dispatcher (or an operator reading /fleet/health) can tell a measured zero from an unknown.

func Reclaimable added in v0.206.0

func Reclaimable(in ReclaimInputs) ReclaimVerdict

Reclaimable applies the rule. Pure.

type ResolvedProvider added in v0.206.0

type ResolvedProvider struct {
	Probe    MemProbe
	Vendor   string
	Arch     string
	Source   string // "nvidia-smi" | "windows-generic" | "linux-amdgpu" | "linux-meminfo"
	TotalGiB float64
	UsedGiB  float64
}

ResolvedProvider is what fleet-serve runs on after resolution: the probe that feeds the gate + sampler, the advertisement identity, the source name for the operator log line, and the selection probe's own reading (TotalGiB/ UsedGiB — so the startup banner never re-executes or discards a probe).

func ResolveProvider added in v0.206.0

func ResolveProvider(smi MemProbe, generic MemProbe, smiIdentity func() (vendor, arch string), info InstalledInfo) (ResolvedProvider, error)

ResolveProvider picks the working GPU memory source. Order: nvidia-smi (the proven path — keeps every existing NVIDIA node byte-identical in behavior), else the injected generic provider (Windows WDDM; nil off-Windows, on a cpu-profile box, or in tests that exclude it). smiIdentity is called ONLY when nvidia-smi wins (it typically shells nvidia-smi for the product name — pointless on a box where smi just failed). Both probes failing is the new gate error: "no working GPU memory source". A note on transience: selection happens once at startup — a transiently failing nvidia-smi binds the generic provider for the process lifetime (restart re-resolves; documented in ADR 0014). Pure of I/O — probes, identity, and manifest info are injected, so selection is unit-testable.

func ResolveProviderNamed added in v0.206.0

func ResolveProviderNamed(smi MemProbe, generic GenericProvider, smiIdentity func() (vendor, arch string), info InstalledInfo) (ResolvedProvider, error)

ResolveProviderNamed is ResolveProvider with the generic source named by the caller. ResolveProvider keeps its signature (and its "windows-generic" label) so every existing caller and test stays byte-identical.

type Runner

type Runner interface {
	Run(ctx context.Context, req core.Request) core.Result
}

Runner runs one translated request to completion. The real pipeline satisfies it; tests inject fakes.

type STTUploadPayload added in v0.206.0

type STTUploadPayload struct {
	JobID    string `json:"job_id"`
	AudioB64 sttB64 `json:"audio_b64"`
	AudioExt string `json:"audio_ext,omitempty"`
	Language string `json:"language,omitempty"`
	HQ       bool   `json:"hq,omitempty"`
}

STTUploadPayload is the POST /fleet/stt body. job_id is the caller-minted id exactly as on /fleet/dispatch (re-acks and polls key on it); audio_b64 is the audio file, standard base64; audio_ext its extension without the dot (ffmpeg sniffs the content, the extension only names the file); language and hq mirror offload_transcribe's parameters.

type Sampler

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

Sampler publishes the latest good Snapshot via an atomic.Value so the health handler never blocks on (or spawns) nvidia-smi.

func StartDeviceProbeSampler added in v0.206.0

func StartDeviceProbeSampler(ctx context.Context, interval time.Duration, probe DeviceProbe, primaryGPUUUID string) *Sampler

StartDeviceProbeSampler is StartProbeSampler's devices-aware sibling: same sync-then-tick contract, but over a DeviceProbe, publishing the full per-device breakdown (Snapshot.Devices) alongside a SelectHeadlineDevice- derived TotalGiB/FreeGiB — primaryGPUUUID (config.Config.PrimaryGPUUUID, "" = disabled) pins the headline to one card by UUID, overriding the largest-total fallback; see SelectHeadlineDevice's doc comment for the full rule and why UUID (not index, not total VRAM) is the only stable pin. Used for the nvidia-smi multi-device source; the windows-generic source has no per-device signal (vram_windows.go) and stays on StartProbeSampler, so its Snapshot.Devices is always nil — exactly today's single-number behavior, and a primaryGPUUUID has no effect there (there is nothing to match it against).

func StartGlobalSampler

func StartGlobalSampler(ctx context.Context, interval time.Duration, run func() (string, error)) *Sampler

StartGlobalSampler samples run() (an injected nvidia-smi invocation) once synchronously, then keeps refreshing — kept as the nvidia-smi convenience wrapper over StartProbeSampler (J3 made the memory SOURCE a provider; this signature predates that and existing callers/tests keep working).

func StartProbeSampler added in v0.206.0

func StartProbeSampler(ctx context.Context, interval time.Duration, probe MemProbe) *Sampler

StartProbeSampler samples probe once synchronously — so a successful probe is Load-able the moment this returns — then keeps refreshing every interval until ctx is done. Probe failures leave the previous snapshot in place: the sampler degrades to stale data, never to zeros. Staleness is bounded downstream — the health handler refuses (503) any snapshot older than maxSnapshotAge, so a persistently failing source (driver reset) cannot serve hours-stale 200s.

func (*Sampler) Load

func (s *Sampler) Load() (Snapshot, bool)

Load returns the latest snapshot. ok is false until a sample has succeeded — callers must treat that as "probe not working", never as zero VRAM.

type SaturationHealth added in v0.206.0

type SaturationHealth struct {
	Score    float64 `json:"score"`
	High     bool    `json:"high"`
	IdleSlot bool    `json:"idle_slot"`
}

SaturationHealth is /fleet/health's `saturation` block (0.113.18): ONE number and two booleans derived from the counters published beside it, so every reader — the delegator's placement, offload_status, a human with curl — agrees on what "this node is saturated" means without each re-deriving it.

score      max(jobs_running / max_concurrent_jobs, queue_depth / max_queue_depth)
           over the limits the node publishes (an unpublished limit
           contributes nothing); 0 on an idle node, 1.0 at a ceiling.
high       a NEW band-0 dispatch would be refused right now: the backlog is at
           max_queue_depth, the node is draining, or its card is under a
           text lease. The delegator's ranking demotes a high node exactly
           as it demotes one whose queue_depth has reached its ceiling.
idle_slot  Jobs.IdleSlot: a sheddable (priority -1) dispatch would be admitted.

Seat-level counters (vLLM running/waiting, KV usage) are deliberately NOT an input yet: the node's health handler never probes the seat (a probe of an unloaded seat through llama-swap LOADS it), and on this fleet the job counters already describe the load the harness itself puts on a seat. The block is the seam a cached seat sampler would feed later, without a wire change.

type SeatBudgetHealth added in v0.206.0

type SeatBudgetHealth struct {
	StepTokens  int    `json:"step_tokens"`
	FinalTokens int    `json:"final_tokens"`
	Thinking    string `json:"thinking"`
}

SeatBudgetHealth is the per-step / final completion budget and thinking policy the node's agent loop runs at (config agent_max_tokens, the final answer at agent.FinalBudgetFor, config agent_thinking or "auto").

type SeatRateHealth added in v0.206.0

type SeatRateHealth struct {
	TokS        float64 `json:"tok_s"`
	ColdLoadSec float64 `json:"cold_load_sec"`
	Samples     int     `json:"samples"`
	MinTurnSec  int     `json:"min_turn_sec"`
	// PrefillTokS is the seat's remembered prefill rate (an average over runs) and PrefillSlowTokS the
	// slowest of its recent solo samples: the rate the stall allowance of a prefill is sized from
	// (register F10). Both are omitted until a solo prefill has been measured, never published as 0.
	PrefillTokS     float64 `json:"prefill_tok_s,omitempty"`
	PrefillSlowTokS float64 `json:"prefill_slow_tok_s,omitempty"`
}

SeatRateHealth is the seat-rates store entry for the agent seat, plus the retry floor it implies at this node's final budget (cold load + one final turn; seatrate.MinTurnFor without a re-pack term — the delegator adds that from the contract).

type Server

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

Server is the fleet-node HTTP server: three handlers over a Runner + Jobs store. Task/family advertisements are derived once at construction (config is immutable while serving).

func New

func New(runner Runner, jobs *Jobs, opts Options) *Server

New builds a Server. The lane verdicts and the image-family list are computed here — the config cannot change under a running server. The supported-task and family lists are not: they are derived per health request and per claim, because the media tasks follow a cached disk read (ADR 0077).

func (*Server) EnableQueueHost added in v0.206.0

func (s *Server) EnableQueueHost(dbPath string) (*fleetqueue.Queue, error)

EnableQueueHost opens the durable queue store and arms the holder surface — called by the serve verb ONLY when cfg.FleetQueueHost is set. Idempotent enough for one process; returns the store so the caller owns Close.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the routed mux for the three contract endpoints.

func (*Server) RefreshAgentResidency added in v0.206.0

func (s *Server) RefreshAgentResidency()

RefreshAgentResidency ensures ONE residency probe has published an answer before it returns, warming the cache agent_seat_resident is served from.

It PARTICIPATES in the single-flight rather than bypassing it: it claims the latch when nothing holds it, and otherwise WAITS for the probe already running. Calling the refresher directly (the previous shape) took no latch while the refresher cleared it unconditionally, which permitted a second concurrent GET against llama-swap and — since the last writer wins the cache — let a staler answer overwrite a fresher one.

Exported for CROSS-PACKAGE callers that need the answer deterministically — an end-to-end delegation test cannot otherwise avoid racing the first health GET's background refresh, and would gate-fail on a cold cache that is about to say yes. This package's OWN residency tests must never call it: production's only trigger is agentResident()'s background single-flight, and a test that runs the probe itself leaves that line uncovered (which is exactly how deleting it once left the whole suite green while the feature was inert in production). The one in-package exception is the test that pins THIS function's latch discipline, which cannot be written any other way.

func (*Server) Serve

func (s *Server) Serve(l net.Listener) error

Serve serves on l until it fails/closes, with the contract timeout table applied. The listener is the verb's business (netguard.Validate happens there, before the socket ever exists).

func (*Server) StartClaimLoop added in v0.206.0

func (s *Server) StartClaimLoop(ctx context.Context, cfg config.Config)

StartClaimLoop runs until ctx cancels. It never claims while this node's backlog is at its cap (the push path's own back-pressure rule), and it nacks jobs it cannot build rather than letting the lease expire — a loud bounded requeue beats a silent slow one.

type Snapshot

type Snapshot struct {
	TotalGiB float64
	FreeGiB  float64
	// Devices is the full per-device breakdown (nvidia-smi source only, in
	// nvidia-smi's own enumeration order — see ParseSmiMemoryDevices/
	// HeadlineDevice). ALWAYS populated when the source is nvidia-smi,
	// including a single-GPU box (one entry — no single-GPU special case).
	// Nil only when the source cannot enumerate devices at all — today, the
	// windows-generic MemProbe path (StartProbeSampler, not
	// StartDeviceProbeSampler): TotalGiB/FreeGiB alone describe that box
	// exactly as they did before this field existed, and a nil Devices is
	// never itself an error condition. Additive only — no pre-fix consumer
	// (the fleet-dispatcher decodes health with a plain json.Decoder, no
	// DisallowUnknownFields anywhere in its internal/) breaks on the new
	// field appearing.
	Devices []GPUDevice
	// DisplayUUIDs is the set of cards driving a display (gpuprobe.DisplayCardUUIDs
	// over this same sample's display_active), so the placement figure can skip
	// them. Derived from the devices this Snapshot already carries — no second
	// nvidia-smi, nothing to go stale, nothing to carry forward. nil = exclude nothing.
	DisplayUUIDs map[string]bool
	At           time.Time
}

Snapshot is the cached global VRAM state /fleet/health reads. GiB = 2^30, per the contract.

type TextPayload added in v0.206.0

type TextPayload struct {
	JobID  string         `json:"job_id"`
	Task   string         `json:"task"`
	Input  string         `json:"input"`
	Params map[string]any `json:"params,omitempty"`
}

TextPayload is the wire body of POST /fleet/text. job_id is the caller-minted id exactly as on /fleet/dispatch; task is classify or extract; params carries what the task takes (classify: labels, at least two; extract: schema), nothing else.

type VisionPayload added in v0.206.0

type VisionPayload struct {
	JobID    string `json:"job_id"`
	Task     string `json:"task"`
	Image    string `json:"image"`
	Question string `json:"question,omitempty"`
	Brief    string `json:"brief,omitempty"`
}

VisionPayload is the wire body of POST /fleet/vision. job_id is the caller-minted id exactly as on /fleet/dispatch (re-acks and polls key on it); task is the pipeline task name; image is a data:image/...;base64 URI.

type WithdrawResult added in v0.206.0

type WithdrawResult struct {
	// Found is false for an id the store does not hold (never admitted, or
	// already evicted).
	Found bool
	// Withdrawn: the job is out of the backlog and never ran — taken back by this
	// call, by an earlier one (Withdraw is idempotent, so a retry after a lost answer
	// is unambiguous), or by the node itself (reaped, or never-started at shutdown:
	// see neverRanErr).
	Withdrawn bool
	// State is the job's state when it could NOT be withdrawn: running (a slot
	// took it), or already done/error. Zero when Withdrawn or not Found.
	State JobState
}

WithdrawResult is Withdraw's answer.

Jump to

Keyboard shortcuts

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