nodes

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 28 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

Index

Constants

This section is empty.

Variables

View Source
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 string) (bool, error)

Serves reports whether some node may take modelID now, by the same filter SelectNode applies; ExplainRoute asks it instead of guessing.

func ValidateCIDRs

func ValidateCIDRs(remoteAddr string, allowedCIDRs []string) error

ValidateCIDRs checks whether remoteAddr belongs to any of the allowed CIDRs. If allowedCIDRs is empty, any remote address is permitted.

func ValidateEndpoint

func ValidateEndpoint(ctx context.Context, endpoint string, allowLocalhost bool) error

ValidateEndpoint checks that the endpoint URL is valid HTTP/HTTPS and prevents SSRF against localhost/loopback/link-local/cloud-metadata unless allowLocalhost is enabled.

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) IsBroken

func (cb *CircuitBreaker) IsBroken(ctx context.Context, nodeID string) (bool, error)

IsBroken checks if the circuit breaker is tripped.

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

func (cb *CircuitBreaker) TryAcquireProbe(ctx context.Context, nodeID string) (bool, error)

TryAcquireProbe attempts to acquire single probe slot during half-open state.

type Config

type Config struct {
	HeartbeatInterval time.Duration
	HeartbeatTTL      time.Duration
	RetentionTTL      time.Duration
	AllowLocalhost    bool
	UsageRetention    time.Duration // how long each node's request log is kept; 0 = no log
}

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) Config

func (m *Manager) Config() Config

func (*Manager) Drain

func (m *Manager) Drain(ctx context.Context, nodeID string) error

Drain marks a node for draining.

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) Register

func (m *Manager) Register(ctx context.Context, meta *NodeMeta) error

Register handles node self-registration.

func (*Manager) Slots

func (m *Manager) Slots() *LeaseManager

func (*Manager) Start

func (m *Manager) Start(ctx context.Context)

func (*Manager) Stop

func (m *Manager) Stop()

func (*Manager) Store

func (m *Manager) Store() *Store

func (*Manager) Telemetry

func (m *Manager) Telemetry() *TelemetryTracker

func (*Manager) Unregister

func (m *Manager) Unregister(ctx context.Context, nodeID string) error

Unregister handles graceful node unregistration.

func (*Manager) Usage added in v1.3.0

func (m *Manager) Usage() *UsageLog

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
}

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 NodePerfData struct {
	NodeID    string    `json:"node_id"`
	ModelID   string    `json:"model_id"`
	TPSEMA    float64   `json:"tps_ema"`
	TTFTEMAMs float64   `json:"ttft_ema_ms"`
	UpdatedAt time.Time `json:"updated_at"`
}

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) 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.

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) SupportsStreaming

func (pa *PoolAdapter) SupportsStreaming() bool

type PoolResolver

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

func NewPoolResolver

func NewPoolResolver(selector *Selector, keyring *crypto.Keyring, leaseTTL time.Duration) *PoolResolver

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 NewSelector(mgr *Manager) *Selector

func (*Selector) SelectNode

func (s *Selector) SelectNode(ctx context.Context, modelID string) (*Candidate, error)

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 NewStore

func NewStore(rdb redis.UniversalClient, keys rediskeys.Keys) *Store

func (*Store) ClearDrain

func (s *Store) ClearDrain(ctx context.Context, nodeID string) error

ClearDrain removes draining flag.

func (*Store) GetAllNodeIDs

func (s *Store) GetAllNodeIDs(ctx context.Context) ([]string, error)

GetAllNodeIDs returns all node IDs in the pool.

func (*Store) GetHeartbeat

func (s *Store) GetHeartbeat(ctx context.Context, nodeID string) (*NodeHeartbeatData, error)

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) GetMeta

func (s *Store) GetMeta(ctx context.Context, nodeID string) (*NodeMeta, error)

GetMeta retrieves node metadata.

func (*Store) IsDraining

func (s *Store) IsDraining(ctx context.Context, nodeID string) (bool, error)

IsDraining checks if node is marked for draining.

func (*Store) Keys

func (s *Store) Keys() rediskeys.Keys

Keys returns the configured rediskeys.Keys.

func (*Store) RemoveNode

func (s *Store) RemoveNode(ctx context.Context, nodeID string) error

RemoveNode completely evicts a node from Redis.

func (*Store) SaveHeartbeat

func (s *Store) SaveHeartbeat(ctx context.Context, hb *NodeHeartbeatData, ttl time.Duration) error

SaveHeartbeat updates the dynamic heartbeat record with TTL.

func (*Store) SaveMeta

func (s *Store) SaveMeta(ctx context.Context, meta *NodeMeta, ttl time.Duration) error

SaveMeta saves static node metadata and adds nodeID to nodes:all set.

func (*Store) SetDrain

func (s *Store) SetDrain(ctx context.Context, nodeID string) error

SetDrain marks a node for draining.

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 NewUsageLog(store *Store, retention time.Duration) *UsageLog

func (*UsageLog) Append added in v1.3.0

func (l *UsageLog) Append(ctx context.Context, nodeID string, r UsageRecord) error

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.

func (*UsageLog) Drop added in v1.3.0

func (l *UsageLog) Drop(ctx context.Context, nodeID string) error

Drop deletes a node's log: a new key for the same node id must not read the previous holder's history.

func (*UsageLog) Enabled added in v1.3.0

func (l *UsageLog) Enabled() bool

func (*UsageLog) Pull added in v1.3.0

func (l *UsageLog) Pull(ctx context.Context, nodeID, afterID string, limit int) (*UsagePage, error)

Pull returns up to limit records after the cursor afterID ("" = the oldest kept).

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

Jump to

Keyboard shortcuts

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