routing

package
v0.16.13 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 17 Imported by: 1 module, 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

Package routing implements the token-based channel selection engine with Fibonacci backoff cooldown and weighted random distribution.

Package routing implements the TokenRouter route selection engine. Split from the TS 3800-line monolith into independent modules with interface contracts and unidirectional dependencies.

Index

Constants

View Source
const (
	ChannelStatusEnabled          = "enabled"
	ChannelStatusCooldown         = "cooldown"
	ChannelStatusBreakerOpen      = "breaker_open"
	ChannelStatusManuallyDisabled = "manually_disabled"
)

Channel runtime status vocabulary for read-only operators (#622/#624).

View Source
const (
	FailureBackoffBaseSec                   = 15
	ShortWindowLimitCooldownMs              = 5 * 60 * 1000
	MaxFailureBackoffSec                    = 30 * 24 * 60 * 60 // 30 days
	RoundRobinFailureThreshold              = 3
	TokenRouterFailureCooldownMaxSecCeiling = MaxFailureBackoffSec
)
View Source
const (
	// CatalogSourceOfficial labels an official vendor list price from the
	// catalog (site points at the vendor's own API host).
	CatalogSourceOfficial = "catalog"
	// CatalogSourceRelayEstimate labels an official list price used only as
	// an estimate for a third-party relay site — never a real payment price.
	CatalogSourceRelayEstimate = "catalog_estimate"
)

Catalog pricing provenance labels for cold-start cost routing.

View Source
const (
	// PriceSourceObserved uses successful proxy_logs estimated_cost averages.
	PriceSourceObserved = "observed"
	// PriceSourceConfigured uses accounts.unit_cost set by operators.
	PriceSourceConfigured = "configured"
	// PriceSourceBilling uses rates/ratios recovered from proxy_logs.billing_details.
	PriceSourceBilling = "billing_details"
	// PriceSourceFallback uses platform FallbackTokenCost / default model ratios.
	// Always label invented defaults with this source (or ratesSource).
	PriceSourceFallback = "fallback"
)

Price comparison provenance labels. Callers must not invent unlabeled prices.

View Source
const (
	// DefaultCacheRatio is the historical Metapi fallback when cache_ratio is
	// missing for non-Claude models (input × 1.0).
	DefaultCacheRatio = 1.0
	// DefaultCacheCreationRatio is the historical Metapi fallback when
	// cache_creation_ratio is missing for non-Claude models.
	DefaultCacheCreationRatio = 1.0

	// ClaudeCacheRatio is Anthropic's cache-read multiplier (input × 0.1).
	ClaudeCacheRatio = 0.1
	// ClaudeCacheCreationRatio is Anthropic's cache-write / creation
	// multiplier (input × 1.25).
	ClaudeCacheCreationRatio = 1.25
)

Non-Claude models keep the original Metapi fallback of 1.0 so we do not invent vendor-specific multipliers without evidence.

View Source
const (
	SiteRuntimeHealthDecayHalfLifeMs   = 10 * 60 * 1000
	SiteRuntimeMinMultiplier           = 0.08
	SiteRuntimeLatencyBaselineMs       = 2500
	SiteRuntimeLatencyWindowMs         = 30000
	SiteRuntimeMaxLatencyPenalty       = 0.35
	SiteRuntimeLatencyEMAAlpha         = 0.3
	SiteRuntimeBreakerStreakThreshold  = 3
	SiteTransientStreakWindowMs        = 5 * 60 * 1000
	SiteRecentOutcomeHalfLifeMs        = 30 * 60 * 1000
	SiteRecentSuccessConfidenceSamples = 12
	SiteRecentSuccessPriorSuccesses    = 1
	SiteRecentSuccessPriorFailures     = 1
	SiteRecentSuccessFallbackRate      = 0.5
	SiteRecentModelWeight              = 0.65

	SiteHistoricalHealthMinMultiplier = 0.45
	SiteHistoricalHealthMaxSample     = 24
	SiteHistoricalLatencyBaselineMs   = 2000
	SiteHistoricalLatencyWindowMs     = 20000
	SiteHistoricalMaxLatencyPenalty   = 0.18

	SiteRuntimeHealthSettingKey        = "token_router_site_runtime_health_v1"
	SiteRuntimeHealthPersistDebounceMs = 500
	SiteRuntimeHealthPersistStaleTTLMs = 7 * 24 * 60 * 60 * 1000
	SiteRuntimeHealthPersistIdleTTLMs  = 12 * 60 * 60 * 1000
	SiteRuntimeHealthPersistMinPenalty = 0.02

	StableFirstPrimarySuccessRateRatio    = 0.92
	StableFirstTrustedRecentConfidence    = 0.5
	StableFirstTrustedHistoricalCalls     = 8
	StableFirstObservationRequestInterval = 24
	StableFirstObservationSiteCooldownMs  = 30 * 60 * 1000
)
View Source
const (
	MaxStableFirstRotationKeys                = 1024
	MaxStableFirstObservationProgressKeys     = 1024
	MaxStableFirstObservationSiteCooldownKeys = 4096
)
View Source
const SiteRuntimeHalfOpenProbeTimeoutMs = 10 * 60 * 1000

SiteRuntimeHalfOpenProbeTimeoutMs bounds the half-open probe window. If the admitted recovery probe never records an outcome (process restart, dropped request), the breaker releases back to the expired state so the next request retries the probe instead of leaving the site isolated forever. Upstream HTTP timeouts are far below this bound, so live probes resolve long before it.

View Source
const StableFirstSiteScoreRatio = 0.92

Variables

View Source
var DefaultPriceCompareSampleUsage = UsageForCost{
	PromptTokens:     1000,
	CompletionTokens: 1000,
	TotalTokens:      2000,
}

DefaultPriceCompareSampleUsage is the sample window used for estimatedCostSample when the operator does not supply custom usage (1k in + 1k out).

View Source
var EmptyDownstreamRoutingPolicy = DownstreamRoutingPolicy{
	SiteWeightMultipliers: map[int64]float64{},
}

EmptyDownstreamRoutingPolicy is the default allow-all policy.

KnownRouteRoutingStrategies lists operator-selectable strategies.

View Source
var RoundRobinCooldownLevelsSec = []int64{0, 10 * 60, 60 * 60, 24 * 60 * 60}

RoundRobinCooldownLevelsSec defines tiered cooldown for round-robin: [0s, 10min, 1h, 24h].

View Source
var SiteRuntimeBreakerLevelsMs = []int64{0, 60_000, 5 * 60_000, 30 * 60 * 1000}

SiteRuntimeBreakerLevelsMs defines breaker durations: [0ms, 60s, 5min, 30min].

Functions

func ApplyFibonacciCooldown

func ApplyFibonacciCooldown(failCount int64, nowMs int64, configuredMaxSec int) (cooldownUntilISO *string)

ApplyFibonacciCooldown applies Fibonacci backoff cooldown.

func ApplyRoundRobinCooldown

func ApplyRoundRobinCooldown(
	consecutiveFailCount int64,
	cooldownLevel int64,
	nowMs int64,
	configuredMaxSec int,
) (nextConsecutiveFailCount int64, nextCooldownLevel int64, cooldownUntilISO *string)

ApplyRoundRobinCooldown applies tiered cooldown to a failure-aware struct. Callers must pass the raw consecutiveFailCount (no pre-increment); this helper alone does +1. If the post-increment count reaches RoundRobinFailureThreshold, increments cooldownLevel and resets count. Returns the updated values and cooldownUntil ISO string.

func BuildSiteHistoricalHealthMetrics

func BuildSiteHistoricalHealthMetrics(candidates []RouteChannelCandidate) map[int64]SiteHistoricalHealthMetrics

BuildSiteHistoricalHealthMetrics aggregates historical health per site.

func BuildStableFirstRotationKey

func BuildStableFirstRotationKey(routeID int64, requestedModel string) string

BuildStableFirstRotationKey creates a rotation key from route ID and model.

func CacheAwarePerMillionRates

func CacheAwarePerMillionRates(model PricingModel, groupMultiplier float64) (input, output, cacheRead, cacheCreation float64)

CacheAwarePerMillionRates derives input/output/cache $/M rates for catalog display and routing reference helpers. Uses Claude-aware cache defaults.

func CalculateModelUsageCost

func CalculateModelUsageCost(
	model PricingModel,
	usage UsageForCost,
	groupRatio map[string]float64,
) float64

CalculateModelUsageCost returns the estimated cost for a model + usage.

func ChannelRuntimeStatus added in v0.11.0

func ChannelRuntimeStatus(siteID int64, modelName string, enabled bool, cooldownUntil *string) string

ChannelRuntimeStatus classifies a channel's current routing state by overlaying the in-memory site/model runtime breaker and the persisted cooldown window on top of the channel's enabled flag. It is intentionally read-only: it never mutates routing state, so callers can render the status without hard-disabling (soft isolation only).

func ChannelSupportsRequestedModel

func ChannelSupportsRequestedModel(channelSourceModel *string, requestedModel string) bool

ChannelSupportsRequestedModel checks if a channel's source model supports the requested model.

func ChannelSupportsRequestedModelWithRedirects

func ChannelSupportsRequestedModelWithRedirects(channelSourceModel *string, requestedModel string, accountID int64) bool

ChannelSupportsRequestedModelWithRedirects is the K1b variant: besides the base checks it consults the in-process redirect registry, so a channel whose source_model is an upstream `actual` name (e.g. claude-3-5-sonnet-20241022) becomes eligible for a request of its `canonical` (claude-3-5-sonnet) on the same account. Pure function over the registry; no DB access.

func ClampFailureCooldownMs

func ClampFailureCooldownMs(cooldownMs int64, configuredMaxSec int) int64

ClampFailureCooldownMs clamps a cooldown duration to the configured maximum.

func ClampInt

func ClampInt(value, lo, hi int) int

ClampInt clamps an int to [lo, hi].

func ClampNumber

func ClampNumber(value, lo, hi float64) float64

ClampNumber clamps a float64 to [lo, hi].

func ClearRuntimeHealthStatesForChannels

func ClearRuntimeHealthStatesForChannels(rows []ChannelRuntimeHealthRow) bool

ClearRuntimeHealthStatesForChannels clears the in-memory runtime health state for the site+model combinations of the given channel rows. Returns true if any state was cleared and persistence should be triggered.

func ClearStableFirstCachesForRoute

func ClearStableFirstCachesForRoute(routeID int64)

ClearStableFirstCachesForRoute clears rotation/progress/cooldown for a route.

func CompareNullableTimeAsc

func CompareNullableTimeAsc(left, right *string) int

CompareNullableTimeAsc compares two nullable ISO timestamps ascending.

func CompareNullableTimeDesc

func CompareNullableTimeDesc(left, right *string) int

CompareNullableTimeDesc compares two nullable ISO timestamps descending.

func DefaultCacheCreationRatioForModel

func DefaultCacheCreationRatioForModel(modelName string) float64

DefaultCacheCreationRatioForModel returns the intentional cache_creation_ratio fallback when the field is missing.

func DefaultCacheRatioForModel

func DefaultCacheRatioForModel(modelName string) float64

DefaultCacheRatioForModel returns the intentional cache_ratio fallback when an upstream pricing row omits the field. Claude models use Anthropic public ratios; everything else keeps the historical Metapi 1.0 fallback. Both are admin-overridable via SetCacheRatioDefaults.

func EnsureSiteRuntimeHealthStateLoaded

func EnsureSiteRuntimeHealthStateLoaded() error

EnsureSiteRuntimeHealthStateLoaded lazy-loads health state from settings.

func EstimateProxyCostFromModel

func EstimateProxyCostFromModel(model PricingModel, usage UsageForCost, groupRatio map[string]float64) float64

EstimateProxyCostFromModel is a pure cost estimate given an already-resolved pricing model (catalog row or self-log override). Prefer this over inventing prices when the catalog is unavailable — callers should use FallbackTokenCost.

func EstimateRequestContextTokens

func EstimateRequestContextTokens(body map[string]any) int64

EstimateRequestContextTokens is a best-effort chars/4 estimate of inbound context from a parsed request body. Prefers messages/input string leaves; optionally adds max_tokens / max_output_tokens when parseable. Returns 0 when no reliable signal exists (caller must not invent tiers).

func FallbackTokenCost

func FallbackTokenCost(totalTokens int64, platform string) float64

FallbackTokenCost is the last-resort estimate when no pricing catalog is available. Mirrors TS fallbackTokenCost (veloera uses 1e6 divisor, others 5e5).

func FibonacciNumber

func FibonacciNumber(index int64) int64

FibonacciNumber returns the nth Fibonacci number (1-indexed: fib(1)=1, fib(2)=1, fib(3)=2,...).

func FilterRecentlyFailedCandidates

func FilterRecentlyFailedCandidates[T any](
	candidates []T,
	getFailInfo func(T) (failCount *int64, lastFailAt *string),
	nowMs int64,
	configuredMaxSec int,
) []T

FilterRecentlyFailedCandidates filters a list of candidates to those not recently failed. If all are recently failed, returns all candidates.

func FlushSiteRuntimeHealthPersistence

func FlushSiteRuntimeHealthPersistence()

FlushSiteRuntimeHealthPersistence flushes any pending persistence immediately.

func GetExposedModelNameForRoute

func GetExposedModelNameForRoute(displayName *string, modelPattern string) string

GetExposedModelNameForRoute returns the display name or model pattern.

func GetRuntimeHealthMultiplier

func GetRuntimeHealthMultiplier(state *SiteRuntimeHealthState) float64

GetRuntimeHealthMultiplier returns the health multiplier for a state.

func GetSiteRuntimeHealthMultiplier

func GetSiteRuntimeHealthMultiplier(siteID int64) float64

GetSiteRuntimeHealthMultiplier is a convenience wrapper.

func HasCustomDisplayName

func HasCustomDisplayName(modelPattern string, displayName *string) bool

HasCustomDisplayName checks if a route has a non-default display name.

func InvalidateCache

func InvalidateCache()

InvalidateCache invalidates the global route cache. Safe to call even if the cache has not been initialized (no-op).

func IsChannelRecentlyFailed

func IsChannelRecentlyFailed(failCount *int64, lastFailAt *string, nowMs int64, configuredMaxSec int) bool

IsChannelRecentlyFailed checks if a channel failed recently within the backoff window.

func IsClaudeModel

func IsClaudeModel(modelName string) bool

IsClaudeModel reports whether modelName belongs to the Claude / Anthropic family. Matching is case-insensitive substring on "claude".

func IsContributionCloseToBest

func IsContributionCloseToBest(value, bestValue, ratio float64) bool

IsContributionCloseToBest checks if a value is within ratio of best.

func IsCooldownActive

func IsCooldownActive(cooldownUntil *string, nowISO string) bool

IsCooldownActive reports whether cooldownUntil is still in the future relative to nowISO. Both timestamps are parsed to milliseconds before comparison so millis-bearing writer formats (formatUnixMillisISO) cannot lose to second-precision RFC3339 nowISO via lexical order. Example bug: "…T15:04:05.500Z" > "…T15:04:05Z" is false as strings ('.' < 'Z') but true by time.

func IsExactRouteModelPattern

func IsExactRouteModelPattern(pattern string) bool

IsExactRouteModelPattern returns true if the pattern is an exact model name (no wildcards, no "re:" prefix).

func IsExplicitGroupRoute

func IsExplicitGroupRoute(routeMode string) bool

IsExplicitGroupRoute checks if a route is an explicit_group route.

func IsExplicitTokenChannel

func IsExplicitTokenChannel(candidate RouteChannelCandidate) bool

IsExplicitTokenChannel checks if a channel is associated with a specific account token.

func IsModelAliasEquivalent

func IsModelAliasEquivalent(left, right string) bool

IsModelAliasEquivalent checks if two model names are equivalent after alias normalization.

func IsModelAllowedByDownstreamPolicy

func IsModelAllowedByDownstreamPolicy(requestedModel string, policy DownstreamRoutingPolicy) bool

IsModelAllowedByDownstreamPolicy checks whether a model is allowed by the downstream routing policy.

func IsOAuthRouteUnitCandidate

func IsOAuthRouteUnitCandidate(candidate RouteChannelCandidate) bool

IsOAuthRouteUnitCandidate checks if a channel references an OAuth route unit.

func IsRegexModelPattern

func IsRegexModelPattern(pattern string) bool

IsRegexModelPattern returns true if the pattern is a regex pattern (starts with "re:").

func IsRouteDisplayNameMatch

func IsRouteDisplayNameMatch(model string, displayName *string) bool

IsRouteDisplayNameMatch checks if a model matches a route's display name exactly.

func IsSiteRuntimeBreakerOpen

func IsSiteRuntimeBreakerOpen(siteID int64) bool

IsSiteRuntimeBreakerOpen checks if a site's global breaker is open.

func IsTransientSiteRuntimeFailure

func IsTransientSiteRuntimeFailure(ctx SiteRuntimeFailureContext) bool

IsTransientSiteRuntimeFailure checks if a failure is transient.

func IsUsageLimitRateLimitFailure

func IsUsageLimitRateLimitFailure(ctx SiteRuntimeFailureContext) bool

IsUsageLimitRateLimitFailure checks if a 429 is from a usage/rate limit.

func MatchesModelPattern

func MatchesModelPattern(model, pattern string) bool

MatchesModelPattern checks whether a model string matches a pattern (exact, glob, or regex).

func ModelRedirectActual

func ModelRedirectActual(accountID int64, canonical string) string

ModelRedirectActual returns the actual (upstream) name for a canonical model on a given account, or "" when no redirect applies. Hot path, no locks held after the read.

func ModelRedirectCanonical

func ModelRedirectCanonical(accountID int64, actual string) string

ModelRedirectCanonical returns the canonical name for an actual (upstream) model on a given account, or "" when no redirect applies. Used by eligibility: a channel exposing `actual` supports a request for `canonical`.

func NormalizeChannelSourceModel

func NormalizeChannelSourceModel(channelSourceModel *string) string

NormalizeChannelSourceModel trims whitespace from a channel source model.

func NormalizeModelAlias

func NormalizeModelAlias(modelName string) string

NormalizeModelAlias strips the vendor prefix and lowercases. E.g. "anthropic/claude-sonnet" → "claude-sonnet"

func NormalizePricingRatio

func NormalizePricingRatio(value any, modelName, kind string, fallback float64) float64

NormalizePricingRatio normalizes a raw ratio from an upstream pricing JSON field. Missing/NaN/negative values fall back using the model-family default selected by kind ("cache" | "cache_creation" | other→fallback).

func NormalizeRouteDisplayName

func NormalizeRouteDisplayName(displayName *string) string

NormalizeRouteDisplayName trims whitespace from a display name.

func ParseISOTimeMs

func ParseISOTimeMs(value *string) *int64

ParseISOTimeMs parses an ISO timestamp to Unix milliseconds.

func ParseModelMappingRecord

func ParseModelMappingRecord(raw *string) map[string]string

ParseModelMappingRecord parses a model mapping JSON string into a map.

func ParseRegexModelPattern

func ParseRegexModelPattern(pattern string) *regexp.Regexp

ParseRegexModelPattern parses a "re:..." pattern into a compiled regexp. Compiled bodies are cached process-wide (regexCompileCache), so repeated calls with the same pattern reuse one compiled, goroutine-safe instance.

func PickContextTierRoute

func PickContextTierRoute(routes []store.TokenRoute, requestedTokens int64) *store.TokenRoute

PickContextTierRoute selects among same-priority model matches by context ceiling. requestedTokens must be >0; otherwise the first route is returned unchanged (first-match honesty).

Rules: 1. Among routes with positive context_length >= requestedTokens, pick the **smallest** ceiling (tightest fit). 2. Else if any positive context_length exists, pick the **largest** ceiling (best available still short of estimate). 3. Else prefer unsized (NULL/≤0) catch-all routes (first by id). 4. Empty input → nil.

func RecordSiteProbeOutcome

func RecordSiteProbeOutcome(siteID int64, status string, latencyMs float64, modelName *string, channelID *int64, errText *string)

RecordSiteProbeOutcome stamps the last background probe result on site health without treating the event as user traffic. Success/failure still go through the normal runtime health counters via RecordSiteRuntime* helpers.

func RecordSiteRuntimeFailure

func RecordSiteRuntimeFailure(siteID int64, ctx SiteRuntimeFailureContext)

RecordSiteRuntimeFailure records a failure against a site and model.

func RecordSiteRuntimeSuccess

func RecordSiteRuntimeSuccess(siteID int64, latencyMs float64, modelName *string, firstByteMs ...float64)

RecordSiteRuntimeSuccess records a success against a site and model.

func ResetSiteRuntimeHealthState

func ResetSiteRuntimeHealthState()

ResetSiteRuntimeHealthState clears all in-memory runtime health state.

func ResolveActualModelForSelectedChannel

func ResolveActualModelForSelectedChannel(
	requestedModel string,
	routeDisplayName *string,
	mappedModel string,
	channelSourceModel *string,
	accountID int64,
) string

ResolveActualModelForSelectedChannel resolves the actual model to forward. Resolution order (first match wins): 1. display-name hit → the channel's own source model (existing behavior); 2. K1b: per-account redirect (canonical → actual) when no route-level model mapping already rewrote the name — the upstream only knows the dated/versioned actual name; 3. route-level model mapping (existing fallback).

func ResolveCacheCreationRatio

func ResolveCacheCreationRatio(modelName string, cacheCreationRatio *float64) float64

ResolveCacheCreationRatio picks an explicit creation ratio when present, otherwise the model-family default. Explicit 0 is preserved.

func ResolveCacheRatio

func ResolveCacheRatio(modelName string, cacheRatio *float64) float64

ResolveCacheRatio picks an explicit ratio when present and finite (>= 0), otherwise the model-family default. Explicit 0 is preserved (free cache read).

func ResolveChannelRuntimeLoadMultiplier

func ResolveChannelRuntimeLoadMultiplier(snapshot ChannelLoadSnapshot) float64

ResolveChannelRuntimeLoadMultiplier converts a load snapshot to a multiplier.

func ResolveConfiguredFailureCooldownMaxMs

func ResolveConfiguredFailureCooldownMaxMs(configuredMaxSec int) int64

ResolveConfiguredFailureCooldownMaxMs returns the configured max cooldown in ms.

func ResolveEffectiveFailureCooldownMs

func ResolveEffectiveFailureCooldownMs(failCount *int64, configuredMaxSec int) int64

ResolveEffectiveFailureCooldownMs computes the full effective cooldown with clamping.

func ResolveFailureBackoffSec

func ResolveFailureBackoffSec(failCount *int64) int64

ResolveFailureBackoffSec computes Fibonacci backoff: 15 * fib(failCount). failCount=1 → 15s, failCount=2 → 15s, failCount=3 → 30s, etc.

func ResolveMappedModel

func ResolveMappedModel(requestedModel string, modelMapping *string) string

ResolveMappedModel resolves the target model name from a model mapping.

func ResolveRoundRobinCooldownSec

func ResolveRoundRobinCooldownSec(level int) int64

ResolveRoundRobinCooldownSec returns the cooldown duration for a given level.

func ResolveRouteUnitMemberTokenValue

func ResolveRouteUnitMemberTokenValue(account store.Account) string

ResolveRouteUnitMemberTokenValue extracts the token value from a member.

func ResolveSiteRuntimeFailurePenalty

func ResolveSiteRuntimeFailurePenalty(ctx SiteRuntimeFailureContext) float64

ResolveSiteRuntimeFailurePenalty assigns a penalty score based on failure context.

func ResolveStableFirstSuccessRate

func ResolveStableFirstSuccessRate(details SiteRuntimeHealthDetails, historicalSuccessRate *float64) float64

ResolveStableFirstSuccessRate blends recent runtime success rate with historical rate.

func SetCacheRatioDefaults

func SetCacheRatioDefaults(defaultRatio, defaultCreation, claudeRatio, claudeCreation float64)

SetCacheRatioDefaults overrides the cache-ratio fallbacks at runtime. Any value <= 0, NaN, or Inf resets that ratio to its code default. Called by the admin settings handler when cache_ratio_* settings change.

func SetGlobalCache

func SetGlobalCache(c *RouteCache)

SetGlobalCache sets the global route cache. Called once during router initialization.

func SetHealthSettingsStore

func SetHealthSettingsStore(store SettingsStore)

SetHealthSettingsStore sets the settings store for health persistence.

func SetModelRedirects

func SetModelRedirects(byAccount map[int64]map[string]string)

SetModelRedirects atomically replaces the whole registry. Pass nil to clear. Each account's map is canonical→actual; the reverse index is derived here so callers never pass inconsistent data.

func ShouldUseStableFirstObservationCandidate

func ShouldUseStableFirstObservationCandidate(rotationKey string, observationCandidates []RouteChannelCandidate) bool

ShouldUseStableFirstObservationCandidate checks if it's time to probe observation pool.

func TryAdmitSiteModelRuntimeRequest added in v0.14.0

func TryAdmitSiteModelRuntimeRequest(siteID int64, modelName string) bool

TryAdmitSiteModelRuntimeRequest gates one dispatch decision through the three-state recovery semantics for (site, model), mirroring the octopus circuit breaker (internal/relay/balancer/circuit.go):

  • open (cooldown not elapsed): reject — matches octopus StateOpen.
  • half-open (cooldown elapsed, single recovery probe in flight): reject — matches octopus StateHalfOpen.
  • expired (cooldown elapsed, no probe granted yet): this request becomes the recovery probe; the states are marked half-open and the request is admitted. Exactly one probe passes; the rest keep being rejected until the probe outcome is recorded or the probe window times out.
  • closed: admit normally.

Note the gate hard-rejects open breakers, so the pre-existing fail-open starvation guard (single-candidate short-circuit / all-broken full-set pool in the filter layer) no longer dispatches against hard-open sites: open now means no traffic until the cooldown expires and the probe recovers the breaker. This is the deliberate three-state semantic change.

func UpdateStableFirstObservationProgress

func UpdateStableFirstObservationProgress(rotationKey string, usedObservation bool, selectedSiteID int64)

UpdateStableFirstObservationProgress updates observation progress after a selection. The full read-modify-write of progress (and optional cooldown) is held under a single exclusive lock to avoid TOCTOU races on the shared maps.

Types

type CatalogPricingResolver added in v0.14.0

type CatalogPricingResolver interface {
	// ResolveCatalogPricing returns the catalog unit cost for a model on a
	// site/account plus its provenance. (nil, "") declines the query, in
	// which case EffectiveUnitCost falls through to the fallback cost.
	ResolveCatalogPricing(siteID, accountID int64, modelName string) (unitCost *float64, source string)
}

CatalogPricingResolver supplies catalog unit costs for cold-start routing (no history, no configured unit_cost yet). Implementations must label relay-site estimates CatalogSourceRelayEstimate instead of presenting an official list price as a real relay price.

type ChannelLoadParams

type ChannelLoadParams struct {
	ChannelID            int64
	AccountExtraConfig   *string
	AccountOAuthProvider *string
}

ChannelLoadParams are the parameters for resolving a channel's load snapshot.

type ChannelLoadSnapshot

type ChannelLoadSnapshot struct {
	SessionScoped    bool
	ConcurrencyLimit int
	ActiveLeaseCount int
	WaitingCount     int
	Saturated        bool
}

ChannelLoadSnapshot is a snapshot of a channel's concurrency load.

type ChannelLoadSnapshotProvider

type ChannelLoadSnapshotProvider interface {
	GetChannelLoadSnapshot(params ChannelLoadParams) ChannelLoadSnapshot
}

ChannelLoadSnapshotProvider supplies per-channel concurrency load snapshots.

type ChannelRuntimeHealthRow

type ChannelRuntimeHealthRow struct {
	SiteID            int64
	SourceModel       *string
	RouteModelPattern string
}

ChannelRuntimeHealthRow describes a channel-row pair for health clearing.

type ChannelSelector

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

ChannelSelector implements selectChannel, selectNextChannel, selectPreferredChannel.

func NewChannelSelector

func NewChannelSelector(
	db ChannelSelectorDB,
	cache *RouteCache,
	configuredMaxSec int,
	routingWeights RoutingWeightsConfig,
	pricingFn CatalogPricingResolver,
	fallbackUnitCost float64,
	channelLoadProvider ChannelLoadSnapshotProvider,
) *ChannelSelector

NewChannelSelector creates a new ChannelSelector.

func (*ChannelSelector) SelectChannel

func (s *ChannelSelector) SelectChannel(ctx context.Context, requestedModel string, policy DownstreamRoutingPolicy) (*SelectedChannel, error)

SelectChannel finds a matching route and selects the best channel.

func (*ChannelSelector) SelectNextChannel

func (s *ChannelSelector) SelectNextChannel(ctx context.Context, requestedModel string, excludeChannelIDs []int64, policy DownstreamRoutingPolicy) (*SelectedChannel, error)

SelectNextChannel selects a channel excluding already-tried channels.

func (*ChannelSelector) SelectPreferredChannel

func (s *ChannelSelector) SelectPreferredChannel(
	ctx context.Context,
	requestedModel string,
	preferredChannelID int64,
	policy DownstreamRoutingPolicy,
	excludeChannelIDs []int64,
) (*SelectedChannel, error)

SelectPreferredChannel selects a specific preferred channel if eligible.

type ChannelSelectorDB

type ChannelSelectorDB interface {
	// Route operations
	LoadEnabledRoutes(ctx context.Context) ([]store.TokenRoute, error)
	LoadRouteGroupSources(ctx context.Context, groupRouteIDs []int64) (map[int64][]int64, error)

	// Channel operations
	LoadRouteChannels(ctx context.Context, routeIDs []int64) ([]struct {
		Channel store.RouteChannel
		Account store.Account
		Site    store.Site
		Token   *store.AccountToken
	}, error)

	// OAuth route unit operations
	LoadOAuthRouteUnitSummaries(ctx context.Context, unitIDs []int64) (map[int64]OAuthRouteUnitSummary, error)
	LoadOAuthRouteUnitMembers(ctx context.Context, unitIDs []int64) (map[int64][]OAuthRouteUnitMemberCandidate, error)

	// Channel mutation
	UpdateChannelLastSelectedAt(ctx context.Context, channelID int64, lastSelectedAt string) error
	UpdateRouteUnitMemberLastSelectedAt(ctx context.Context, unitID, accountID int64, lastSelectedAt string) error

	// Route unit member routes
	FindRouteIDsByOAuthRouteUnitID(ctx context.Context, unitID int64) ([]int64, error)

	// Load credential-scoped channel IDs
	LoadCredentialScopedChannelIDs(ctx context.Context, channel store.RouteChannel, accountID int64) ([]int64, error)

	// Load channel by ID with joins
	LoadChannelWithAccount(ctx context.Context, channelID int64) (*struct {
		Channel store.RouteChannel
		Account store.Account
	}, error)

	LoadChannelWithAccountAndRoute(ctx context.Context, channelID int64) (*struct {
		Channel store.RouteChannel
		Account store.Account
		Route   store.TokenRoute
	}, error)

	// Batch updates
	UpdateChannelCooldownFields(ctx context.Context, channelIDs []int64, updates map[string]interface{}) error
	UpdateChannelSuccessFields(ctx context.Context, channelID int64, updates map[string]interface{}) error

	// Route unit member updates
	UpdateRouteUnitMemberCooldownFields(ctx context.Context, memberID int64, updates map[string]interface{}) error
	UpdateRouteUnitMemberSuccessFields(ctx context.Context, memberID int64, updates map[string]interface{}) error

	// Load member with account+unit
	LoadRouteUnitMemberWithAccount(ctx context.Context, unitID, accountID int64) (*struct {
		Member  store.OAuthRouteUnitMember
		Account store.Account
		Unit    store.OAuthRouteUnit
	}, error)

	// Find all routes
	FindAllEnabledRoutes(ctx context.Context) ([]store.TokenRoute, error)

	// Credential scoping
	LoadChannelsByTokenID(ctx context.Context, tokenID int64) ([]store.RouteChannel, error)
	LoadChannelsByAccountIDWithoutToken(ctx context.Context, accountID int64) ([]store.RouteChannel, error)

	// Runtime health
	LoadRuntimeHealthChannelRows(ctx context.Context, channelIDs []int64) ([]struct {
		SiteID            int64
		SourceModel       *string
		RouteModelPattern string
	}, error)

	// Clear channel failure states
	ClearChannelFailureStates(ctx context.Context, channelIDs []int64) error
}

ChannelSelectorDB defines the DB operations needed by the selector.

type CostSignal

type CostSignal struct {
	UnitCost float64
	Source   string // "observed", "configured", "catalog", "catalog_estimate", "fallback"
}

CostSignal describes the unit cost and its provenance.

func EffectiveUnitCost

func EffectiveUnitCost(candidate RouteChannelCandidate, modelName string, pricingFn CatalogPricingResolver, fallbackUnitCost float64) CostSignal

EffectiveUnitCost resolves the best available unit cost for a candidate.

type CredentialRef

type CredentialRef struct {
	Kind      string `json:"kind"` // "account_token" or empty
	TokenID   int64  `json:"tokenId"`
	AccountID int64  `json:"accountId"`
	SiteID    int64  `json:"siteId"`
}

CredentialRef identifies a specific credential to exclude.

type DecisionDB

type DecisionDB interface {
	FindAllEnabledRoutes(ctx context.Context) ([]store.TokenRoute, error)
	UpdateRouteDecisionSnapshot(ctx context.Context, routeID int64, snapshot string, refreshedAt string) error
	ClearRouteDecisionSnapshot(ctx context.Context, routeID int64) error
	ClearRouteDecisionSnapshots(ctx context.Context, routeIDs []int64) error
	ClearAllRouteDecisionSnapshots(ctx context.Context) error
}

DecisionDB defines the DB operations for decision snapshots. FindAllEnabledRoutes reuses the TokenRoute shape so the same store adapter that backs TokenRouter can also back snapshot refresh.

type DownstreamRoutingPolicy

type DownstreamRoutingPolicy struct {
	ExcludedSiteIDs        []int64
	ExcludedCredentialRefs []CredentialRef
	// AllowedSiteIDs / AllowedCredentialRefs: optional allow-lists.
	// Empty = unrestricted; non-empty = only listed sites/credentials eligible.
	AllowedSiteIDs        []int64
	AllowedCredentialRefs []CredentialRef
	AllowedRouteIDs       []int64
	SupportedModels       []string
	DenyAllWhenEmpty      bool
	SiteWeightMultipliers map[int64]float64
	// KeyWeight multiplies channel.Weight in weighted selection.
	// 0 or negative is treated as 1.0 (no-op).
	KeyWeight float64
	// RequestedContextTokens is a best-effort inbound context estimate for
	// multi-tier route pick. 0 means unknown → first-match honesty.
	RequestedContextTokens int64
}

DownstreamRoutingPolicy mirrors TS DownstreamRoutingPolicy.

type ModelInfo

type ModelInfo struct {
	ModelName string
	Available bool
	LatencyMs *int64
}

ModelInfo is a lightweight model availability record.

type ModelPrice

type ModelPrice struct {
	// Flat is set for scalar model_price values.
	Flat *float64
	// Input/Output are set for object model_price values (one-hub times).
	Input  float64
	Output float64
	IsPair bool
}

ModelPrice is either a flat per-call price or input/output pair.

type ModelProvider

type ModelProvider interface {
	GetAvailableModels(ctx context.Context, accountID int64) ([]ModelInfo, error)
	RefreshModelsForAccount(ctx context.Context, accountID int64) error
}

ModelProvider supplies model availability data.

type OAuthRouteUnitMemberCandidate

type OAuthRouteUnitMemberCandidate struct {
	Member  store.OAuthRouteUnitMember
	Account store.Account
	Site    store.Site
}

OAuthRouteUnitMemberCandidate is a member candidate with account and site info.

func SelectRouteUnitMember

func SelectRouteUnitMember(
	outerCandidate RouteChannelCandidate,
	requestedModel string,
	nowISO string,
	nowMs int64,
	configuredMaxSec int,
	excludeChannelIDs []int64,
) *OAuthRouteUnitMemberCandidate

SelectRouteUnitMember selects a member from an OAuth route unit channel. Implements both round_robin and stick_until_unavailable strategies.

type OAuthRouteUnitSummary

type OAuthRouteUnitSummary struct {
	ID       int64
	SiteID   int64
	Provider string
	Name     string
	Strategy string
	Enabled  bool
}

OAuthRouteUnitSummary is a light summary of an OAuth route unit.

type PriceCompareInput

type PriceCompareInput struct {
	SiteID    int64
	SiteName  string
	Platform  string
	Model     string
	AccountID int64
	Username  string

	// ObservedAvgCost is AVG(estimated_cost) over successful proxy logs.
	ObservedAvgCost *float64
	ObservedSamples int

	// ConfiguredUnitCost is accounts.unit_cost when set by the operator.
	ConfiguredUnitCost *float64

	// Optional rates recovered from billing_details breakdown.
	InputPerMillion  *float64
	OutputPerMillion *float64

	// Optional ratios recovered from billing_details pricing section.
	ModelRatio      *float64
	CompletionRatio *float64
	GroupRatio      *float64
}

PriceCompareInput is one site/account/model candidate for aggregation. Pointers distinguish missing values from explicit zeros.

type PriceCompareRow

type PriceCompareRow struct {
	SiteID              int64    `json:"siteId"`
	SiteName            string   `json:"siteName"`
	Platform            string   `json:"platform"`
	Model               string   `json:"model"`
	AccountID           int64    `json:"accountId"`
	Username            string   `json:"username,omitempty"`
	InputPerMillion     float64  `json:"inputPerMillion"`
	OutputPerMillion    float64  `json:"outputPerMillion"`
	Source              string   `json:"source"`
	RatesSource         string   `json:"ratesSource"`
	EstimatedCostSample float64  `json:"estimatedCostSample"`
	ObservedSamples     int      `json:"observedSamples,omitempty"`
	ConfiguredUnitCost  *float64 `json:"configuredUnitCost,omitempty"`
	MissingPrice        bool     `json:"missingPrice"`
	Recommended         bool     `json:"recommended"`
}

PriceCompareRow is one cross-site effective price candidate for admin UX.

func AggregatePriceCompareRows

func AggregatePriceCompareRows(rows []PriceCompareRow) []PriceCompareRow

AggregatePriceCompareRows sorts cheaper first, then by site name / account id. Rows with missingPrice sort after priced rows with the same cost.

func BuildPriceCompareRow

func BuildPriceCompareRow(in PriceCompareInput, sample UsageForCost) PriceCompareRow

BuildPriceCompareRow resolves effective rates + sample cost without inventing unlabeled prices. Provenance priority for estimatedCostSample:

1. billing_details rates/ratios → source=billing_details 2. observed avg estimated_cost → source=observed 3. configured account unit_cost → source=configured 4. platform FallbackTokenCost + default ratios → source=fallback

Per-million rates prefer explicit billing rates, then derived ratios, then CacheAwarePerMillionRates defaults (ratesSource=fallback).

type PricingModel

type PricingModel struct {
	ModelName          string
	QuotaType          int // 0 = token-based, 1 = per-call
	ModelRatio         float64
	CompletionRatio    float64
	CacheRatio         *float64
	CacheCreationRatio *float64
	ModelPrice         *ModelPrice
	EnableGroups       []string
}

PricingModel is a normalized upstream pricing row used for cost estimation. Pointer ratios distinguish "missing" from an explicit zero.

func BuildPricingOverrideModel

func BuildPricingOverrideModel(modelName string, override ProxyBillingPricingOverride) (PricingModel, map[string]float64)

BuildPricingOverrideModel builds a token-quota PricingModel from self-log billing metadata. Missing Claude cache ratios receive Anthropic defaults.

type PricingProvider

type PricingProvider interface {
	GetReferenceCost(ctx context.Context, model string, siteID int64, accountID int64) (float64, error)
	RefreshModelPricingCatalog(ctx context.Context, site store.Site, account store.Account, modelName string) error
}

PricingProvider supplies model pricing reference costs.

type PricingReference

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

PricingReference provides model pricing cost resolution.

func NewPricingReference

func NewPricingReference(provider PricingProvider) *PricingReference

NewPricingReference creates a new PricingReference.

func (*PricingReference) GetCachedModelRoutingReferenceCost

func (p *PricingReference) GetCachedModelRoutingReferenceCost(ctx context.Context, siteID, accountID int64, modelName string) *float64

GetCachedModelRoutingReferenceCost returns the cached routing reference cost.

func (*PricingReference) RefreshPricingReferenceCostsForMatch

func (p *PricingReference) RefreshPricingReferenceCostsForMatch(
	ctx context.Context,
	match *RouteMatch,
	requestedModel string,
	options PricingReferenceRefreshOptions,
) error

RefreshPricingReferenceCostsForMatch asynchronously refreshes pricing for all candidates.

type PricingReferenceRefreshOptions

type PricingReferenceRefreshOptions struct {
	UseChannelSourceModelForCost bool
	DownstreamPolicy             DownstreamRoutingPolicy
	RefreshedKeys                *map[string]struct{}
}

PricingReferenceRefreshOptions configures pricing refresh behavior.

type ProbeStatus

type ProbeStatus struct {
	Status      string // success | failure | inconclusive | ""
	AtMs        int64
	LatencyMs   *float64
	ErrorText   *string
	ModelName   string
	ChannelID   *int64
	BreakerOpen bool
	Multiplier  float64
}

func GetSiteProbeStatus

func GetSiteProbeStatus(siteID int64) ProbeStatus

GetSiteProbeStatus returns the last background probe stamp for a site.

type ProxyBillingBreakdown

type ProxyBillingBreakdown struct {
	InputPerMillion         float64 `json:"inputPerMillion"`
	OutputPerMillion        float64 `json:"outputPerMillion"`
	CacheReadPerMillion     float64 `json:"cacheReadPerMillion"`
	CacheCreationPerMillion float64 `json:"cacheCreationPerMillion"`
	InputCost               float64 `json:"inputCost"`
	OutputCost              float64 `json:"outputCost"`
	CacheReadCost           float64 `json:"cacheReadCost"`
	CacheCreationCost       float64 `json:"cacheCreationCost"`
	TotalCost               float64 `json:"totalCost"`
}

ProxyBillingBreakdown is the money breakdown of billing details.

type ProxyBillingDetails

type ProxyBillingDetails struct {
	QuotaType int                   `json:"quotaType"`
	Usage     ProxyBillingUsage     `json:"usage"`
	Pricing   ProxyBillingPricing   `json:"pricing"`
	Breakdown ProxyBillingBreakdown `json:"breakdown"`
}

ProxyBillingDetails mirrors the TS ProxyBillingDetails shape (camelCase JSON).

func CalculateModelUsageBreakdown

func CalculateModelUsageBreakdown(
	model PricingModel,
	usage UsageForCost,
	groupRatio map[string]float64,
) *ProxyBillingDetails

CalculateModelUsageBreakdown computes token-based billing details. Returns nil for per-call quotaType (1), matching TS behavior.

func CalculateModelUsageFullPrice added in v0.14.0

func CalculateModelUsageFullPrice(
	model PricingModel,
	usage UsageForCost,
	groupRatio map[string]float64,
) *ProxyBillingDetails

CalculateModelUsageFullPrice bills the no-cache-detail tier: every input token at the input rate and every output token at the output rate, with no cache discount. Upstreams that report token usage without cache detail must not be discounted — octopus semantics (internal/relay/metrics.go): missing cache detail means nonCachedTokens = promptTokens, so the whole input side is billed at full input price. This tier sits between FallbackTokenCost (token-divisor estimate) and CalculateModelUsageBreakdown (cache-aware three-way split). Unit prices reuse the existing conversion (inputPerMillion = modelRatio × 2 × multiplier) via CacheAwarePerMillionRates instead of hardcoding new formulas. Returns nil for per-call quotaType (1), matching CalculateModelUsageBreakdown.

type ProxyBillingPricing

type ProxyBillingPricing struct {
	ModelRatio         float64 `json:"modelRatio"`
	CompletionRatio    float64 `json:"completionRatio"`
	CacheRatio         float64 `json:"cacheRatio"`
	CacheCreationRatio float64 `json:"cacheCreationRatio"`
	GroupRatio         float64 `json:"groupRatio"`
}

ProxyBillingPricing is the ratio section of billing details.

type ProxyBillingPricingOverride

type ProxyBillingPricingOverride struct {
	ModelRatio         float64
	CompletionRatio    float64
	CacheRatio         *float64
	CacheCreationRatio *float64
	GroupRatio         *float64
}

ProxyBillingPricingOverride supplies ratios from self-log metadata.

type ProxyBillingUsage

type ProxyBillingUsage struct {
	PromptTokens             int64 `json:"promptTokens"`
	CompletionTokens         int64 `json:"completionTokens"`
	TotalTokens              int64 `json:"totalTokens"`
	CacheReadTokens          int64 `json:"cacheReadTokens"`
	CacheCreationTokens      int64 `json:"cacheCreationTokens"`
	BillablePromptTokens     int64 `json:"billablePromptTokens"`
	PromptTokensIncludeCache *bool `json:"promptTokensIncludeCache"`
}

ProxyBillingUsage is the usage section of billing details.

type RecentOutcomeSnapshot

type RecentOutcomeSnapshot struct {
	SuccessCount float64
	FailureCount float64
	SampleCount  float64
	SuccessRate  float64
	Confidence   float64
}

RecentOutcomeSnapshot is a snapshot of recent success/failure counts.

type RouteCache

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

RouteCache caches the routes list and per-route matches with TTL. The selector serves both from cache on the hot path and falls back to the DB on miss/expiry. Cached matches are immutable snapshots: patching clones (see PatchCachedChannel), so lock-free readers never race the patcher.

func NewRouteCache

func NewRouteCache(ttlMs int64) *RouteCache

NewRouteCache creates a new route cache with the given TTL in milliseconds.

func (*RouteCache) GetMatch

func (c *RouteCache) GetMatch(routeID int64) *RouteMatch

GetMatch returns a cached route match if fresh.

func (*RouteCache) GetRoutes

func (c *RouteCache) GetRoutes() []store.TokenRoute

GetRoutes returns cached routes if fresh, nil otherwise.

func (*RouteCache) InvalidateAll

func (c *RouteCache) InvalidateAll()

InvalidateAll clears all caches.

func (*RouteCache) InvalidateRouteScopedCache

func (c *RouteCache) InvalidateRouteScopedCache(routeID int64)

InvalidateRouteScopedCache clears the cache for a specific route.

func (*RouteCache) IsRoutesFresh

func (c *RouteCache) IsRoutesFresh() bool

IsRoutesFresh checks if the routes list is still fresh.

func (*RouteCache) PatchCachedChannel

func (c *RouteCache) PatchCachedChannel(channelID int64, apply func(ch *store.RouteChannel))

PatchCachedChannel applies a mutation to a channel across all cached matches. Cached matches are treated as immutable snapshots: the mutation is applied to a clone that atomically replaces the cached entry, so goroutines holding a previously returned snapshot (GetMatch readers use the match outside the cache lock) keep reading consistent data instead of racing the patcher.

func (*RouteCache) SetMatch

func (c *RouteCache) SetMatch(routeID int64, match *RouteMatch)

SetMatch caches a route match.

func (*RouteCache) SetRoutes

func (c *RouteCache) SetRoutes(routes []store.TokenRoute)

SetRoutes sets the cached routes.

type RouteChannelCandidate

type RouteChannelCandidate struct {
	Channel          store.RouteChannel
	Account          store.Account
	Site             store.Site
	Token            *store.AccountToken
	RouteUnit        *OAuthRouteUnitSummary
	RouteUnitMembers []OAuthRouteUnitMemberCandidate
}

RouteChannelCandidate is a channel joined with account, site, token, and optional OAuth route unit.

func FilterSiteRuntimeBrokenCandidatesByModel

func FilterSiteRuntimeBrokenCandidatesByModel(
	candidates []RouteChannelCandidate,
	modelName string,
) (healthy []RouteChannelCandidate, avoided []struct {
	Candidate RouteChannelCandidate
	Reason    string
})

FilterSiteRuntimeBrokenCandidatesByModel filters by model-level breaker.

func FilterSiteRuntimeBrokenCandidatesByModelResolver

func FilterSiteRuntimeBrokenCandidatesByModelResolver(
	candidates []RouteChannelCandidate,
	resolveModel func(RouteChannelCandidate) string,
) (healthy []RouteChannelCandidate, avoided []struct {
	Candidate RouteChannelCandidate
	Reason    string
})

FilterSiteRuntimeBrokenCandidatesByModelResolver filters by model-level breaker, resolving the model name per-candidate via the provided function. This is needed for display-name-matched routes where each candidate may have a different source model.

func GetRoundRobinCandidates

func GetRoundRobinCandidates(candidates []RouteChannelCandidate) []RouteChannelCandidate

GetRoundRobinCandidates sorts candidates by lastSelectedAt || lastUsedAt ascending.

func SelectLeastBusyCandidate

func SelectLeastBusyCandidate(
	candidates []RouteChannelCandidate,
	loadProvider ChannelLoadSnapshotProvider,
) *RouteChannelCandidate

SelectLeastBusyCandidate picks the candidate with the lowest load pressure. Prefer providers that expose lease/concurrency data; fall back to historical success/fail volume so the strategy still works without a load provider. Sticky exclude lists are applied upstream — this only ranks the filtered pool.

func SelectLowestCostCandidate

func SelectLowestCostCandidate(
	candidates []RouteChannelCandidate,
	modelResolver func(RouteChannelCandidate) string,
	pricingFn CatalogPricingResolver,
	fallbackUnitCost float64,
) *RouteChannelCandidate

SelectLowestCostCandidate picks the candidate with the lowest effective unit cost.

func SelectLowestLatencyCandidate

func SelectLowestLatencyCandidate(
	candidates []RouteChannelCandidate,
	modelResolver func(RouteChannelCandidate) string,
) *RouteChannelCandidate

SelectLowestLatencyCandidate ranks by site runtime first-byte/total latency EMA.

func SelectRoundRobinCandidate

func SelectRoundRobinCandidate(candidates []RouteChannelCandidate) *RouteChannelCandidate

SelectRoundRobinCandidate picks the first candidate in round-robin order.

type RouteDecisionCandidate

type RouteDecisionCandidate struct {
	ChannelID              int64   `json:"channelId"`
	AccountID              int64   `json:"accountId"`
	Username               string  `json:"username"`
	SiteName               string  `json:"siteName"`
	TokenName              string  `json:"tokenName"`
	Priority               int64   `json:"priority"`
	Weight                 int64   `json:"weight"`
	Eligible               bool    `json:"eligible"`
	RecentlyFailed         bool    `json:"recentlyFailed"`
	AvoidedByRecentFailure bool    `json:"avoidedByRecentFailure"`
	Probability            float64 `json:"probability"`
	Reason                 string  `json:"reason"`
}

RouteDecisionCandidate mirrors TS RouteDecisionCandidate.

type RouteDecisionExplanation

type RouteDecisionExplanation struct {
	RequestedModel    string                   `json:"requestedModel"`
	ActualModel       string                   `json:"actualModel"`
	Matched           bool                     `json:"matched"`
	RouteID           *int64                   `json:"routeId,omitempty"`
	ModelPattern      string                   `json:"modelPattern,omitempty"`
	SelectedChannelID *int64                   `json:"selectedChannelId,omitempty"`
	SelectedAccountID *int64                   `json:"selectedAccountId,omitempty"`
	SelectedLabel     string                   `json:"selectedLabel,omitempty"`
	Summary           []string                 `json:"summary"`
	Candidates        []RouteDecisionCandidate `json:"candidates"`
}

RouteDecisionExplanation mirrors TS RouteDecisionExplanation.

type RouteDecisionService

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

RouteDecisionService handles route decision snapshots.

func NewRouteDecisionService

func NewRouteDecisionService(router *TokenRouter, db DecisionDB) *RouteDecisionService

NewRouteDecisionService creates a new RouteDecisionService.

func (*RouteDecisionService) RefreshAllRouteDecisionSnapshots

func (s *RouteDecisionService) RefreshAllRouteDecisionSnapshots(ctx context.Context, refreshPricingCatalog bool) (exactModelCount int, wildcardRouteCount int, err error)

RefreshAllRouteDecisionSnapshots refreshes all route decision snapshots.

type RouteMatch

type RouteMatch struct {
	Route    store.TokenRoute
	Channels []RouteChannelCandidate
}

RouteMatch holds a matched route with its resolved channels.

type RouteRoutingStrategy

type RouteRoutingStrategy string

RouteRoutingStrategy is the strategy for a route.

const (
	StrategyWeighted      RouteRoutingStrategy = "weighted"
	StrategyRoundRobin    RouteRoutingStrategy = "round_robin"
	StrategyStableFirst   RouteRoutingStrategy = "stable_first"
	StrategyLeastBusy     RouteRoutingStrategy = "least_busy"
	StrategyLowestLatency RouteRoutingStrategy = "lowest_latency"
	StrategyLowestCost    RouteRoutingStrategy = "lowest_cost"
)

func NormalizeRouteRoutingStrategy

func NormalizeRouteRoutingStrategy(value string) RouteRoutingStrategy

NormalizeRouteRoutingStrategy normalizes a strategy string.

type RoutingWeightsConfig

type RoutingWeightsConfig struct {
	BaseWeightFactor float64
	ValueScoreFactor float64
	CostWeight       float64
	BalanceWeight    float64
	UsageWeight      float64
}

RoutingWeightsConfig mirrors config.RoutingWeights for the routing package.

type RuntimeHealthBreaker added in v0.11.0

type RuntimeHealthBreaker struct {
	SiteID         int64   `json:"siteId"`
	Model          string  `json:"model"` // empty = site-level breaker
	BreakerLevel   int64   `json:"breakerLevel"`
	BreakerUntilMs *int64  `json:"breakerUntilMs,omitempty"`
	PenaltyScore   float64 `json:"penaltyScore"`
}

RuntimeHealthBreaker is one open site-level or site+model breaker row.

type RuntimeHealthSnapshot added in v0.11.0

type RuntimeHealthSnapshot struct {
	SitesTracked      int                    `json:"sitesTracked"`
	SitesBreakerOpen  int                    `json:"sitesBreakerOpen"`
	ModelsTracked     int                    `json:"modelsTracked"`
	ModelsBreakerOpen int                    `json:"modelsBreakerOpen"`
	OpenBreakers      []RuntimeHealthBreaker `json:"openBreakers"`
}

RuntimeHealthSnapshot is a read-only aggregate of runtime health state.

func SnapshotRuntimeHealth added in v0.11.0

func SnapshotRuntimeHealth() RuntimeHealthSnapshot

SnapshotRuntimeHealth returns a read-only projection of the in-memory site/model runtime breaker state. Never hard-disables anything.

type SelectedChannel

type SelectedChannel struct {
	Channel     store.RouteChannel
	Account     store.Account
	Site        store.Site
	Token       *store.AccountToken
	TokenValue  string
	TokenName   string
	ActualModel string
	// ContextLength is the matched token_routes.context_length (tokens).
	// nil or <=0 means unknown / no max_tokens enforcement on the proxy path.
	ContextLength *int64
}

SelectedChannel is the result of a successful channel selection.

type SettingsStore

type SettingsStore interface {
	Get(key string) (string, error)
	Set(key, value string) error
}

SettingsStore defines the interface for persisting runtime health state.

type SiteHistoricalHealthMetrics

type SiteHistoricalHealthMetrics struct {
	Multiplier   float64
	TotalCalls   int64
	SuccessRate  *float64
	AvgLatencyMs *int64
}

SiteHistoricalHealthMetrics tracks historical health per site.

type SiteRuntimeFailureContext

type SiteRuntimeFailureContext struct {
	Status    *int
	ErrorText *string
	ModelName *string
}

SiteRuntimeFailureContext describes a failure event for runtime health tracking.

type SiteRuntimeHealthDetails

type SiteRuntimeHealthDetails struct {
	GlobalMultiplier   float64
	ModelMultiplier    float64
	CombinedMultiplier float64
	GlobalBreakerOpen  bool
	ModelBreakerOpen   bool
	// Half-open flags: the cooldown elapsed and the single recovery probe has
	// been admitted but not resolved yet. New requests keep being rejected.
	GlobalHalfOpen    bool
	ModelHalfOpen     bool
	ModelKey          string
	RecentSuccessRate float64
	RecentSampleCount float64
	RecentConfidence  float64
}

SiteRuntimeHealthDetails is the resolved health for selection.

func GetSiteRuntimeHealthDetails

func GetSiteRuntimeHealthDetails(siteID int64, modelName string) SiteRuntimeHealthDetails

GetSiteRuntimeHealthDetails returns combined health details for a site and model.

type SiteRuntimeHealthPersistencePayload

type SiteRuntimeHealthPersistencePayload struct {
	Version        int                                           `json:"version"`
	SavedAtMs      int64                                         `json:"savedAtMs"`
	GlobalBySiteID map[string]*SiteRuntimeHealthState            `json:"globalBySiteId"`
	ModelBySiteID  map[string]map[string]*SiteRuntimeHealthState `json:"modelBySiteId"`
}

SiteRuntimeHealthPersistencePayload is the serialization format.

type SiteRuntimeHealthState

type SiteRuntimeHealthState struct {
	PenaltyScore             float64  `json:"penaltyScore"`
	LatencyEMAMs             *float64 `json:"latencyEmaMs,omitempty"`
	FirstByteEMAMs           *float64 `json:"firstByteEmaMs,omitempty"`
	TransientFailureStreak   int64    `json:"transientFailureStreak"`
	LastTransientFailureAtMs *int64   `json:"lastTransientFailureAtMs,omitempty"`
	RecentSuccessCount       float64  `json:"recentSuccessCount"`
	RecentFailureCount       float64  `json:"recentFailureCount"`
	RecentWindowUpdatedAtMs  int64    `json:"recentWindowUpdatedAtMs"`
	BreakerLevel             int64    `json:"breakerLevel"`
	BreakerUntilMs           *int64   `json:"breakerUntilMs,omitempty"`
	// HalfOpenSinceMs marks the half-open probe window: non-nil while the single
	// post-cooldown recovery probe is in flight. Cleared when the probe outcome
	// is recorded or the probe window times out.
	HalfOpenSinceMs *int64 `json:"halfOpenSinceMs,omitempty"`
	LastUpdatedAtMs int64  `json:"lastUpdatedAtMs"`
	LastFailureAtMs *int64 `json:"lastFailureAtMs,omitempty"`
	LastSuccessAtMs *int64 `json:"lastSuccessAtMs,omitempty"`
	// Background probe status (). Soft operator signal; never marks keys expired.
	LastProbeAtMs      *int64   `json:"lastProbeAtMs,omitempty"`
	LastProbeStatus    string   `json:"lastProbeStatus,omitempty"` // success | failure | inconclusive
	LastProbeLatencyMs *float64 `json:"lastProbeLatencyMs,omitempty"`
	LastProbeError     *string  `json:"lastProbeError,omitempty"`
	LastProbeModel     string   `json:"lastProbeModel,omitempty"`
	LastProbeChannelID *int64   `json:"lastProbeChannelId,omitempty"`
}

SiteRuntimeHealthState tracks runtime health for a site or (site, model).

type SnapshotDB

type SnapshotDB interface {
	UpdateRouteDecisionSnapshot(ctx context.Context, routeID int64, snapshot string, refreshedAt string) error
	ClearRouteDecisionSnapshot(ctx context.Context, routeID int64) error
	ClearRouteDecisionSnapshots(ctx context.Context, routeIDs []int64) error
	ClearAllRouteDecisionSnapshots(ctx context.Context) error
	LoadRouteGroupSources(ctx context.Context, groupRouteIDs []int64) (map[int64][]int64, error)
}

SnapshotDB defines the low-level DB operations for persisting route decision snapshots. The concrete implementation is service.ProxyRoutingStore (service/routing_store.go); the former high-level RouteDecisionSnapshotStore was removed as dead code — decision snapshots are written directly by the route-decision service through this interface.

type StableFirstObservationProgressState

type StableFirstObservationProgressState struct {
	RequestCount        int64
	LastObservationAtMs *int64
}

StableFirstObservationProgressState tracks observation gating progress.

type StableFirstPoolPlan

type StableFirstPoolPlan struct {
	PrimaryCandidates     []RouteChannelCandidate
	ObservationCandidates []RouteChannelCandidate
	PrimarySiteIDs        []int64
	ObservationSiteIDs    []int64
	SiteStateByID         map[int64]StableFirstSitePoolState
}

StableFirstPoolPlan is the result of splitting candidates into pools.

func BuildStableFirstPoolPlan

func BuildStableFirstPoolPlan(candidates []RouteChannelCandidate, modelResolver func(RouteChannelCandidate) string) StableFirstPoolPlan

BuildStableFirstPoolPlan splits candidates into primary and observation pools.

type StableFirstSitePoolState

type StableFirstSitePoolState struct {
	SiteID               int64
	Leader               RouteChannelCandidate
	EffectiveSuccessRate float64
	Trusted              bool
	ObservationReason    string
}

StableFirstSitePoolState is per-site state in a pool plan.

type TokenProvider

type TokenProvider interface {
	GetTokens(ctx context.Context, accountID int64) ([]store.AccountToken, error)
	GetDefaultToken(ctx context.Context, accountID int64) (*store.AccountToken, error)
}

TokenProvider supplies token data.

type TokenRouter

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

TokenRouter is the main routing engine. It composes all sub-modules.

func NewTokenRouter

func NewTokenRouter(
	db ChannelSelectorDB,
	cfg *config.Config,
	pricingFn CatalogPricingResolver,
	channelLoadProvider ChannelLoadSnapshotProvider,
) *TokenRouter

NewTokenRouter creates a new TokenRouter.

func (*TokenRouter) ClearChannelFailureState

func (tr *TokenRouter) ClearChannelFailureState(ctx context.Context, channelIDs []int64) (int64, error)

ClearChannelFailureState clears failure/cooldown for channels.

func (*TokenRouter) ExplainSelection

func (tr *TokenRouter) ExplainSelection(ctx context.Context, requestedModel string, excludeChannelIDs []int64, policy DownstreamRoutingPolicy) (RouteDecisionExplanation, error)

ExplainSelection returns a decision explanation for the requested model.

func (*TokenRouter) ExplainSelectionForRoute

func (tr *TokenRouter) ExplainSelectionForRoute(ctx context.Context, routeID int64, requestedModel string, excludeChannelIDs []int64, policy DownstreamRoutingPolicy) (RouteDecisionExplanation, error)

ExplainSelectionForRoute returns a decision explanation for a specific route.

func (*TokenRouter) ExplainSelectionRouteWide

func (tr *TokenRouter) ExplainSelectionRouteWide(ctx context.Context, routeID int64, policy DownstreamRoutingPolicy) (RouteDecisionExplanation, error)

ExplainSelectionRouteWide returns a decision explanation for a route-wide view.

func (*TokenRouter) GetAvailableModelContextLengths

func (tr *TokenRouter) GetAvailableModelContextLengths(ctx context.Context) (map[string]int64, error)

Metadata only — no proxy max-token enforcement is implied by this map.

func (*TokenRouter) GetAvailableModels

func (tr *TokenRouter) GetAvailableModels(ctx context.Context) ([]string, error)

GetAvailableModels returns all exposed model names from enabled routes.

func (*TokenRouter) InvalidateAllCaches

func (tr *TokenRouter) InvalidateAllCaches()

InvalidateAllCaches clears all caches.

func (*TokenRouter) InvalidateRouteScopedCache

func (tr *TokenRouter) InvalidateRouteScopedCache(routeID int64)

InvalidateRouteScopedCache clears cache for a specific route.

func (*TokenRouter) RecordFailure

func (tr *TokenRouter) RecordFailure(ctx context.Context, channelID int64, failureCtx SiteRuntimeFailureContext, actualAccountID *int64) error

RecordFailure records a channel failure and sets cooldown.

func (*TokenRouter) RecordProbeFailure

func (tr *TokenRouter) RecordProbeFailure(ctx context.Context, channelID int64, failureCtx SiteRuntimeFailureContext, actualAccountID *int64) error

Unlike RecordFailure (user traffic path), probe failures: - update site/model runtime health + breaker streak (so routing can avoid dead channels) - apply a short channel cooldown only for the probed channel (no credential cascade) - never mark accounts/keys expired - never treat auth-looking probe errors as credential expiry

func (*TokenRouter) RecordProbeSuccess

func (tr *TokenRouter) RecordProbeSuccess(ctx context.Context, channelID int64, latencyMs float64, modelName *string, actualAccountID *int64) error

RecordProbeSuccess records a successful background health probe. It clears cooldown for credential-scoped channels, feeds runtime health success, and stamps last probe status. It never marks credentials expired.

func (*TokenRouter) RecordSuccess

func (tr *TokenRouter) RecordSuccess(ctx context.Context, channelID int64, latencyMs float64, cost float64, modelName *string, actualAccountID *int64) error

RecordSuccess records a successful channel usage.

func (*TokenRouter) SelectChannel

func (tr *TokenRouter) SelectChannel(ctx context.Context, requestedModel string, policy DownstreamRoutingPolicy) (*SelectedChannel, error)

SelectChannel finds a matching route and selects a channel.

func (*TokenRouter) SelectNextChannel

func (tr *TokenRouter) SelectNextChannel(ctx context.Context, requestedModel string, excludeChannelIDs []int64, policy DownstreamRoutingPolicy) (*SelectedChannel, error)

SelectNextChannel selects the next channel excluding already-tried ones.

func (*TokenRouter) SelectPreferredChannel

func (tr *TokenRouter) SelectPreferredChannel(ctx context.Context, requestedModel string, preferredChannelID int64, policy DownstreamRoutingPolicy, excludeChannelIDs []int64) (*SelectedChannel, error)

SelectPreferredChannel selects a specific preferred channel.

type UsageForCost

type UsageForCost struct {
	PromptTokens        int64
	CompletionTokens    int64
	TotalTokens         int64
	CacheReadTokens     int64
	CacheCreationTokens int64
	// PromptTokensIncludeCache:
	// true/nil → prompt tokens already include cache tokens (subtract for billable input)
	// false → prompt tokens are exclusive of cache tokens
	PromptTokensIncludeCache *bool
}

UsageForCost is token usage for a single request cost estimate.

type WeightedDetail

type WeightedDetail struct {
	Candidate   RouteChannelCandidate
	Probability float64
	Reason      string
}

WeightedDetail describes a single candidate's score breakdown.

type WeightedSelectionMode

type WeightedSelectionMode string

WeightedSelectionMode is either "weighted" or "stable_first".

const (
	WeightedMode    WeightedSelectionMode = "weighted"
	StableFirstMode WeightedSelectionMode = "stable_first"
)

type WeightedSelectionResult

type WeightedSelectionResult struct {
	Selected        *RouteChannelCandidate
	Details         []WeightedDetail
	StableSiteCount int
}

WeightedSelectionResult holds the selection result and detailed info.

func CalculateWeightedSelection

func CalculateWeightedSelection(
	candidates []RouteChannelCandidate,
	modelResolver func(RouteChannelCandidate) string,
	routingWeights RoutingWeightsConfig,
	siteWeightMultipliers map[int64]float64,
	keyWeight float64,
	channelLoadProvider ChannelLoadSnapshotProvider,
	nowMs int64,
	mode WeightedSelectionMode,
	stableFirstRotationKey string,
	pricingFn CatalogPricingResolver,
	fallbackUnitCost float64,
) WeightedSelectionResult

CalculateWeightedSelection performs the full weighted random selection algorithm. Implements the TS calculateWeightedSelection exactly.

Jump to

Keyboard shortcuts

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