provideroptimizer

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: Apache-2.0 Imports: 16 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 (
	CacheMaxCost     = 20000 // each item cost would be 1
	CacheNumCounters = 20000 // expect 2000 items
)

Variables

This section is empty.

Functions

func CumulativeProbabilityFunctionForPoissonDist

func CumulativeProbabilityFunctionForPoissonDist(k_events uint64, lambda float64) float64

Types

type ConcurrentBlockStore

type ConcurrentBlockStore struct {
	Lock  sync.Mutex
	Time  time.Time
	Block uint64
}

type ProviderData

type ProviderData struct {
	Availability score.ScoreStorer // will be used to calculate the probability of error
	Latency      score.ScoreStorer // will be used to calculate the latency score
	Sync         score.ScoreStorer // will be used to calculate the sync score for spectypes.LATEST_BLOCK/spectypes.NOT_APPLICABLE requests
	SyncBlock    uint64            // will be used to calculate the probability of block error
}

type ProviderOptimizer

type ProviderOptimizer struct {
	NowFunc func() time.Time // NowFunc overrides the clock used for score updates nil = use real time.Now()
	// contains filtered or unexported fields
}

func NewProviderOptimizer

func NewProviderOptimizer(strategy Strategy, averageBlockTIme time.Duration, wantedNumProvidersInConcurrency uint, consumerOptimizerQoSClient consumerOptimizerQoSClientInf, chainId string) *ProviderOptimizer

func (*ProviderOptimizer) AppendProbeRelayData

func (po *ProviderOptimizer) AppendProbeRelayData(providerAddress string, latency time.Duration, success bool)

AppendProbeRelayData updates a provider's QoS metrics for a probe relay message

func (*ProviderOptimizer) AppendRelayData

func (po *ProviderOptimizer) AppendRelayData(provider string, latency time.Duration, cu, syncBlock uint64)

AppendRelayData updates a provider's QoS metrics for a successful relay

func (*ProviderOptimizer) AppendRelayFailure

func (po *ProviderOptimizer) AppendRelayFailure(provider string)

AppendRelayFailure updates a provider's QoS metrics for a failed relay

func (*ProviderOptimizer) CalculateQoSScoresForMetrics

func (po *ProviderOptimizer) CalculateQoSScoresForMetrics(allAddresses []string, ignoredProviders map[string]struct{}, cu uint64, requestedBlock int64) []*metrics.OptimizerQoSReport

CalculateQoSScoresForMetrics calculates QoS scores for all providers for metrics reporting

func (*ProviderOptimizer) ChooseBestProvider

func (po *ProviderOptimizer) ChooseBestProvider(ctx context.Context, allAddresses []string, ignoredProviders map[string]struct{}, cu uint64, requestedBlock int64) (addresses []string)

ChooseBestProvider selects a single high-quality provider using weighted selection This is used for sticky sessions and other scenarios requiring consistent provider selection

func (*ProviderOptimizer) ChooseBestProviderWithStats

func (po *ProviderOptimizer) ChooseBestProviderWithStats(ctx context.Context, allAddresses []string, ignoredProviders map[string]struct{}, cu uint64, requestedBlock int64) (addresses []string, stats *SelectionStats)

ChooseBestProviderWithStats selects a single high-quality provider and returns detailed selection statistics

func (*ProviderOptimizer) ChooseProvider

func (po *ProviderOptimizer) ChooseProvider(ctx context.Context, allAddresses []string, ignoredProviders map[string]struct{}, cu uint64, requestedBlock int64) (addresses []string)

ChooseProvider returns a subset of selected providers using weighted random selection based on QoS scores

func (*ProviderOptimizer) ChooseProviderWithStats

func (po *ProviderOptimizer) ChooseProviderWithStats(ctx context.Context, allAddresses []string, ignoredProviders map[string]struct{}, cu uint64, requestedBlock int64) (addresses []string, stats *SelectionStats)

ChooseProviderWithStats returns a subset of selected providers and detailed selection statistics

func (*ProviderOptimizer) ConfigureWeightedSelector

func (po *ProviderOptimizer) ConfigureWeightedSelector(config WeightedSelectorConfig)

ConfigureWeightedSelector rebuilds the weighted selector using the supplied configuration. Strategy is always enforced from the optimizer so callers only provide weights and selection chance values.

func (*ProviderOptimizer) GetReputationReportForProvider

func (po *ProviderOptimizer) GetReputationReportForProvider(providerAddress string) (report *pairingtypes.QualityOfServiceReport, lastUpdateTime time.Time)

func (*ProviderOptimizer) GetWeightedSelectorConfig

func (po *ProviderOptimizer) GetWeightedSelectorConfig() WeightedSelectorConfig

GetWeightedSelectorConfig returns the current weighted selector configuration

func (*ProviderOptimizer) ResetState

func (po *ProviderOptimizer) ResetState()

ResetState clears all time-dependent internal state so the optimizer works correctly after a debug clock reset (i.e. when the time offset is set back to 0).

Why this is necessary: When the clock is shifted forward (e.g. +24 h via the debug server), all ScoreStore entries written during that window carry future timestamps. When the offset is reset to 0, po.now() returns real time again — but ScoreStore.Update rejects any sample whose timestamp is earlier than the stored one ("TimeConflictingScoresError"). That means every new relay sample would be silently dropped for the next 24 hours, leaving the optimizer effectively frozen. Calling ResetState discards all the future-dated data so incoming real-time samples are accepted immediately.

func (*ProviderOptimizer) SetDeterministicSeed

func (po *ProviderOptimizer) SetDeterministicSeed(seed int64)

SetDeterministicSeed sets a deterministic seed for the weighted selector This is used for testing purposes only to ensure reproducible provider selection

func (*ProviderOptimizer) Strategy

func (po *ProviderOptimizer) Strategy() Strategy

func (*ProviderOptimizer) UpdateWeightedSelectorStrategy

func (po *ProviderOptimizer) UpdateWeightedSelectorStrategy(strategy Strategy)

UpdateWeightedSelectorStrategy updates the weighted selector's strategy This should be called when the optimizer's strategy changes

func (*ProviderOptimizer) UpdateWeights

func (po *ProviderOptimizer) UpdateWeights(weights map[string]int64, epoch uint64)

UpdateWeights updates provider stake amounts in the cache and metrics

type ProviderScore

type ProviderScore struct {
	Address         string  // Provider address
	CompositeScore  float64 // Normalized 0-1 composite score
	SelectionWeight float64 // Score adjusted by strategy and stake
}

ProviderScore represents a provider's calculated scores for selection

type ProviderScoreDetails

type ProviderScoreDetails struct {
	Address      string  // Provider address
	Availability float64 // Availability score (0-1)
	Latency      float64 // Latency score (0-1)
	Sync         float64 // Sync score (0-1)
	Stake        float64 // Stake score (0-1)
	Composite    float64 // Combined QoS score (0-1)
}

ProviderScoreDetails contains detailed scoring information for a single provider

type ProviderStakeCache

type ProviderStakeCache interface {
	GetStake(address string) int64
	UpdateStakes(stakes map[string]int64)
}

ProviderStakeCache maintains provider stake amounts for use in selection algorithms. It provides thread-safe access to stake values used by the weighted selector to calculate provider selection probabilities.

func NewProviderStakeCache

func NewProviderStakeCache() ProviderStakeCache

type Randomizer

type Randomizer interface {
	Float64() float64
	Intn(n int) int
}

Randomizer interface allows switching between global probabilistic RNG and deterministic RNG for testing

type SelectionStats

type SelectionStats struct {
	ProviderScores   []ProviderScoreDetails // Scores for all candidates
	RNGValue         float64                // Random number used for selection
	SelectedProvider string                 // The provider that was selected
}

SelectionStats contains detailed information about provider selection for debugging

func (*SelectionStats) FormatSelectionStats

func (stats *SelectionStats) FormatSelectionStats() string

FormatSelectionStats formats selection stats as a string for the header Format: [provider1: availability, latency, sync, stake, composite] [provider2: ...] | RNG: <value> | Selected: <provider>

type Strategy

type Strategy int

Strategy defines the pairing strategy. Using different strategies allow users to determine the providers type they'll be paired with: providers with low latency, fresh sync and more.

const (
	StrategyBalanced      Strategy = iota
	StrategyLatency                // prefer low latency
	StrategySyncFreshness          // prefer better sync
	StrategyCost                   // prefer low CU cost
	StrategyPrivacy                // prefer pairing with a single provider (not fully implemented)
	StrategyAccuracy               // higher cost for more accuracy
	StrategyDistributed            // prefer pairing with different providers
)

func (Strategy) String

func (s Strategy) String() string

type WeightedSelector

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

WeightedSelector implements continuous weighted random selection based on composite QoS scores. It replaces the tier-based selection system with a probability-based approach where providers are selected according to their overall quality without artificial tier boundaries.

func NewWeightedSelector

func NewWeightedSelector(config WeightedSelectorConfig) *WeightedSelector

NewWeightedSelector creates a new WeightedSelector with the given configuration

func (*WeightedSelector) CalculateProviderScores

func (ws *WeightedSelector) CalculateProviderScores(
	allAddresses []string,
	ignoredProviders map[string]struct{},
	providerDataGetter func(string) (*pairingtypes.QualityOfServiceReport, time.Time, bool),
	stakeGetter func(string) int64,
) ([]ProviderScore, map[string]*metrics.OptimizerQoSReport, []ProviderScoreDetails)

CalculateProviderScores computes scores for all providers

func (*WeightedSelector) CalculateScore

func (ws *WeightedSelector) CalculateScore(
	qos *pairingtypes.QualityOfServiceReport,
	stake float64,
	totalStake float64,
	providerAddress string,
) float64

CalculateScore computes a composite score for a provider based on QoS metrics and stake. stake and totalStake are raw stake amounts (e.g. in ulava). Returns a normalized score between 0 and 1, where higher is better

func (*WeightedSelector) GetConfig

func (ws *WeightedSelector) GetConfig() WeightedSelectorConfig

GetConfig returns the current configuration

func (*WeightedSelector) SelectProvider

func (ws *WeightedSelector) SelectProvider(
	ctx context.Context,
	providerScores []ProviderScore,
) string

SelectProvider selects a provider using weighted random selection Providers with higher composite scores have higher probability of selection

func (*WeightedSelector) SelectProviderWithStats

func (ws *WeightedSelector) SelectProviderWithStats(
	ctx context.Context,
	providerScores []ProviderScore,
	scoreDetails []ProviderScoreDetails,
) (string, *SelectionStats)

SelectProviderWithStats selects a provider using weighted random selection and returns detailed selection statistics if scoreDetails is provided

func (*WeightedSelector) SetDeterministicSeed

func (ws *WeightedSelector) SetDeterministicSeed(seed int64)

SetDeterministicSeed sets a specific seed for the weighted selector's RNG This should ONLY be used for testing to ensure deterministic selection

func (*WeightedSelector) UpdateStrategy

func (ws *WeightedSelector) UpdateStrategy(strategy Strategy)

UpdateStrategy changes the strategy and recalculates any strategy-dependent parameters

type WeightedSelectorConfig

type WeightedSelectorConfig struct {
	AvailabilityWeight    float64
	LatencyWeight         float64
	SyncWeight            float64
	StakeWeight           float64
	MinSelectionChance    float64
	Strategy              Strategy
	UseAdaptiveLatencyMax bool                      // Phase 2: Enable adaptive max for latency
	AdaptiveLatencyGetter func() (p10, p90 float64) // Phase 2: Function to get adaptive P10-P90 bounds
	UseAdaptiveSyncMax    bool                      // Phase 2: Enable adaptive max for sync
	AdaptiveSyncGetter    func() (p10, p90 float64) // Phase 2: Function to get adaptive P10-P90 bounds for sync
}

WeightedSelectorConfig holds configuration options for creating a WeightedSelector

func DefaultWeightedSelectorConfig

func DefaultWeightedSelectorConfig() WeightedSelectorConfig

DefaultWeightedSelectorConfig returns a configuration with balanced default weights

Jump to

Keyboard shortcuts

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