Documentation
¶
Index ¶
- Variables
- func Serves(ctx context.Context, mgr interface{ ... }, modelID, capability string) (bool, error)
- func ValidateCIDRs(remoteAddr string, allowedCIDRs []string) error
- func ValidateEndpoint(ctx context.Context, endpoint string, allowLocalhost bool) error
- type Candidate
- type CircuitBreaker
- func (cb *CircuitBreaker) IsBroken(ctx context.Context, nodeID string) (bool, error)
- func (cb *CircuitBreaker) RecordFailure(ctx context.Context, nodeID string) error
- func (cb *CircuitBreaker) RecordSuccess(ctx context.Context, nodeID string) error
- func (cb *CircuitBreaker) TryAcquireProbe(ctx context.Context, nodeID string) (bool, error)
- type Config
- type LeaseManager
- func (lm *LeaseManager) AcquireLease(ctx context.Context, nodeID, reqID string, maxConc int32, ttl time.Duration) (bool, error)
- func (lm *LeaseManager) ReleaseLease(ctx context.Context, nodeID, reqID string, cooldown time.Duration) error
- func (lm *LeaseManager) RenewLease(ctx context.Context, nodeID, reqID string, extension time.Duration) (bool, error)
- type Manager
- func (m *Manager) Circuit() *CircuitBreaker
- func (m *Manager) Config() Config
- func (m *Manager) Drain(ctx context.Context, nodeID string) error
- func (m *Manager) GetNodeState(ctx context.Context, nodeID string, hb *NodeHeartbeatData) (pb.NodeState, error)
- func (m *Manager) Heartbeat(ctx context.Context, hb *NodeHeartbeatData) (drainRequested bool, activeProxyRequests int32, err error)
- func (m *Manager) ListNodes(ctx context.Context) ([]*NodeSnapshot, error)
- func (m *Manager) Register(ctx context.Context, meta *NodeMeta) error
- func (m *Manager) Slots() *LeaseManager
- func (m *Manager) Start(ctx context.Context)
- func (m *Manager) Stop()
- func (m *Manager) Store() *Store
- func (m *Manager) Telemetry() *TelemetryTracker
- func (m *Manager) Unregister(ctx context.Context, nodeID string) error
- func (m *Manager) Usage() *UsageLog
- type NodeHeartbeatData
- type NodeMeta
- type NodePerfData
- type NodeSnapshot
- type PoolAdapter
- func (pa *PoolAdapter) CheckJudgeMedia(media []*llm.JudgeMediaPart, questions map[string]*llm.JudgeQuestion) error
- func (pa *PoolAdapter) EvaluateRollouts(ctx context.Context, req *llm.EvaluateRolloutsRequest, userID string, ...) (*llm.EvaluateRolloutsResult, error)
- func (pa *PoolAdapter) GenerateText(ctx context.Context, chat *llm.ChatContext) (*llm.Response, error)
- func (pa *PoolAdapter) GenerateTextStream(ctx context.Context, chat *llm.ChatContext, ...) error
- func (pa *PoolAdapter) Judge(ctx context.Context, req *llm.JudgeRequest, userID string, ...) (*llm.JudgeResult, error)
- func (pa *PoolAdapter) JudgesSerially() bool
- func (pa *PoolAdapter) SupportsStreaming() bool
- func (pa *PoolAdapter) Translate(ctx context.Context, req *llm.TranslateRequest, userID string, ...) (*llm.TranslateResult, error)
- type PoolResolver
- type Selector
- type Store
- func (s *Store) ClearDrain(ctx context.Context, nodeID string) error
- func (s *Store) GetAllNodeIDs(ctx context.Context) ([]string, error)
- func (s *Store) GetHeartbeat(ctx context.Context, nodeID string) (*NodeHeartbeatData, error)
- func (s *Store) GetInflight(ctx context.Context, nodeID string, now time.Time) (taken, active int32, err error)
- func (s *Store) GetMeta(ctx context.Context, nodeID string) (*NodeMeta, error)
- func (s *Store) IsDraining(ctx context.Context, nodeID string) (bool, error)
- func (s *Store) Keys() rediskeys.Keys
- func (s *Store) RemoveNode(ctx context.Context, nodeID string) error
- func (s *Store) SaveHeartbeat(ctx context.Context, hb *NodeHeartbeatData, ttl time.Duration) error
- func (s *Store) SaveMeta(ctx context.Context, meta *NodeMeta, ttl time.Duration) error
- func (s *Store) SetDrain(ctx context.Context, nodeID string) error
- func (s *Store) UpdateMeta(ctx context.Context, nodeID string, fn func(*NodeMeta) bool) (bool, error)
- type TelemetryTracker
- type UsageLog
- type UsagePage
- type UsageRecord
- type UserRateLimitResolver
Constants ¶
This section is empty.
Variables ¶
var ( ErrNodeNotFound = errors.New("nodes: node not found") ErrInvalidNode = errors.New("nodes: invalid registration") // the node's fault, not the pool's ErrCorruptNode = errors.New("nodes: unreadable node record") // Redis answered; the data is bad ErrBadCursor = errors.New("nodes: bad usage cursor") ErrNodeSlotExhausted = &nodeCapacityError{msg: "nodes: max concurrent requests reached"} ErrNodePoolFull = &nodeCapacityError{msg: "nodes: all candidate nodes at capacity"} ErrNoAvailableNodes = &nodeCapacityError{msg: "nodes: no healthy nodes available for model"} )
Functions ¶
func Serves ¶ added in v1.2.0
func Serves(ctx context.Context, mgr interface { ListNodes(context.Context) ([]*NodeSnapshot, error) }, modelID, capability string) (bool, error)
Serves reports whether some node may take modelID now for a call needing capability ("" for chat), by the filter SelectNode applies; ExplainRoute asks it instead of guessing.
func ValidateCIDRs ¶
ValidateCIDRs checks whether remoteAddr belongs to any of the allowed CIDRs. If allowedCIDRs is empty, any remote address is permitted.
Types ¶
type Candidate ¶
type Candidate struct {
Snapshot *NodeSnapshot
ModelSpec *pb.NodeModelSpec
EffectiveWeight float64
IsWarm bool
}
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker manages failure tracking and half-open state for nodes. When error rate or consecutive errors trip the breaker, state transitions to CIRCUIT_BROKEN. A probe request can attempt half-open recovery using Redis SET NX.
func NewCircuitBreaker ¶
func NewCircuitBreaker(rdb redis.UniversalClient, store *Store, failThresh int, cooldown time.Duration) *CircuitBreaker
func (*CircuitBreaker) RecordFailure ¶
func (cb *CircuitBreaker) RecordFailure(ctx context.Context, nodeID string) error
RecordFailure increments consecutive failures; trips breaker if threshold exceeded.
func (*CircuitBreaker) RecordSuccess ¶
func (cb *CircuitBreaker) RecordSuccess(ctx context.Context, nodeID string) error
RecordSuccess resets consecutive failure counters and clears circuit broken status.
func (*CircuitBreaker) TryAcquireProbe ¶
TryAcquireProbe attempts to acquire single probe slot during half-open state.
type LeaseManager ¶
type LeaseManager struct {
// contains filtered or unexported fields
}
func NewLeaseManager ¶
func NewLeaseManager(rdb redis.UniversalClient, store *Store) *LeaseManager
func (*LeaseManager) AcquireLease ¶
func (lm *LeaseManager) AcquireLease(ctx context.Context, nodeID, reqID string, maxConc int32, ttl time.Duration) (bool, error)
AcquireLease attempts to take a slot on nodeID. Returns true if acquired.
func (*LeaseManager) ReleaseLease ¶
func (lm *LeaseManager) ReleaseLease(ctx context.Context, nodeID, reqID string, cooldown time.Duration) error
ReleaseLease frees the slot, or with a positive cooldown keeps it taken until the cooldown ends; the hold then expires like any lease.
func (*LeaseManager) RenewLease ¶
func (lm *LeaseManager) RenewLease(ctx context.Context, nodeID, reqID string, extension time.Duration) (bool, error)
RenewLease extends lease expiration for streaming or long requests.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
func NewManager ¶
func NewManager(store *Store, slots *LeaseManager, circuit *CircuitBreaker, telemetry *TelemetryTracker, cfg Config) *Manager
func (*Manager) Circuit ¶
func (m *Manager) Circuit() *CircuitBreaker
func (*Manager) GetNodeState ¶
func (m *Manager) GetNodeState(ctx context.Context, nodeID string, hb *NodeHeartbeatData) (pb.NodeState, error)
GetNodeState calculates node state based on: 1. OFFLINE (heartbeat missing / expired) 2. DRAINING (operator requested or self reported) 3. PAUSED (the node's schedule is at 0%) 4. CIRCUIT_BROKEN (circuit tripped) 5. SUSPECT (GPU temp >= 88C or high utilization) 6. HEALTHY
func (*Manager) Heartbeat ¶
func (m *Manager) Heartbeat(ctx context.Context, hb *NodeHeartbeatData) (drainRequested bool, activeProxyRequests int32, err error)
Heartbeat processes node heartbeat and returns current state.
func (*Manager) ListNodes ¶
func (m *Manager) ListNodes(ctx context.Context) ([]*NodeSnapshot, error)
ListNodes builds snapshot list for all known nodes.
func (*Manager) Slots ¶
func (m *Manager) Slots() *LeaseManager
func (*Manager) Telemetry ¶
func (m *Manager) Telemetry() *TelemetryTracker
func (*Manager) Unregister ¶
Unregister handles graceful node unregistration.
type NodeHeartbeatData ¶
type NodeHeartbeatData struct {
NodeID string `json:"node_id"`
LastHeartbeat time.Time `json:"last_heartbeat"`
Draining bool `json:"draining"`
ActiveRequests int32 `json:"active_requests"`
QueueDepth int32 `json:"queue_depth"`
VRAMTotalMB uint64 `json:"vram_total_mb"`
VRAMFreeMB uint64 `json:"vram_free_mb"`
GPUUtilPercent float64 `json:"gpu_util_percent"`
GPUTempC uint32 `json:"gpu_temp_c"`
GPUModel string `json:"gpu_model"`
WarmModels []string `json:"warm_models"`
ModelSpecs []*pb.NodeModelSpec `json:"model_specs,omitempty"`
CapacityPercent *uint32 `json:"capacity_percent,omitempty"` // nil = 100
ScheduleSource string `json:"schedule_source,omitempty"` // local | ktms
CapacitySource string `json:"capacity_source,omitempty"`
CapacityUntil *time.Time `json:"capacity_until,omitempty"`
}
type NodeMeta ¶
type NodeMeta struct {
NodeID string `json:"node_id"`
Name string `json:"name"`
Endpoint string `json:"endpoint"`
Engine string `json:"engine"`
AuthToken string `json:"auth_token,omitempty"`
BaseWeight float64 `json:"base_weight"`
MaxConcurrent int32 `json:"max_concurrent"`
Models []*pb.NodeModelSpec `json:"models"`
Tags map[string]string `json:"tags,omitempty"`
RegisteredAt time.Time `json:"registered_at"`
}
type NodePerfData ¶
type NodeSnapshot ¶
type NodeSnapshot struct {
Meta *NodeMeta
Heartbeat *NodeHeartbeatData
Perf map[string]*NodePerfData // modelID -> perf
Inflight int32 // slots taken, cooldown holds included
Active int32 // requests running
State pb.NodeState
}
func (*NodeSnapshot) Capacity ¶ added in v1.1.0
func (n *NodeSnapshot) Capacity() uint32
Capacity is the share of time, 0-100, the node may spend on proxy requests.
func (*NodeSnapshot) Cooldown ¶ added in v1.1.0
func (n *NodeSnapshot) Cooldown(d time.Duration) time.Duration
Cooldown is how long a slot stays taken after a request that ran for d. Rounding slots up overshoots the level (one slot of one is 100%, not 50%), so the slot idles for the difference: a 20 s request at 1 slot, 50% -> 20 s.
func (*NodeSnapshot) Slots ¶ added in v1.1.0
func (n *NodeSnapshot) Slots() int32
Slots is how many requests may run at once at the node's level.
type PoolAdapter ¶
type PoolAdapter struct {
// contains filtered or unexported fields
}
func NewPoolAdapter ¶
func NewPoolAdapter(selector *Selector, keyring *crypto.Keyring, model *proxydb.Model, leaseTTL time.Duration, userLimitResolver UserRateLimitResolver) *PoolAdapter
func (*PoolAdapter) CheckJudgeMedia ¶ added in v1.9.0
func (pa *PoolAdapter) CheckJudgeMedia(media []*llm.JudgeMediaPart, questions map[string]*llm.JudgeQuestion) error
CheckJudgeMedia applies the node's System One image limits before a rollout takes any slot; OpenAI-style node judges have no check of their own.
func (*PoolAdapter) EvaluateRollouts ¶
func (pa *PoolAdapter) EvaluateRollouts(ctx context.Context, req *llm.EvaluateRolloutsRequest, userID string, meta map[string]string) (*llm.EvaluateRolloutsResult, error)
EvaluateRollouts scores multiple rollout candidate actions against a local node. System One has no rollouts route: such models yield, and the caller judges each candidate with Judge instead.
func (*PoolAdapter) GenerateText ¶
func (pa *PoolAdapter) GenerateText(ctx context.Context, chat *llm.ChatContext) (*llm.Response, error)
func (*PoolAdapter) GenerateTextStream ¶
func (pa *PoolAdapter) GenerateTextStream(ctx context.Context, chat *llm.ChatContext, onChunk func(llm.StreamChunk) error) error
func (*PoolAdapter) Judge ¶
func (pa *PoolAdapter) Judge(ctx context.Context, req *llm.JudgeRequest, userID string, meta map[string]string) (*llm.JudgeResult, error)
Judge evaluates a decision request against a local node with judge capability.
func (*PoolAdapter) JudgesSerially ¶ added in v1.9.0
func (pa *PoolAdapter) JudgesSerially() bool
JudgesSerially is true for System One models: there is no rollouts route, and parallel candidates would race for the node's few slots and fail.
func (*PoolAdapter) SupportsStreaming ¶
func (pa *PoolAdapter) SupportsStreaming() bool
func (*PoolAdapter) Translate ¶ added in v1.6.0
func (pa *PoolAdapter) Translate(ctx context.Context, req *llm.TranslateRequest, userID string, meta map[string]string) (*llm.TranslateResult, error)
Translate sends the batch to an MT engine when a node serves this model natively (engine mt, spec capability translate), and otherwise translates by prompt through GenerateText, as a chat model on a node does.
type PoolResolver ¶
type PoolResolver struct {
// contains filtered or unexported fields
}
func NewPoolResolver ¶
func (*PoolResolver) PoolAdapter ¶
func (pr *PoolResolver) PoolAdapter(m *proxydb.Model) (llm.ClientAdapter, error)
func (*PoolResolver) SetUserRateLimitResolver ¶
func (pr *PoolResolver) SetUserRateLimitResolver(resolver UserRateLimitResolver)
type Selector ¶
type Selector struct {
// contains filtered or unexported fields
}
func NewSelector ¶
func (*Selector) SelectNode ¶
SelectNode performs candidate filtering and weighted selection: 1. Filter by model support, state (HEALTHY over SUSPECT, probe CIRCUIT_BROKEN when no healthy/suspect). 2. Strict warm over cold filter: if any warm node has capacity, cold nodes are eliminated. 3. Compute effective weights: W_eff = base_weight * F_perf * F_load. 4. Smooth WRR selection.
func (*Selector) SelectNodeForCapability ¶
func (s *Selector) SelectNodeForCapability(ctx context.Context, modelID string, capability string) (*Candidate, error)
SelectNodeForCapability performs candidate filtering and weighted selection, optionally filtering for a specific capability (e.g. "judge").
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store interacts with Redis to persist and query node status.
func (*Store) ClearDrain ¶
ClearDrain removes draining flag.
func (*Store) GetAllNodeIDs ¶
GetAllNodeIDs returns all node IDs in the pool.
func (*Store) GetHeartbeat ¶
GetHeartbeat retrieves node heartbeat.
func (*Store) GetInflight ¶ added in v1.1.0
func (s *Store) GetInflight(ctx context.Context, nodeID string, now time.Time) (taken, active int32, err error)
GetInflight purges expired leases and returns the slots taken and, of those, the requests still running (cooldown holds left out). The set holds at most a slot count of members.
func (*Store) IsDraining ¶
IsDraining checks if node is marked for draining.
func (*Store) RemoveNode ¶
RemoveNode completely evicts a node from Redis.
func (*Store) SaveHeartbeat ¶
SaveHeartbeat updates the dynamic heartbeat record with TTL.
func (*Store) UpdateMeta ¶ added in v0.14.0
func (s *Store) UpdateMeta(ctx context.Context, nodeID string, fn func(*NodeMeta) bool) (bool, error)
UpdateMeta rewrites a node's meta in place when fn reports a change. It keeps the remaining TTL and, through WATCH, gives up rather than overwrite a registration or removal that happened meanwhile; a missing node is left missing.
type TelemetryTracker ¶
type TelemetryTracker struct {
// contains filtered or unexported fields
}
func NewTelemetryTracker ¶
func NewTelemetryTracker(rdb redis.UniversalClient, store *Store, alpha float64, ttl time.Duration) *TelemetryTracker
func (*TelemetryTracker) GetPerf ¶
func (tt *TelemetryTracker) GetPerf(ctx context.Context, nodeID, modelID string) (*NodePerfData, error)
GetPerf retrieves performance metrics for node and model.
func (*TelemetryTracker) RecordMetrics ¶
func (tt *TelemetryTracker) RecordMetrics(ctx context.Context, nodeID, modelID string, tps float64, ttftNormalizedMs float64) error
RecordMetrics updates EWMA for a node & model. For unary calls, ttftNormalizedMs may be <= 0.
type UsageLog ¶ added in v1.3.0
type UsageLog struct {
// contains filtered or unexported fields
}
UsageLog keeps each node's requests in a Redis stream that every proxy replica appends to, trimmed by age on each write.
func NewUsageLog ¶ added in v1.3.0
func (*UsageLog) Append ¶ added in v1.3.0
Append adds a record and drops those older than the retention. The TTL, refreshed on each write, removes the log of a node that stopped getting requests or is gone, which no later write would trim.
type UsagePage ¶ added in v1.3.0
type UsagePage struct {
Records []UsageRecord
NextID string
More bool
GapUntil time.Time // zero unless the cursor is older than the log keeps
}
UsagePage is one pull from a node's log.
type UsageRecord ¶ added in v1.3.0
type UsageRecord struct {
ID string `json:"-"`
RequestID string `json:"req"`
StartedAt time.Time `json:"at"`
DurationMs int64 `json:"dur"`
TTFTMs int64 `json:"ttft,omitempty"`
ModelID string `json:"model"`
Kind string `json:"kind"`
InputTokens int64 `json:"in,omitempty"`
OutputTokens int64 `json:"out,omitempty"`
CacheReadTokens int64 `json:"cache,omitempty"`
Outcome string `json:"outcome"`
ErrorCode string `json:"err,omitempty"`
CapacityPercent uint32 `json:"level"`
CooldownMs int64 `json:"cd,omitempty"`
}
UsageRecord is one request on a node as its owner sees it: what the machine did, never for whom.
type UserRateLimitResolver ¶
type UserRateLimitResolver func(userID, modelID string) *proxydb.UserRateLimit