Documentation
¶
Overview ¶
Multi-runtime/multi-GPU coverage: this file's node/model validation, eviction, and TTFT measurement are all runtime-agnostic by construction, not by explicit per-runtime branching - node/model discovery goes through the existing Marbor Agent models.list/loadedModels endpoints, eviction reuses the same UnloadModel/unloadModelViaAgent path handleUnloadModel already uses for every runtime, and bench.MeasureChatTTFT talks to the OpenAI-compatible /v1/chat/completions surface every runtime (Ollama, vLLM, TGI, llama.cpp, MLX) exposes through the marbor proxy. None of it is GPU-vendor-specific either - VRAM eviction and TTFT timing don't touch vendor-specific telemetry. Covered: all 5 runtimes x all 4 GPU vendors. Deferred: nothing - there is no runtime/vendor-specific branch to add here.
Index ¶
- func MarkRestoreNotCarriedOut(dbPath string)
- func NodeSignalIDs() []string
- func WriteRestoreOutcome(dbPath string, restoreErr error, note string) (ref string, err error)
- type BudgetEntry
- type CatalogModel
- type CloudBudgetStatusResp
- type ContextFeasibility
- type HFModelInfo
- type HFRepoResponse
- type HourlyBucket
- type ModelStat
- type ModelVariant
- type ModelVariantFit
- type RequestLog
- type Server
- func (s *Server) AcknowledgeRestoreResult(ref string) error
- func (s *Server) AdminToken() string
- func (s *Server) CloseRestores() string
- func (s *Server) CloudBudgetExceeded(keyName string) (bool, string)
- func (s *Server) ContextWindowFor(model string) (int, bool)
- func (s *Server) Handler() http.Handler
- func (s *Server) IncrSpill(keyName, servedBy string)
- func (s *Server) LoadFromStore() error
- func (s *Server) LocalTokens() int64
- func (s *Server) LogRequest(requestID, apiKey, sourceIP, model, node, status string, httpStatus int, ...)
- func (s *Server) ModelConfigFor(model, node string) (store.ModelConfig, bool)
- func (s *Server) ReloadFromStore() (nodesAdded, nodesRemoved, authKeys, cloudProviders int, err error)
- func (s *Server) SetAuditLogger(al *audit.Logger)
- func (s *Server) SetDeadlineObserver(fn func(op string, err error))
- func (s *Server) SetDemoMode(v bool)
- func (s *Server) SetProxyHandler(p managementEndpointsSetter)
- func (s *Server) SetRestoreChannel(ch chan<- string)
- func (s *Server) SetStore(st store.Store)
- func (s *Server) SetVersion(v string)
- func (s *Server) Shutdown()
- func (s *Server) StartBackupScheduler(ctx context.Context)
- func (s *Server) StartCounterFlush(ctx context.Context)
- func (s *Server) StartPeriodicCleanup(ctx context.Context)
- func (s *Server) StopBackups()
- func (s *Server) SweepBackupDir(dir string)
- func (s *Server) TrackCloudCostModel(keyName, provider, model string, costPer1K float64, tokens int64)
- func (s *Server) TrackLocalRequestModel(keyName, model string, tokens, genDurationMs int64)
- type SystemInfo
- type TokenEvent
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func MarkRestoreNotCarriedOut ¶ added in v0.25.2
func MarkRestoreNotCarriedOut(dbPath string)
MarkRestoreNotCarriedOut records in the pending marker that the restore was abandoned and its staged file removed, so the next start can report it precisely. A missing marker is not an error.
func NodeSignalIDs ¶ added in v0.25.1
func NodeSignalIDs() []string
NodeSignalIDs returns the valid signal ids in canonical order. The slice is a copy; callers may modify it.
func WriteRestoreOutcome ¶ added in v0.25.2
WriteRestoreOutcome records, next to the database file, how a restore ended. The process exits right after a restore, so the next start reads this and shows the result in the dashboard. restoreErr nil means success; note is a caveat on a success. It returns the reference of the restore (taken from the pending marker) that the outcome text and the log both carry, so the operator can match them. The pending marker is removed once the outcome is durable.
Types ¶
type BudgetEntry ¶
type BudgetEntry struct {
Name string `json:"name,omitempty"`
DailySpent float64 `json:"dailySpent"`
DailyCap float64 `json:"dailyCap"`
DailyPct float64 `json:"dailyPct"`
MonthlySpent float64 `json:"monthlySpent"`
MonthlyCap float64 `json:"monthlyCap"`
MonthlyPct float64 `json:"monthlyPct"`
}
BudgetEntry is one cloud-spend budget's current standing (global or a single key), used by the soft-budget warning banner. Pct is 0 when its cap is unset (0/disabled) - never divides by zero.
type CatalogModel ¶
type CatalogModel struct {
Name string `json:"name"` // e.g. "llama3.2:3b"
DisplayName string `json:"display_name"` // e.g. "Llama 3.2 3B"
Description string `json:"description"`
ParamCount string `json:"param_count"` // "3B", "8B", "70B"
Categories []string `json:"categories"` // ["chat", "coding", "reasoning"]
Variants []ModelVariant `json:"variants"` // different quant options
Popular bool `json:"popular"`
Rank int `json:"rank"` // lower = more popular
}
CatalogModel is a curated, popular Ollama model baked into the binary.
type CloudBudgetStatusResp ¶
type CloudBudgetStatusResp struct {
SoftBudgetPct float64 `json:"softBudgetPct"`
Global BudgetEntry `json:"global"`
PerKey []BudgetEntry `json:"perKey"`
}
CloudBudgetStatusResp is the /admin/cloud-budget-status response: the global budget plus every key that has its own cap set. Keys with no cap configured are omitted - nothing to warn about.
type ContextFeasibility ¶
type ContextFeasibility struct {
// Confidence is "derived" when real transformer architecture facts were
// available (Ollama /api/show for a downloaded model, or an HF repo's
// config.json) and the KV-cache formula in kvCacheBytesPerToken actually
// ran; "estimated" when only the pre-existing linear multiplier could be
// used. Never any other value.
Confidence string `json:"confidence"`
// RequestedCtx echoes the context length this advice was computed for.
RequestedCtx int64 `json:"requested_ctx"`
// DeclaredMaxContext is the model's own trained maximum context length,
// Known only when Confidence=="derived" - nil (omitted) otherwise, never
// guessed.
DeclaredMaxContext *int64 `json:"declared_max_context,omitempty"`
// ExceedsDeclaredMax is true when RequestedCtx is beyond the model's own
// trained maximum - a correctness problem distinct from a VRAM/memory
// problem, only ever set when DeclaredMaxContext is Known.
ExceedsDeclaredMax bool `json:"exceeds_declared_max,omitempty"`
// KVCacheEstMB is the real per-token KV-cache formula's result at
// RequestedCtx, in MB. Only populated when Confidence=="derived".
KVCacheEstMB int64 `json:"kv_cache_est_mb,omitempty"`
// LimitingFactor names which term dominates the total estimate at
// RequestedCtx: "weights" or "kv_cache". Only populated when
// Confidence=="derived" - the linear estimate has no way to separate the
// two terms honestly.
LimitingFactor string `json:"limiting_factor,omitempty"`
// RecommendedCtx is the largest context length <= RequestedCtx (capped at
// DeclaredMaxContext) that the same real formula classifies "green" on
// this node. Only ever set when Confidence=="derived" and the requested
// length itself did not already classify green - never offered as a
// suggestion built on a rough estimate.
RecommendedCtx *int64 `json:"recommended_ctx,omitempty"`
// RuntimeCaveat is a short, static, runtime-family-specific note about
// what remains Unknown even when Confidence=="derived" (e.g. a runtime's
// own launched context ceiling, which this codebase has no way to
// discover). Empty when there's nothing to add.
RuntimeCaveat string `json:"runtime_caveat,omitempty"`
}
ContextFeasibility carries the context-length feasibility advice for one model variant at one requested context length. Confidence is always populated ("derived" or "estimated") so a caller can never mistake a rough linear guess for a real architecture-derived calculation - see the design's Known/Derived/Estimated/Unknown distinction.
type HFModelInfo ¶
type HFModelInfo struct {
ID string `json:"id"`
Downloads int `json:"downloads"`
Likes int `json:"likes"`
Tags []string `json:"tags"`
LastModified string `json:"lastModified"`
PipelineTag string `json:"pipeline_tag"`
CreatedAt string `json:"createdAt"`
}
HFModelInfo represents the metadata returned by Hugging Face API
type HFRepoResponse ¶
type HFRepoResponse struct {
ID string `json:"id"`
Downloads int `json:"downloads"`
Likes int `json:"likes"`
Tags []string `json:"tags"`
LastModified string `json:"lastModified"`
Siblings []struct {
Rfilename string `json:"rfilename"`
Size int64 `json:"size"`
} `json:"siblings"`
}
HFRepoResponse represents the detail returned by Hugging Face API for a single repository
type HourlyBucket ¶
type HourlyBucket struct {
Hour string `json:"hour"` // "2026-05-23T14" format
Local int64 `json:"local"`
Cloud int64 `json:"cloud"`
SavedUSD float64 `json:"saved_usd"`
SpentUSD float64 `json:"spent_usd"`
// Tokens and GenDurationMs are raw accumulators for local (Ollama-native)
// requests, real eval_count/eval_duration parsed from responses.
// TokensPerSec is derived from them (Tokens / GenDurationMs) only when
// GenDurationMs > 0 for the hour; otherwise 0, meaning no real
// generation-time data was available for this hour - never a fabricated
// rate.
Tokens int64 `json:"tokens"`
GenDurationMs int64 `json:"gen_duration_ms"`
TokensPerSec float64 `json:"tokens_per_sec"`
}
HourlyBucket tracks request counts and costs for one UTC hour.
type ModelStat ¶
type ModelStat struct {
Model string `json:"model"`
Local int64 `json:"local"`
Cloud int64 `json:"cloud"`
SavedUSD float64 `json:"saved_usd"`
}
ModelStat tracks aggregate stats per model.
type ModelVariant ¶
type ModelVariant struct {
Tag string `json:"tag"` // "llama3.2:3b-instruct-q4_K_M"
Quantization string `json:"quantization"` // "Q4_K_M"
VRAMEstMB int64 `json:"vram_est_mb"` // estimated VRAM in MB
SizeMB int64 `json:"size_mb"` // download size in MB
Recommended bool `json:"recommended"` // best quality/size tradeoff
}
ModelVariant is a specific quantization of a catalog model.
type ModelVariantFit ¶
type ModelVariantFit struct {
Tag string `json:"tag"` // "hf.co/username/repo:quant"
Quantization string `json:"quantization"` // "Q4_K_M"
VRAMEstMB int64 `json:"vram_est_mb"`
SizeMB int64 `json:"size_mb"`
Fit string `json:"fit"` // "green", "yellow", "red", "unknown"
DiskFit string `json:"disk_fit"` // "ok", "insufficient", "unknown"
Downloaded bool `json:"downloaded"`
// ContextFeasibility is the context-length feasibility advice at the
// requested ctx query-param value. Additive-only field; VRAMEstMB/Fit
// above already incorporate whatever total this struct computed (derived
// or estimated) so existing consumers see the improved number for free,
// while this field carries the confidence label and explanation that
// make it possible to tell a real architecture-derived answer from the
// older linear guess (never presented as more certain than it is).
ContextFeasibility ContextFeasibility `json:"context_feasibility"`
}
type RequestLog ¶
type RequestLog struct {
ID string `json:"id"`
ApiKey string `json:"apiKey"`
SourceIP string `json:"sourceIP"`
Model string `json:"model"`
Node string `json:"routedTo"`
Status string `json:"status"`
HTTPStatus int `json:"httpStatus"`
Latency int `json:"latency"`
Tokens int64 `json:"tokens"`
TokensPerSec float64 `json:"tokensPerSec"`
Time time.Time `json:"time"`
// RoutingReason is the top-level routing explanation (session_affinity |
// pinned_warm | score_based); empty for cloud-fallback requests, which
// have no router.RoutingDecision. RoutingDetail is the JSON-encoded
// router.RoutingDecision, kept off the /admin/requests list response
// (only RoutingReason is serialized there) and used internally by the
// /admin/v1/requests/{id}/explain handler for recent (in-memory-ring)
// requests without a round-trip to SQLite.
RoutingReason string `json:"routingReason,omitempty"`
RoutingDetail string `json:"-"`
// PrefillMs is Ollama's real prompt_eval_duration in milliseconds (see
// proxy.statusRecorder.promptEvalDurationMs) - the prefill half of a
// request's total latency, as opposed to generation time. 0 means
// unavailable: cloud requests never report it, and non-Ollama local
// runtimes have no equivalent per-request field on this response-parsing
// path (their engine telemetry is a separate, node-level aggregate
// scrape, not attributable to one request). Never a fabricated real
// zero - a genuine prefill always takes non-zero time.
PrefillMs int64 `json:"prefillMs,omitempty"`
}
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
func (*Server) AcknowledgeRestoreResult ¶ added in v0.25.2
AcknowledgeRestoreResult clears the shown result of the last restore, if its reference is ref ("-" stands for a result with no reference). The saved copy is removed first and the in-memory result cleared only after that worked: a failed removal leaves the result visible, so what is shown is what would come back at the next start. A client acknowledging a result it did not show gets errRestoreRefMismatch.
func (*Server) AdminToken ¶
AdminToken enables demo mode on the server and returns the static demo session token. Use only in tests to bypass DB-backed session auth when the authentication pathway itself is not under test.
func (*Server) CloseRestores ¶ added in v0.25.2
CloseRestores stops accepting restores (main calls it as soon as shutdown starts) and returns the staged path of a restore that was handed off, so main performs it even when the signal that began the shutdown won the race against the channel. It returns "" when no restore is pending.
func (*Server) CloudBudgetExceeded ¶
CloudBudgetExceeded reports whether cumulative cloud spend has reached the configured daily or monthly cap - the global cap (routing.cloud_budget in config) or, if keyName has its own cap set, that key's cap - and a human-readable reason if so. Global caps default to 0 (disabled); a key with no cap configured is only subject to the global check.
func (*Server) ContextWindowFor ¶
ContextWindowFor returns the operator-declared context window (in tokens) for model from config.context_windows, and whether one is configured. A model with no declared window means the proxy performs no admission-time context-length check for it (fails open - never guess a value that wasn't declared).
func (*Server) IncrSpill ¶
IncrSpill increments the (keyName, servedBy) row in spill_counters. servedBy is "local", a cloud provider's Name, or "blocked" (a local_only policy rejection). Best-effort accounting only: a SQLite error here (e.g. momentarily locked) is logged and otherwise ignored - it must never affect the inference request that triggered it, the same posture LogRequest's own async writer already takes on a full queue.
func (*Server) LoadFromStore ¶
LoadFromStore seeds in-memory state from the persistent store on startup. Errors are non-fatal - the server still runs, just with a cold cache.
func (*Server) LocalTokens ¶
LocalTokens returns the running total of real tokens served by local nodes. Exported only so integration tests in internal/proxy can verify that streamed responses produce real token counts; the value is otherwise exposed solely through the savings endpoint.
func (*Server) LogRequest ¶
func (s *Server) LogRequest(requestID, apiKey, sourceIP, model, node, status string, httpStatus int, latencyMs int, tokens int64, prefillMs int64, decision *router.RoutingDecision)
LogRequest records a completed request. status is a semantic label ("warm", "loading", "error", "aborted", "cloud") used for cold/warm tracking and the live-requests dashboard badge - it is never parsed as a number. httpStatus is the real numeric HTTP status the client received (from statusRecorder.StatusCode() in proxy.go) and is what gets persisted to the SQLite request_log and served from /admin/requests.
requestID is the trace ID proxy.go already generates once per request (the same one used for X-Request-ID and audit.Entry.RequestID) - it becomes request_log.id, replacing a previously independently-minted id. This has no external format coupling (verified during the routing- explainability feature's verify-before-build pass) and lets request_log rows be correlated with audit_log/access-log entries for the same request, which the two separately-minted ID spaces could not before.
decision is the routing explanation from the router for this request's chosen node; nil for cloud-fallback requests, which have no router.RoutingDecision.
func (*Server) ModelConfigFor ¶
func (s *Server) ModelConfigFor(model, node string) (store.ModelConfig, bool)
ModelConfigFor returns the operator-configured default parameter profile for model on the given node, if one exists. Lets the proxy inject defaults without holding a direct store reference (mirrors ContextWindowFor's admin-as-facade shape).
func (*Server) ReloadFromStore ¶
func (s *Server) ReloadFromStore() (nodesAdded, nodesRemoved, authKeys, cloudProviders int, err error)
ReloadFromStore re-syncs live router/auth state from SQLite - the marbor.db-first replacement for the old "reload config.yaml from disk" behavior. Used by both handleConfigReload (POST /admin/config/reload) and main.go's SIGHUP handler, since there is no file left to re-read; SQLite (already the source of truth for nodes/keys/cloud providers/settings) is re-applied to the live router/auth instead.
func (*Server) SetAuditLogger ¶
SetAuditLogger wires the audit logger into the admin server for query access.
func (*Server) SetDeadlineObserver ¶ added in v0.25.2
SetDeadlineObserver installs a function that is told about every connection deadline change a backup transfer through this server makes and whether it worked. It exists so a test can prove, through the real middleware chain, that the deadlines reach the connection. Pass nil to remove it.
func (*Server) SetDemoMode ¶
SetDemoMode enables demo mode, where the dashboard login accepts admin/admin.
func (*Server) SetProxyHandler ¶
func (s *Server) SetProxyHandler(p managementEndpointsSetter)
SetProxyHandler wires the proxy handler so routing.allow_management_endpoints changes made via handleUpdateSettings/handleConfigReload take effect immediately instead of only at boot.
func (*Server) SetRestoreChannel ¶
SetRestoreChannel wires the channel handleRestoreBackup sends a validated backup file's full path down after a one-click restore request. main.go owns process-lifecycle decisions (graceful shutdown, file swap, exit code for the supervisor to restart on), so the HTTP handler here only validates the request and hands off - it never performs the swap or exits itself. Left nil in tests/demo/other run modes that never wire this: the handler returns 501 rather than silently accepting a restore it can't act on.
func (*Server) SetStore ¶
SetStore replaces the persistence backend. Useful for tests and for wiring a real SQLite store after construction when the store isn't known yet. If st is nil, NopStore is used so callers never need to nil-check.
func (*Server) SetVersion ¶
SetVersion sets the version string reported by /health. Call this from main with the ldflags-injected version before serving.
func (*Server) Shutdown ¶
func (s *Server) Shutdown()
Shutdown drains any in-flight request logs and stops the async logger. Call this after the HTTP servers have stopped accepting new requests and before closing the store, or the logger can still be writing through s.st after it's been closed.
func (*Server) StartBackupScheduler ¶
StartBackupScheduler launches a background goroutine that runs a scheduled marbor.db backup into cfg.Backup.TargetDir whenever it is enabled and due, then prunes old backup files beyond cfg.Backup.RetentionCount. The start-up housekeeping (loading the saved status, picking up the outcome of a restore, removing what a run that died left behind) runs first, in that goroutine. Until it finishes the housekeeping flag is set and backup, upload and restore requests are refused with a message that says so; no lock is held across it. A second call does nothing. ctx cancellation, or StopBackups, stops the ticker and any running backup, and Shutdown waits for the goroutine.
func (*Server) StartCounterFlush ¶
StartCounterFlush launches a background goroutine that persists global counters every 30 seconds. Call once after construction; ctx cancellation stops the ticker.
func (*Server) StartPeriodicCleanup ¶
StartPeriodicCleanup launches a background goroutine that prunes expired user sessions and audit_log rows past their retention window every 12 hours (plus once at startup, so a long-idle marbor doesn't wait 12h for its first prune). Call once after construction; ctx cancellation stops the ticker, mirroring StartCounterFlush.
func (*Server) StopBackups ¶ added in v0.25.2
func (s *Server) StopBackups()
StopBackups cancels the scheduler and any scheduled or swept work, stops new backups from starting, and waits (bounded) for them to end. main calls it as soon as a restore is accepted, before the servers drain, so no snapshot is holding the database open when it has to be closed and replaced.
func (*Server) SweepBackupDir ¶ added in v0.25.2
SweepBackupDir clears marbor's leftover files from dir, which has just been configured as the backup directory. It never blocks the settings request or a backup: when a backup, upload or restore check is using the directory it waits and tries again, and it stops at shutdown. It is tracked with the scheduler, which Shutdown waits for.
func (*Server) TrackCloudCostModel ¶
func (s *Server) TrackCloudCostModel(keyName, provider, model string, costPer1K float64, tokens int64)
TrackCloudCostModel tracks a cloud request with model-level granularity. tokens is the real token count parsed from the provider response; 0 means the count was unavailable and no cost is recorded for the request.
func (*Server) TrackLocalRequestModel ¶
TrackLocalRequestModel tracks a local request with model-level granularity. tokens is the real token count parsed from the response (eval_count + prompt_eval_count); 0 means the count was unavailable and contributes nothing to savings. genDurationMs is Ollama's real eval_duration in milliseconds (generation time only, excluding prompt processing); 0 means unavailable (cloud responses never report it) and is excluded from the hourly tokens-per-second rollup rather than skewing it toward infinity.
type SystemInfo ¶
type SystemInfo struct {
CPUCores int `json:"cpu_cores"`
OS string `json:"os"`
Arch string `json:"arch"`
RAMTotalMB int64 `json:"ram_total_mb"`
RAMFreeMB int64 `json:"ram_free_mb"`
// RAMKnown is false when readSystemMemory couldn't actually read the
// host's memory (as opposed to RAMTotalMB/RAMFreeMB being 0 because
// they're genuinely unset) - real data or unknown, never a fake 0
// presented as a measurement.
RAMKnown bool `json:"ram_known"`
GPUs []sysGPUEntry `json:"gpus"`
ServerTime string `json:"server_time"`
Timezone string `json:"timezone"`
}
type TokenEvent ¶
Source Files
¶
- admin.go
- analytics.go
- backup.go
- backup_http.go
- backup_os_unix.go
- backup_restore.go
- backup_restorestate.go
- backup_run.go
- backup_space.go
- backup_status.go
- backup_verify.go
- benchmark.go
- catalog.go
- catalog_hf.go
- fit_advisor.go
- model_aliases.go
- node_detected.go
- node_signals.go
- replica_guard.go
- replica_suggestions.go
- sole_replica.go
- sysinfo_unix.go