score

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2026 License: Apache-2.0 Imports: 7 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

Index

Constants

View Source
const (
	DefaultHalfLifeTime = time.Hour
	MaxHalfTime         = 3 * time.Hour

	DefaultWeight     float64 = 1
	RelayUpdateWeight float64 = 1

	// DefaultProbeUpdateWeight controls the relative impact of probe samples (liveness/latency)
	// compared to relay samples in the provider optimizer.
	// It can be overridden at process start via CLI flag (see rpcconsumer/rpcsmartrouter).
	DefaultProbeUpdateWeight float64 = 0.25

	// TODO: find actual numbers from info of latencies of high/mid/low CU from "stats.lavanet.xyz".
	// Do a distribution and find average factor to multiply the failure cost by.
	DefaultCuLatencyFactor = LowCuLatencyFactor
	HighCuLatencyFactor    = 0.01       // for cu > HighCuThreshold
	MidCuLatencyFactor     = 0.1        // for MidCuThreshold < cu < HighCuThreshold
	LowCuLatencyFactor     = float64(1) // for cu < MidCuThreshold

	HighCuThreshold = uint64(100)
	MidCuThreshold  = uint64(50)

	// Adaptive Normalization Constants (Phase 2)
	// P10 bounds: Used to clamp the 10th percentile (adaptive minimum)
	AdaptiveP10MinBound float64 = 0.001 // 1ms - extremely fast local/optimized providers
	AdaptiveP10MaxBound float64 = 10.0  // 10s - maximum reasonable P10

	// T-Digest compression for adaptive max calculator
	DefaultTDigestCompression float64 = 100.0 // Good balance of accuracy vs memory

	// Default bounds for latency adaptive max calculator
	DefaultLatencyAdaptiveMinMax float64 = 1.0  // 1 second minimum for P90
	DefaultLatencyAdaptiveMaxMax float64 = 30.0 // 30 seconds maximum for P90 (WorstLatencyScore)

	// Sync-specific adaptive normalization constants (Phase 2)
	// P10 bounds for sync: Used to clamp the 10th percentile (adaptive minimum)
	AdaptiveSyncP10MinBound float64 = 0.1  // 100ms - very fast sync (perfect or near-perfect)
	AdaptiveSyncP10MaxBound float64 = 60.0 // 60s - maximum reasonable P10 for sync

	// Default bounds for sync adaptive max calculator
	DefaultSyncAdaptiveMinMax float64 = 30.0   // 30 seconds minimum for P90
	DefaultSyncAdaptiveMaxMax float64 = 1200.0 // 1200 seconds (20 min) maximum for P90 (WorstSyncScore)

	// Availability-specific normalization constants (Phase 1: Simple Rescaling)
	// Availability is already in [0,1] range but has poor distribution (typically 0.95-1.0 = only 5% of range)
	// Rescaling [MIN_ACCEPTABLE, 1.0] → [0.0, 1.0] achieves 100% range utilization
	MinAcceptableAvailability float64 = 0.80 // Below 80% availability = score of 0 (reasonable minimum)
)
View Source
const (
	DecPrecision         int64 = 8
	InitialDataStaleness       = 24 * time.Hour
)
View Source
const (
	DefaultLatencyNum      float64 = 0.01
	DefaultSyncNum         float64 = 0.1
	DefaultAvailabilityNum float64 = 1

	LatencyScoreType      = "latency"
	SyncScoreType         = "sync"
	AvailabilityScoreType = "availability"
	TotalScoreType        = "total"

	// Worst score results for each QoS excellence metric for truncation
	WorstLatencyScore      float64 = 30      // seconds
	WorstSyncScore         float64 = 20 * 60 // seconds
	WorstAvailabilityScore float64 = 0.00001 // very small value to avoid score = 0
)

Variables

View Source
var ProbeUpdateWeight = DefaultProbeUpdateWeight

ProbeUpdateWeight is a process-level knob used by the provider optimizer when recording probe samples. It must be strictly positive and finite (ScoreStore config validates weight > 0).

View Source
var TimeConflictingScoresError = &sentinelError{msg: "ScoreStore has a more recent sample than the one provided"}

Functions

func GetLatencyFactor

func GetLatencyFactor(cu uint64) float64

GetLatencyFactor returns the appropriate latency factor by the CU amount

func SetProbeUpdateWeight

func SetProbeUpdateWeight(weight float64) error

Types

type AdaptiveMaxCalculator

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

AdaptiveMaxCalculator uses T-Digest with exponential decay to calculate adaptive maximum values for normalization. This approach uses the 95th percentile of all individual samples (not provider averages) with exponential decay weighting that aligns mathematically with the ScoreStore's decaying weighted average.

func NewAdaptiveMaxCalculator

func NewAdaptiveMaxCalculator(halfLife time.Duration, minP10, maxP10, minMax, maxMax, compression float64) *AdaptiveMaxCalculator

NewAdaptiveMaxCalculator creates a new adaptive max calculator with T-Digest and exponential decay support.

Parameters:

  • halfLife: The half-life for exponential decay (should match ScoreStore half-life)
  • minP10: Minimum value to clamp P10 to (safety bound for 10th percentile)
  • maxP10: Maximum value to clamp P10 to (safety bound for 10th percentile)
  • minMax: Minimum value to clamp P90/adaptive max to (safety bound)
  • maxMax: Maximum value to clamp P90/adaptive max to (safety bound)
  • compression: T-Digest compression parameter (100 is recommended)

func (*AdaptiveMaxCalculator) AddSample

func (a *AdaptiveMaxCalculator) AddSample(value float64, sampleTime time.Time) error

AddSample adds a new sample to the T-Digest with exponential decay. This method applies exponential decay to all existing centroids (using the SAME formula as ScoreStore) and then adds the new sample with weight = 1.0.

The decay formula is:

decayFactor = exp(-(ln(2) * timeDiff) / halfLife)

This ensures that:

  • Sample from 1 hour ago: 50% weight
  • Sample from 2 hours ago: 25% weight
  • Sample from 3 hours ago: 12.5% weight

Parameters:

  • value: The sample value to add
  • sampleTime: The timestamp of the sample

func (*AdaptiveMaxCalculator) GetAdaptiveBounds

func (a *AdaptiveMaxCalculator) GetAdaptiveBounds() (p10, p90 float64)

GetAdaptiveBounds returns both P10 and P90 from the T-Digest for the P10-P90 adaptive normalization approach (Phase 2 hybrid). This provides better distribution and outlier handling than P95-only.

Returns:

  • p10: 10th percentile (adaptive minimum), clamped to reasonable bounds
  • p90: 90th percentile (adaptive maximum), clamped to reasonable bounds

func (*AdaptiveMaxCalculator) GetAdaptiveMax

func (a *AdaptiveMaxCalculator) GetAdaptiveMax() float64

GetAdaptiveMax returns the 95th percentile from the T-Digest as the adaptive max, clamped to the configured [minMax, maxMax] range. Deprecated: Use GetAdaptiveBounds() for the P10-P90 approach (Phase 2 hybrid).

func (*AdaptiveMaxCalculator) GetStats

func (a *AdaptiveMaxCalculator) GetStats() map[string]interface{}

GetStats returns statistics about the adaptive max calculator for debugging

func (*AdaptiveMaxCalculator) LogDistributionStats

func (a *AdaptiveMaxCalculator) LogDistributionStats(parameterName string)

LogDistributionStats logs comprehensive distribution statistics for visualization This is designed to provide all needed data for Python plotting and analysis

func (*AdaptiveMaxCalculator) Reset

func (a *AdaptiveMaxCalculator) Reset()

Reset clears the T-Digest and resets to initial state

type AvailabilityScoreStore

type AvailabilityScoreStore struct {
	*ScoreStore
}

func (*AvailabilityScoreStore) Resolve

func (as *AvailabilityScoreStore) Resolve() (float64, error)

func (*AvailabilityScoreStore) Update

func (as *AvailabilityScoreStore) Update(sample float64, sampleTime time.Time) error

Update updates the availability ScoreStore's numerator and denominator with a new sample. The new sample must be 0 or 1.

type Config

type Config struct {
	Weight          float64
	HalfLife        time.Duration
	LatencyCuFactor float64 // should only be used for latency samples
}

func (Config) String

func (c Config) String() string

String prints a Config's fields

func (Config) Validate

func (c Config) Validate() error

Validate validates the Config's fields hold valid values

type LatencyScoreStore

type LatencyScoreStore struct {
	*ScoreStore
	// contains filtered or unexported fields
}

func (*LatencyScoreStore) EnableAdaptiveMax

func (ls *LatencyScoreStore) EnableAdaptiveMax(halfLife time.Duration, minMax, maxMax, compression float64)

EnableAdaptiveMax enables adaptive max calculation with T-Digest

func (*LatencyScoreStore) GetAdaptiveBounds

func (ls *LatencyScoreStore) GetAdaptiveBounds() (p10, p90 float64)

GetAdaptiveBounds returns both P10 and P90 for adaptive normalization (Phase 2 hybrid) Returns (p10, p90) where both values are clamped to reasonable bounds. If adaptive max is not enabled, returns safe defaults.

func (*LatencyScoreStore) GetAdaptiveMax

func (ls *LatencyScoreStore) GetAdaptiveMax() float64

GetAdaptiveMax returns the adaptive max value if enabled, otherwise returns 0 Deprecated: Use GetAdaptiveBounds() for the P10-P90 approach (Phase 2 hybrid).

func (*LatencyScoreStore) GetAdaptiveMaxStats

func (ls *LatencyScoreStore) GetAdaptiveMaxStats() map[string]interface{}

GetAdaptiveMaxStats returns statistics about the adaptive max calculator

func (*LatencyScoreStore) IsAdaptiveMaxEnabled

func (ls *LatencyScoreStore) IsAdaptiveMaxEnabled() bool

IsAdaptiveMaxEnabled returns whether adaptive max is enabled

func (*LatencyScoreStore) Update

func (ls *LatencyScoreStore) Update(sample float64, sampleTime time.Time) error

Update updates the Latency ScoreStore's numerator and denominator with a new sample.

type Option

type Option func(*Config)

Option is used as a generic and elegant way to configure a new ScoreStore

func WithDecayHalfLife

func WithDecayHalfLife(halfLife time.Duration) Option

func WithLatencyCuFactor

func WithLatencyCuFactor(factor float64) Option

func WithWeight

func WithWeight(weight float64) Option

type ScoreStore

type ScoreStore struct {
	Name   string
	Num    float64 // using float64 and not math/big for performance
	Denom  float64
	Time   time.Time
	Config Config
	// contains filtered or unexported fields
}

ScoreStore is a decaying weighted average object that is used to collect providers performance metrics samples (see QoS excellence comment below). These are used to calculate the providers QoS excellence score, used by the provider optimizer when choosing providers to be paired with a consumer.

ScoreStore holds a score's numerator and denominator, last update timestamp, and a configuration object. When a ScoreStore updates it uses a decay exponent to lower the weight of old average samples and a weight parameter to determine the influence of the new sample.

Resolving the ScoreStore's num and denom means to divide the num by the denom to get the score. Keeping the score as a fracture helps calculating and updating weighted average calculations on the go.

func (*ScoreStore) GetConfig

func (ss *ScoreStore) GetConfig() Config

func (*ScoreStore) GetDenom

func (ss *ScoreStore) GetDenom() float64

func (*ScoreStore) GetLastUpdateTime

func (ss *ScoreStore) GetLastUpdateTime() time.Time

func (*ScoreStore) GetName

func (ss *ScoreStore) GetName() string

func (*ScoreStore) GetNum

func (ss *ScoreStore) GetNum() float64

func (*ScoreStore) Resolve

func (ss *ScoreStore) Resolve() (float64, error)

Resolve resolves the ScoreStore's frac by dividing the numerator by the denominator

func (*ScoreStore) String

func (ss *ScoreStore) String() string

String prints a ScoreStore's fields

func (*ScoreStore) Update

func (ss *ScoreStore) Update(sample float64, sampleTime time.Time) error

update updates the ScoreStore's numerator and denominator with a new sample. The ScoreStore's score is calculated as a weighted average with a decay factor. The new sample is added by the following formula:

num = num * decay_factor + sample * weight
denom = denom * decay_factor + weight
decay_factor = exp(-time_since_last_update / half_life_time)

func (*ScoreStore) UpdateConfig

func (ss *ScoreStore) UpdateConfig(opts ...Option) error

UpdateConfig updates the configuration of a ScoreStore

func (*ScoreStore) Validate

func (ss *ScoreStore) Validate() error

Validate validates the ScoreStore's fields hold valid values

type ScoreStorer

type ScoreStorer interface {
	Update(sample float64, sampleTime time.Time) error
	Resolve() (float64, error)
	Validate() error
	String() string
	UpdateConfig(opts ...Option) error

	GetName() string
	GetNum() float64
	GetDenom() float64
	GetLastUpdateTime() time.Time
	GetConfig() Config
}

ScoreStorer defines the interface for all score stores

func NewCustomScoreStore

func NewCustomScoreStore(scoreType string, num, denom float64, t time.Time, opts ...Option) (ScoreStorer, error)

NewCustomScoreStore creates a new custom ScoreStorer based on the score type

func NewScoreStore

func NewScoreStore(scoreType string) ScoreStorer

NewScoreStore creates a new default ScoreStorer based on the score type

type SyncScoreStore

type SyncScoreStore struct {
	*ScoreStore
	// contains filtered or unexported fields
}

func (*SyncScoreStore) EnableAdaptiveMax

func (ss *SyncScoreStore) EnableAdaptiveMax(halfLife time.Duration, minMax, maxMax, compression float64)

EnableAdaptiveMax enables adaptive max calculation with T-Digest

func (*SyncScoreStore) GetAdaptiveBounds

func (ss *SyncScoreStore) GetAdaptiveBounds() (p10, p90 float64)

GetAdaptiveBounds returns both P10 and P90 for adaptive normalization (Phase 2 hybrid) Returns (p10, p90) where both values are clamped to reasonable bounds. If adaptive max is not enabled, returns safe defaults.

func (*SyncScoreStore) GetAdaptiveMaxStats

func (ss *SyncScoreStore) GetAdaptiveMaxStats() map[string]interface{}

GetAdaptiveMaxStats returns statistics about the adaptive max calculator

func (*SyncScoreStore) IsAdaptiveMaxEnabled

func (ss *SyncScoreStore) IsAdaptiveMaxEnabled() bool

IsAdaptiveMaxEnabled returns whether adaptive max is enabled

func (*SyncScoreStore) Update

func (ss *SyncScoreStore) Update(sample float64, sampleTime time.Time) error

Update updates the Sync ScoreStore's numerator and denominator with a new sample.

Jump to

Keyboard shortcuts

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