Documentation
¶
Index ¶
- Constants
- func AllowService(ruleUUID, serviceID string) bool
- func FormatBreakerKey(ruleUUID, serviceID string) string
- func FormatServiceID(providerUUID, model string) string
- func NormalizeServiceTiers(services []*Service) bool
- func RecordServiceFailure(ruleUUID, serviceID string)
- func RecordServiceSuccess(ruleUUID, serviceID string)
- type Breaker
- type BreakerState
- type BreakerStore
- func (s *BreakerStore) Allow(ruleUUID, serviceID string) bool
- func (s *BreakerStore) Get(ruleUUID, serviceID string) *Breaker
- func (s *BreakerStore) IsAvailable(ruleUUID, serviceID string) bool
- func (s *BreakerStore) RecordFailure(ruleUUID, serviceID string)
- func (s *BreakerStore) RecordSuccess(ruleUUID, serviceID string)
- func (s *BreakerStore) Reset()
- func (s *BreakerStore) WithinPromotionHold(ruleUUID, serviceID string, hold time.Duration) bool
- type HealthMonitor
- func (hm *HealthMonitor) GetAllHealth() map[string]*ServiceHealth
- func (hm *HealthMonitor) GetHealth(serviceID string) *ServiceHealth
- func (hm *HealthMonitor) IsHealthy(serviceID string) bool
- func (hm *HealthMonitor) RemoveHealth(serviceID string)
- func (hm *HealthMonitor) ReportAuthError(serviceID string, statusCode int)
- func (hm *HealthMonitor) ReportRateLimit(serviceID string)
- func (hm *HealthMonitor) ReportSuccess(serviceID string)
- func (hm *HealthMonitor) ResetHealth(serviceID string)
- func (hm *HealthMonitor) SetProbeFunc(fn HealthProbeFunc)
- func (hm *HealthMonitor) UpdateConfig(config HealthMonitorConfig)
- type HealthMonitorConfig
- type HealthProbeFunc
- type HealthStatus
- type Service
- type ServiceHealth
- type ServiceID
- type ServiceStats
- func (ss *ServiceStats) GetCacheStats() (hitRate float64, hits int64, misses int64)
- func (ss *ServiceStats) GetCostMetrics() int64
- func (ss *ServiceStats) GetLatencyStats() (avg, p50, p95, p99 float64, sampleCount int)
- func (ss *ServiceStats) GetStats() ServiceStats
- func (ss *ServiceStats) GetTTFTStats() (avg, p50, p95, p99 float64, sampleCount int)
- func (ss *ServiceStats) GetTokenSpeedStats() (avgSpeed float64, sampleCount int)
- func (ss *ServiceStats) GetWindowStats() (requestCount int64, tokensConsumed int64)
- func (ss *ServiceStats) GetWindowTokenDetails() (requestCount int64, inputTokens int64, outputTokens int64)
- func (ss *ServiceStats) IsWindowExpired() bool
- func (ss *ServiceStats) RecordCacheHit(isHit bool)
- func (ss *ServiceStats) RecordLatency(latencyMs int64, maxSamples int)
- func (ss *ServiceStats) RecordTTFT(ttftMs int64, maxSamples int)
- func (ss *ServiceStats) RecordTokenSpeed(speedTps float64, maxSamples int)
- func (ss *ServiceStats) RecordUsage(inputTokens, outputTokens int)
- func (ss *ServiceStats) ResetWindow()
- type TacticType
Constants ¶
const ( DefaultBreakerFailureThreshold = 3 DefaultBreakerOpenDuration = 30 * time.Second DefaultBreakerRecoveryThreshold = 3 // consecutive half-open successes required to close // DefaultPromotionHold is how long a recovered (Closed) primary tier must // stay recovered before it can reclaim sessions pinned to a lower tier. // It de-jitters batch return-to-primary: a freshly-recovered primary only // takes NEW sessions during the hold; existing fallback-tier pins migrate // back once the primary has proven stable. Zero disables the hold. DefaultPromotionHold = 60 * time.Second )
Default circuit breaker tunables.
Variables ¶
This section is empty.
Functions ¶
func AllowService ¶ added in v0.260531.1
AllowService is a package-level convenience used by selection logic.
func FormatBreakerKey ¶ added in v0.260716.1
FormatBreakerKey formats a (ruleUUID, serviceID) pair into the canonical "ruleUUID/serviceID" string used as the breaker-store key. The breaker is rule-scoped: each rule owns independent breaker state per service so a busy rule's failing traffic cannot trip another rule's primary. The serviceID half is FormatServiceID's "provider/model"; rule UUIDs are slash-free, so the composite is unambiguous. Mirrors the affinity store's rule-scoped key (internal/server/affinity/affinity.go makeKey).
func FormatServiceID ¶ added in v0.260604.1
FormatServiceID formats a (providerUUID, model) pair into the canonical "provider/model" string used as the exclusion map key and as the service-scoped half of the breaker key. Sites that don't have a full *Service in hand (the failover orchestrator, the recorder, usage tracking) call this directly so all paths agree on the same key shape.
func NormalizeServiceTiers ¶ added in v0.260813.1
NormalizeServiceTiers compacts Service.Tier values so tiers are contiguous starting at 0 while preserving relative order: e.g. tiers {1, 3} become {0, 1}. This keeps the persisted shape canonical no matter how services are added, moved, or deleted — emptying T0 automatically promotes T1 to T0. Returns true when any tier was rewritten.
func RecordServiceFailure ¶ added in v0.260531.1
func RecordServiceFailure(ruleUUID, serviceID string)
RecordServiceFailure is a package-level convenience used by dispatch.
func RecordServiceSuccess ¶ added in v0.260531.1
func RecordServiceSuccess(ruleUUID, serviceID string)
RecordServiceSuccess is a package-level convenience used by dispatch.
Types ¶
type Breaker ¶ added in v0.260531.1
type Breaker struct {
FailureThreshold int
OpenDuration time.Duration
RecoveryThreshold int // N_up: consecutive successes to recover
// contains filtered or unexported fields
}
Breaker is a three-state circuit breaker for a single service, with hysteresis on recovery to avoid tier oscillation.
- Closed → Open when consecutive failures hit FailureThreshold.
- Open → HalfOpen lazily, once OpenDuration has elapsed since the trip.
- HalfOpen → Closed only after RecoveryThreshold consecutive probe successes. A single success is not enough — it just releases the probe slot so the next probe can go through.
- HalfOpen → Open on any probe failure (timer restarts from scratch).
While HalfOpen, Allow() returns true for at most one caller at a time, so exactly one probe request goes through per probe round.
func NewBreaker ¶ added in v0.260531.1
NewBreaker creates a breaker with the supplied thresholds. Zero values fall back to defaults. RecoveryThreshold defaults to DefaultBreakerRecoveryThreshold.
func (*Breaker) Allow ¶ added in v0.260531.1
Allow reports whether a new request is permitted right now. It also performs the Open→HalfOpen transition when the open timer has expired and arbitrates which caller gets the probe slot.
func (*Breaker) ClosedSince ¶ added in v0.260716.1
ClosedSince returns when recovery last completed (the HalfOpen→Closed transition after RecoveryThreshold successes). It is zero while the service has never recovered or is currently open/tripping. Tier affinity uses it for PromotionHold: a primary tier must stay recovered for a hold period before it can reclaim sessions pinned to a lower tier, so a freshly-recovered primary doesn't vacuum all fallback-tier sessions back at once.
func (*Breaker) RecordFailure ¶ added in v0.260531.1
func (b *Breaker) RecordFailure()
RecordFailure increments failure tracking and trips the breaker when the threshold is reached. A failure during HalfOpen immediately re-opens and restarts the open timer from scratch.
func (*Breaker) RecordSuccess ¶ added in v0.260531.1
func (b *Breaker) RecordSuccess()
RecordSuccess closes the breaker once RecoveryThreshold consecutive probe successes have been observed in HalfOpen. Before the threshold is reached it merely releases the probe slot so the next probe can go through. A success from a Closed breaker resets failure tracking.
func (*Breaker) RetryIn ¶ added in v0.260716.1
RetryIn returns how long until an Open breaker lazily flips to HalfOpen (its next recovery probe). It is zero for Closed/HalfOpen breakers and for an Open breaker whose window has already elapsed. Intended for introspection / UI ("retrying in Ns").
func (*Breaker) State ¶ added in v0.260531.1
func (b *Breaker) State() BreakerState
State returns the current breaker state. Intended for introspection / UI.
type BreakerState ¶ added in v0.260531.1
type BreakerState int
BreakerState represents the state of a circuit breaker.
const ( BreakerClosed BreakerState = iota // Normal operation; requests pass through BreakerOpen // Tripped; requests are blocked BreakerHalfOpen // Recovery probe; one request is allowed )
func (BreakerState) String ¶ added in v0.260531.1
func (s BreakerState) String() string
String renders the breaker state for logs/UI.
type BreakerStore ¶ added in v0.260531.1
type BreakerStore struct {
// contains filtered or unexported fields
}
BreakerStore is a concurrent-safe registry of breakers keyed by (ruleUUID, serviceID). Breakers are created lazily on first access.
Breakers are rule-scoped: each rule owns independent breaker state per service. A service failing for one rule does NOT fail it for another rule that uses the same provider:model — each rule's failover decisions are driven only by the traffic it observes. This mirrors the rule-scoped affinity store (internal/server/affinity/affinity.go). Key composition lives in FormatBreakerKey.
func DefaultBreakerStore ¶ added in v0.260531.1
func DefaultBreakerStore() *BreakerStore
DefaultBreakerStore returns the process-wide breaker store.
func NewBreakerStore ¶ added in v0.260531.1
func NewBreakerStore(failureThreshold int, openDuration time.Duration) *BreakerStore
NewBreakerStore returns a BreakerStore. Defaults are applied for zero values, matching the package defaults.
func (*BreakerStore) Allow ¶ added in v0.260531.1
func (s *BreakerStore) Allow(ruleUUID, serviceID string) bool
Allow is a convenience over Get(ruleUUID, serviceID).Allow().
func (*BreakerStore) Get ¶ added in v0.260531.1
func (s *BreakerStore) Get(ruleUUID, serviceID string) *Breaker
Get returns the breaker for the given (ruleUUID, serviceID), creating one with the store's default thresholds if needed.
func (*BreakerStore) IsAvailable ¶ added in v0.260625.1
func (s *BreakerStore) IsAvailable(ruleUUID, serviceID string) bool
IsAvailable reports whether the service's breaker currently permits traffic, without consuming a half-open probe slot. Closed and HalfOpen are available; Open is not. Unlike Allow(), this is a side-effect-free read — callers that only need to know "is this service usable right now" (e.g. affinity scoping) should use it so they don't steal the single half-open probe from the selection path.
func (*BreakerStore) RecordFailure ¶ added in v0.260531.1
func (s *BreakerStore) RecordFailure(ruleUUID, serviceID string)
RecordFailure is a convenience over Get(ruleUUID, serviceID).RecordFailure().
func (*BreakerStore) RecordSuccess ¶ added in v0.260531.1
func (s *BreakerStore) RecordSuccess(ruleUUID, serviceID string)
RecordSuccess is a convenience over Get(ruleUUID, serviceID).RecordSuccess().
func (*BreakerStore) Reset ¶ added in v0.260625.1
func (s *BreakerStore) Reset()
Reset clears all breaker entries. Useful for tests/harness to avoid state leakage between scenarios when reusing the global store.
func (*BreakerStore) WithinPromotionHold ¶ added in v0.260716.1
func (s *BreakerStore) WithinPromotionHold(ruleUUID, serviceID string, hold time.Duration) bool
WithinPromotionHold reports whether the service recovered (entered Closed from a HalfOpen recovery) within the given hold window. Tier affinity uses this to keep sessions pinned to a lower tier from being vacuumed back to a freshly-recovered primary until it has proven stable for the hold. A service that is Open, HalfOpen, never-tripped, or recovered longer ago than hold is NOT within the hold. hold <= 0 disables the check (always false).
type HealthMonitor ¶
type HealthMonitor struct {
// contains filtered or unexported fields
}
HealthMonitor manages health status for all services
func NewHealthMonitor ¶
func NewHealthMonitor(config HealthMonitorConfig) *HealthMonitor
NewHealthMonitor creates a new health monitor with the given configuration
func (*HealthMonitor) GetAllHealth ¶
func (hm *HealthMonitor) GetAllHealth() map[string]*ServiceHealth
GetAllHealth returns health status for all services
func (*HealthMonitor) GetHealth ¶
func (hm *HealthMonitor) GetHealth(serviceID string) *ServiceHealth
GetHealth returns the health status for a service
func (*HealthMonitor) IsHealthy ¶
func (hm *HealthMonitor) IsHealthy(serviceID string) bool
IsHealthy checks if a service is healthy (with time-based recovery and probing)
func (*HealthMonitor) RemoveHealth ¶
func (hm *HealthMonitor) RemoveHealth(serviceID string)
RemoveHealth removes a service's health record
func (*HealthMonitor) ReportAuthError ¶
func (hm *HealthMonitor) ReportAuthError(serviceID string, statusCode int)
ReportAuthError reports a 401/403 auth error for a service
func (*HealthMonitor) ReportRateLimit ¶
func (hm *HealthMonitor) ReportRateLimit(serviceID string)
ReportRateLimit reports a 429 rate limit error for a service
func (*HealthMonitor) ReportSuccess ¶
func (hm *HealthMonitor) ReportSuccess(serviceID string)
ReportSuccess reports a successful request for a service
func (*HealthMonitor) ResetHealth ¶
func (hm *HealthMonitor) ResetHealth(serviceID string)
ResetHealth manually resets a service's health to healthy
func (*HealthMonitor) SetProbeFunc ¶
func (hm *HealthMonitor) SetProbeFunc(fn HealthProbeFunc)
SetProbeFunc sets the probe function for health checking during recovery
func (*HealthMonitor) UpdateConfig ¶
func (hm *HealthMonitor) UpdateConfig(config HealthMonitorConfig)
UpdateConfig updates the health monitor configuration
type HealthMonitorConfig ¶
type HealthMonitorConfig struct {
// RecoveryTimeoutSeconds is the time in seconds before auto-recovery
RecoveryTimeoutSeconds int `json:"recovery_timeout_seconds" yaml:"recovery_timeout_seconds"`
// ProbeEnabled enables health check probing before marking service healthy
ProbeEnabled bool `json:"probe_enabled" yaml:"probe_enabled"`
}
HealthMonitorConfig holds configuration for health monitoring
func DefaultHealthMonitorConfig ¶
func DefaultHealthMonitorConfig() HealthMonitorConfig
DefaultHealthMonitorConfig returns default configuration
type HealthProbeFunc ¶
HealthProbeFunc is the function type for probing service health Returns true if service is healthy, false otherwise
type HealthStatus ¶
type HealthStatus int
HealthStatus represents the health state of a service
const ( HealthHealthy HealthStatus = iota // Service is healthy and available HealthUnhealthy // Service is unhealthy (rate limited, failing) )
func (HealthStatus) String ¶
func (h HealthStatus) String() string
String returns the string representation of HealthStatus
type Service ¶
type Service struct {
Provider string `yaml:"provider" json:"provider"` // Provider name / uuid
Model string `yaml:"model" json:"model"` // Model name
Weight int `yaml:"weight" json:"weight"` // Weight for load balancing
Active bool `yaml:"active" json:"active"` // Whether this service is active
TimeWindow int `yaml:"time_window" json:"time_window"` // Statistics time window in seconds
ModelCapacity *int `yaml:"model_capacity,omitempty" json:"model_capacity,omitempty"` // ModelCapacity overrides the provider's default_model_capacity for this specific model
Tier int `yaml:"tier,omitempty" json:"tier,omitempty"` // Tier within a rule: lower number = tried first (T0 is highest priority). Used by TacticTier.
Stats ServiceStats `yaml:"-" json:"-"` // Service usage statistics (stored in SQLite, not in config)
}
Service represents a provider-model combination for load balancing
func (*Service) GetServiceID ¶ added in v0.260409.1540
GetServiceID returns the typed service identifier.
func (*Service) GetWindowStats ¶
GetWindowStats returns current window statistics for this service
func (*Service) InitializeStats ¶
func (s *Service) InitializeStats()
InitializeStats initializes the service statistics if they are empty
func (*Service) RecordUsage ¶
RecordUsage records usage for this service
type ServiceHealth ¶
type ServiceHealth struct {
ServiceID string // Unique service identifier (provider:model)
Status HealthStatus // Current health status
LastError error // Last error that caused unhealthy state
LastErrorTime time.Time // When the error occurred
RateLimited bool // True if last error was 429
AuthError bool // True if last error was 401/403
RateLimitedUntil time.Time // Earliest time when rate limit can be cleared
LastHealthCheck time.Time // Last time health was checked
RecoveryTimeout time.Duration // Time before auto-recovery
// contains filtered or unexported fields
}
ServiceHealth tracks health information for a single service
type ServiceID ¶ added in v0.260409.1540
ServiceID uniquely identifies a provider+model combination in load balancing.
func NewServiceID ¶ added in v0.260409.1540
NewServiceID creates a ServiceID from provider UUID/name and model.
type ServiceStats ¶
type ServiceStats struct {
ServiceID string `json:"service_id"` // Unique service identifier
RequestCount int64 `json:"request_count"` // Total request count
LastUsed time.Time `json:"last_used"` // Last usage timestamp
WindowStart time.Time `json:"window_start"` // Current time window start
WindowRequestCount int64 `json:"window_request_count"` // Requests in current window
WindowTokensConsumed int64 `json:"window_tokens_consumed"` // Tokens consumed in current window (input + output)
WindowInputTokens int64 `json:"window_input_tokens"` // Input tokens in current window
WindowOutputTokens int64 `json:"window_output_tokens"` // Output tokens in current window
TimeWindow int `json:"time_window"` // Copy of service's time window
// Latency tracking fields
LatencySamples []int64 `json:"-"` // Rolling window of latency samples (in ms)
AvgLatencyMs float64 `json:"avg_latency_ms"` // Average latency in current window
P50LatencyMs float64 `json:"p50_latency_ms"` // 50th percentile latency
P95LatencyMs float64 `json:"p95_latency_ms"` // 95th percentile latency
P99LatencyMs float64 `json:"p99_latency_ms"` // 99th percentile latency
LastLatencyUpdate time.Time `json:"last_latency_update"` // When latency was last updated
// Per-request output TPS tracking fields (decode speed after TTFT)
SpeedSamples []float64 `json:"-"` // Rolling window of token speed samples
AvgTokenSpeed float64 `json:"avg_token_speed"` // Average tokens per second
LastSpeedUpdate time.Time `json:"last_speed_update"` // When speed was last updated
// TTFT (Time To First Token) tracking fields
TTFTSamples []int64 `json:"-"` // Rolling window of TTFT samples (in ms)
AvgTTFTMs float64 `json:"avg_ttft_ms"` // Average TTFT in milliseconds
P50TTFTMs float64 `json:"p50_ttft_ms"` // 50th percentile TTFT
P95TTFTMs float64 `json:"p95_ttft_ms"` // 95th percentile TTFT
P99TTFTMs float64 `json:"p99_ttft_ms"` // 99th percentile TTFT
LastTTFTUpdate time.Time `json:"last_ttft_update"` // When TTFT was last updated
// Cache tracking fields
WindowCacheHits int64 `json:"window_cache_hits"` // Cache hits in current window
WindowCacheMisses int64 `json:"window_cache_misses"` // Cache misses in current window
CacheHitRate float64 `json:"cache_hit_rate"` // Cache hit rate (hits / total)
// Cost tracking fields (token-based)
WindowCostTokens int64 `json:"window_cost_tokens"` // Total tokens as cost proxy in current window
// contains filtered or unexported fields
}
ServiceStats tracks usage statistics for a service
func (*ServiceStats) GetCacheStats ¶
func (ss *ServiceStats) GetCacheStats() (hitRate float64, hits int64, misses int64)
GetCacheStats returns current cache statistics
func (*ServiceStats) GetCostMetrics ¶
func (ss *ServiceStats) GetCostMetrics() int64
GetCostMetrics returns cost-related metrics (token-based)
func (*ServiceStats) GetLatencyStats ¶
func (ss *ServiceStats) GetLatencyStats() (avg, p50, p95, p99 float64, sampleCount int)
GetLatencyStats returns current latency statistics
func (*ServiceStats) GetStats ¶
func (ss *ServiceStats) GetStats() ServiceStats
GetStats returns a copy of current statistics
func (*ServiceStats) GetTTFTStats ¶
func (ss *ServiceStats) GetTTFTStats() (avg, p50, p95, p99 float64, sampleCount int)
GetTTFTStats returns current TTFT statistics
func (*ServiceStats) GetTokenSpeedStats ¶
func (ss *ServiceStats) GetTokenSpeedStats() (avgSpeed float64, sampleCount int)
GetTokenSpeedStats returns current token speed statistics
func (*ServiceStats) GetWindowStats ¶
func (ss *ServiceStats) GetWindowStats() (requestCount int64, tokensConsumed int64)
GetWindowStats returns current window statistics
func (*ServiceStats) GetWindowTokenDetails ¶
func (ss *ServiceStats) GetWindowTokenDetails() (requestCount int64, inputTokens int64, outputTokens int64)
GetWindowTokenDetails returns current window input and output token details
func (*ServiceStats) IsWindowExpired ¶
func (ss *ServiceStats) IsWindowExpired() bool
IsWindowExpired checks if the current time window has expired
func (*ServiceStats) RecordCacheHit ¶
func (ss *ServiceStats) RecordCacheHit(isHit bool)
RecordCacheHit records a cache hit or miss event
func (*ServiceStats) RecordLatency ¶
func (ss *ServiceStats) RecordLatency(latencyMs int64, maxSamples int)
RecordLatency records a latency sample for this service
func (*ServiceStats) RecordTTFT ¶
func (ss *ServiceStats) RecordTTFT(ttftMs int64, maxSamples int)
RecordTTFT records a Time To First Token sample (in milliseconds)
func (*ServiceStats) RecordTokenSpeed ¶
func (ss *ServiceStats) RecordTokenSpeed(speedTps float64, maxSamples int)
RecordTokenSpeed records a per-request output TPS sample after TTFT
func (*ServiceStats) RecordUsage ¶
func (ss *ServiceStats) RecordUsage(inputTokens, outputTokens int)
RecordUsage records a usage event for this service
func (*ServiceStats) ResetWindow ¶
func (ss *ServiceStats) ResetWindow()
ResetWindow resets the time window statistics
type TacticType ¶
type TacticType int
TacticType represents different load balancing strategies
const ( TacticRandom TacticType // 3: Random selection with weighted probability TacticSpeedBased // 5: Route based on token generation speed TacticCapacityBased // 7: capacity-based load balancing TacticTier // 8: tier-based failover by Service.Tier (lower = tried first); ties share via sub-tactic )
func ParseTacticType ¶
func ParseTacticType(s string) TacticType
ParseTacticType parses string to TacticType, falling back to Random for unknown input (the documented default for unset/unknown tactics).
func ParseTacticTypeStrict ¶ added in v0.260716.1
func ParseTacticTypeStrict(s string) (TacticType, bool)
ParseTacticTypeStrict parses s (case-insensitively) into a TacticType, reporting whether it named a known tactic. Deprecated/removed names are still accepted and silently downgrade to a safe tactic so persisted configs keep working: round_robin/hybrid/token_based/latency_based/adaptive → random, priority → tier. Unlike ParseTacticType it does not fall back to Random on unknown input, so API surfaces can reject typos instead of silently degrading.
func (TacticType) MarshalJSON ¶
func (tt TacticType) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for TacticType
func (TacticType) String ¶
func (tt TacticType) String() string
String returns string representation of TacticType
func (*TacticType) UnmarshalJSON ¶
func (tt *TacticType) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler for TacticType