preload

package
v0.97.0 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package preload provides predictive cache preloading for AI operations. It implements Issue #102: Predictive preloading based on user patterns.

Package preload provides predictive cache preloading scheduling. This file implements the scheduler that performs preloading based on predictions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Activity

type Activity struct {
	// Timestamp when the activity occurred.
	Timestamp time.Time

	// Query is the search query (if any).
	Query string

	// AgentType used for the query.
	AgentType string

	// SessionDuration is the duration of the session.
	SessionDuration time.Duration

	// TokensUsed is the number of tokens consumed.
	TokensUsed int

	// Topics are topics related to this activity.
	Topics []string
}

Activity represents a single user activity.

type Analyzer

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

Analyzer analyzes user behavior patterns for predictive preloading.

func NewAnalyzer

func NewAnalyzer(cfg Config) *Analyzer

NewAnalyzer creates a new pattern analyzer.

func (*Analyzer) Clear

func (a *Analyzer) Clear()

Clear clears the pattern cache.

func (*Analyzer) GetPattern

func (a *Analyzer) GetPattern(ctx context.Context, userID int64) (*UserPattern, error)

GetPattern returns the user's current pattern.

func (*Analyzer) GetPreloadSuggestions

func (a *Analyzer) GetPreloadSuggestions(ctx context.Context, userID int64) *PreloadSuggestions

GetPreloadSuggestions returns suggested items to preload for a user.

func (*Analyzer) GetStats

func (a *Analyzer) GetStats() *AnalyzerStats

GetStats returns analyzer statistics.

func (*Analyzer) IsPeakHour

func (a *Analyzer) IsPeakHour(ctx context.Context, userID int64) bool

IsPeakHour returns true if current time is a peak hour for the user.

func (*Analyzer) IsQuietHour

func (a *Analyzer) IsQuietHour(ctx context.Context, userID int64) bool

IsQuietHour returns true if current time is a quiet hour for the user.

func (*Analyzer) PredictNextQuery

func (a *Analyzer) PredictNextQuery(ctx context.Context, userID int64, currentQuery string) []string

PredictNextQuery predicts the user's next likely queries.

func (*Analyzer) RecordActivity

func (a *Analyzer) RecordActivity(ctx context.Context, userID int64, activity *Activity) error

RecordActivity records a user activity for pattern analysis.

type AnalyzerStats

type AnalyzerStats struct {
	CachedPatterns int
	MaxCacheSize   int
	TotalSamples   int64
	TotalQueries   int
}

AnalyzerStats contains analyzer statistics.

type Config

type Config struct {
	// Store is the pattern store backend.
	Store PatternStore

	// MaxCacheSize is the maximum patterns to keep in memory.
	MaxCacheSize int

	// TTL is how long cached patterns remain valid.
	TTL time.Duration

	// MinSamples is the minIntimum samples before a pattern is considered valid.
	MinSamples int
}

Config configures the analyzer.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns default analyzer configuration.

type MemoryPatternStore

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

MemoryPatternStore is an in-memory pattern store for testing.

func NewMemoryPatternStore

func NewMemoryPatternStore() *MemoryPatternStore

NewMemoryPatternStore creates a new memory pattern store.

func (*MemoryPatternStore) LoadPattern

func (m *MemoryPatternStore) LoadPattern(ctx context.Context, userID int64) (*UserPattern, error)

LoadPattern loads a pattern from memory.

func (*MemoryPatternStore) SavePattern

func (m *MemoryPatternStore) SavePattern(ctx context.Context, userID int64, pattern *UserPattern) error

SavePattern saves a pattern to memory.

func (*MemoryPatternStore) UpdatePattern

func (m *MemoryPatternStore) UpdatePattern(ctx context.Context, userID int64, pattern *UserPattern) error

UpdatePattern updates a pattern in memory.

type MockPreloader

type MockPreloader struct {
	Calls []struct {
		UserID int64
		Query  string
	}
	// contains filtered or unexported fields
}

MockPreloader is a mock preloader for testing.

func NewMockPreloader

func NewMockPreloader() *MockPreloader

NewMockPreloader creates a new mock preloader.

func (*MockPreloader) Clear

func (m *MockPreloader) Clear()

Clear clears the call history.

func (*MockPreloader) GetCallCount

func (m *MockPreloader) GetCallCount() int

GetCallCount returns the number of preload calls.

func (*MockPreloader) PreloadQuery

func (m *MockPreloader) PreloadQuery(ctx context.Context, userID int64, query string) error

PreloadQuery records the preload call.

func (*MockPreloader) PreloadUserContext

func (m *MockPreloader) PreloadUserContext(ctx context.Context, userID int64) error

PreloadUserContext records the preload call.

type PatternStore

type PatternStore interface {
	// SavePattern saves a user pattern.
	SavePattern(ctx context.Context, userID int64, pattern *UserPattern) error

	// LoadPattern loads a user pattern.
	LoadPattern(ctx context.Context, userID int64) (*UserPattern, error)

	// UpdatePattern updates an existing pattern.
	UpdatePattern(ctx context.Context, userID int64, pattern *UserPattern) error
}

PatternStore persists and retrieves user patterns.

type PreloadSuggestions

type PreloadSuggestions struct {
	UserID         int64
	Timestamp      time.Time
	Queries        []string
	IsPeakHour     bool
	ExpectedTokens int
}

PreloadSuggestions contains items suggested for preloading.

type Preloader

type Preloader interface {
	// PreloadQuery preloads data for a query.
	PreloadQuery(ctx context.Context, userID int64, query string) error

	// PreloadUserContext preloads user context data.
	PreloadUserContext(ctx context.Context, userID int64) error
}

Preloader performs the actual preloading of data.

type QueryPattern

type QueryPattern struct {
	// Query is the search query (may be normalized).
	Query string

	// Frequency is how often this query is used.
	Frequency int

	// LastUsed is when this query was last used.
	LastUsed time.Time

	// AvgTokens is the average tokens used for this query.
	AvgTokens int
}

QueryPattern represents a frequent search query pattern.

type Scheduler

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

Scheduler manages predictive preloading tasks.

func NewScheduler

func NewScheduler(analyzer *Analyzer, preloader Preloader, cfg SchedulerConfig) *Scheduler

NewScheduler creates a new preload scheduler.

func (*Scheduler) GetConfig

func (s *Scheduler) GetConfig() SchedulerConfig

GetConfig returns the current scheduler configuration.

func (*Scheduler) GetScheduledUsers

func (s *Scheduler) GetScheduledUsers() []int64

GetScheduledUsers returns the list of scheduled user IDs.

func (*Scheduler) GetStats

func (s *Scheduler) GetStats() *SchedulerStats

GetStats returns scheduler statistics.

func (*Scheduler) IsRunning

func (s *Scheduler) IsRunning() bool

IsRunning returns true if the scheduler is running.

func (*Scheduler) ScheduleUser

func (s *Scheduler) ScheduleUser(userID int64)

ScheduleUser adds a user to the preload schedule.

func (*Scheduler) Start

func (s *Scheduler) Start()

Start starts the scheduler.

func (*Scheduler) Stop

func (s *Scheduler) Stop()

Stop stops the scheduler.

func (*Scheduler) TriggerPreload

func (s *Scheduler) TriggerPreload(ctx context.Context, userID int64) error

TriggerPreload manually triggers preloading for a user.

func (*Scheduler) UnscheduleUser

func (s *Scheduler) UnscheduleUser(userID int64)

UnscheduleUser removes a user from the preload schedule.

func (*Scheduler) UpdateConfig

func (s *Scheduler) UpdateConfig(cfg SchedulerConfig)

UpdateConfig updates the scheduler configuration.

type SchedulerConfig

type SchedulerConfig struct {
	// AnalysisInterval is how often to analyze patterns.
	AnalysisInterval time.Duration

	// PreloadInterval is how often to perform preloading.
	PreloadInterval time.Duration

	// QuietHours are hours when preloading is paused.
	QuietHours []int // 0-23

	// MaxCPUPercent limits CPU usage for preloading.
	MaxCPUPercent int

	// MaxMemoryMB limits memory usage for preloading.
	MaxMemoryMB int

	// ConcurrentPreloads is the max concurrent preload operations.
	ConcurrentPreloads int
}

SchedulerConfig configures the preload scheduler.

func DefaultSchedulerConfig

func DefaultSchedulerConfig() SchedulerConfig

DefaultSchedulerConfig returns default scheduler configuration.

type SchedulerStats

type SchedulerStats struct {
	ScheduledUsers int
	SuccessCount   int64
	ErrorCount     int64
	Running        bool
	QuietHours     []int
	MaxCPUPercent  int
	MaxMemoryMB    int
}

SchedulerStats contains scheduler statistics.

type UserPattern

type UserPattern struct {
	// UserID is the user's ID.
	UserID int64

	// ActiveHours shows when the user is most active.
	// Each bucket represents an hour of the day (0-23).
	ActiveHours [24]int

	// ActiveDays shows which days of the week the user is active.
	// Each bucket represents a day (0=Sunday, 6=Saturday).
	ActiveDays [7]int

	// FrequentQueries are the user's most common search queries.
	FrequentQueries []*QueryPattern

	// CommonTopics are topics the user frequently searches for.
	CommonTopics []string

	// LastUpdate is when this pattern was last updated.
	LastUpdate time.Time

	// SampleCount is the number of data points used to build this pattern.
	SampleCount int64

	// AvgSessionDuration is the user's average session duration.
	AvgSessionDuration time.Duration

	// PeakHours are the user's peak activity hours.
	PeakHours []int

	// QuietHours are hours when the user is rarely active.
	QuietHours []int
}

UserPattern represents a user's behavioral pattern.

func (*UserPattern) CalculateEntropy

func (p *UserPattern) CalculateEntropy() float64

CalculateEntropy calculates the entropy of the user's activity distribution. Higher entropy means more predictable patterns.

func (*UserPattern) ExportJSON

func (p *UserPattern) ExportJSON() (string, error)

ExportJSON exports the pattern as JSON for debugging.

func (*UserPattern) GetConfidence

func (p *UserPattern) GetConfidence(minIntSamples int) float64

GetConfidence returns a confidence score (0-1) for the pattern. Higher values mean more reliable predictions.

func (*UserPattern) Merge

func (p *UserPattern) Merge(other *UserPattern)

Merge merges another pattern into this one.

Jump to

Keyboard shortcuts

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