Documentation
¶
Overview ¶
Package logstore provides a logs store for Bifrost.
Index ¶
- Constants
- Variables
- func BuildMCPToolTags(l *MCPToolLog) map[string]string
- func BuildTags(l *Log) map[string]string
- func ClearPayload(l *Log)
- func ClearPayloadFiltered(l *Log, excluded map[string]struct{})
- func DimensionColumnDef(d RankingDimension) (idCol, nameCol string, ok bool)
- func ExtractPayload(l *Log) map[string]string
- func ExtractPayloadFiltered(l *Log, excluded map[string]struct{}) map[string]string
- func MCPToolObjectKey(prefix string, timestamp time.Time, logID string) string
- func MarshalMCPToolLogPayload(l *MCPToolLog) ([]byte, error)
- func MarshalPayload(payload map[string]string) ([]byte, error)
- func MergeMCPToolLogPayloadFromJSON(l *MCPToolLog, data []byte) error
- func MergePayloadFromJSON(l *Log, data []byte) error
- func ObjectKey(prefix string, timestamp time.Time, logID string) string
- func PayloadFieldNames() []string
- func PrepareMCPToolDBEntry(l *MCPToolLog)
- type AsyncJob
- type AsyncJobCleaner
- type AsyncJobExecutor
- type AsyncOperation
- type CleanerConfig
- type Config
- type CostHistogramBucket
- type CostHistogramResult
- type DimensionCostHistogramBucket
- type DimensionCostHistogramResult
- type DimensionLatencyHistogramBucket
- type DimensionLatencyHistogramResult
- type DimensionLatencyStats
- type DimensionRankingEntry
- type DimensionRankingResult
- type DimensionRankingTrend
- type DimensionRankingWithTrend
- type DimensionTokenHistogramBucket
- type DimensionTokenHistogramResult
- type DimensionTokenStats
- type GovernanceStore
- type HistogramBucket
- type HistogramDimension
- type HistogramResult
- type HybridLogStore
- func (h *HybridLogStore) BatchCreateIfNotExists(ctx context.Context, entries []*Log) error
- func (h *HybridLogStore) BatchCreateMCPToolLogsIfNotExists(ctx context.Context, entries []*MCPToolLog) error
- func (h *HybridLogStore) BulkUpdateCost(ctx context.Context, updates map[string]float64) error
- func (h *HybridLogStore) Close(ctx context.Context) error
- func (h *HybridLogStore) Create(ctx context.Context, entry *Log) error
- func (h *HybridLogStore) CreateAsyncJob(ctx context.Context, job *AsyncJob) error
- func (h *HybridLogStore) CreateIfNotExists(ctx context.Context, entry *Log) error
- func (h *HybridLogStore) CreateMCPToolLog(ctx context.Context, entry *MCPToolLog) error
- func (h *HybridLogStore) DeleteExpiredAsyncJobs(ctx context.Context) (int64, error)
- func (h *HybridLogStore) DeleteLog(ctx context.Context, id string) error
- func (h *HybridLogStore) DeleteLogs(ctx context.Context, ids []string) error
- func (h *HybridLogStore) DeleteLogsBatch(ctx context.Context, cutoff time.Time, batchSize int) (int64, error)
- func (h *HybridLogStore) DeleteMCPToolLogs(ctx context.Context, ids []string) error
- func (h *HybridLogStore) DeleteStaleAsyncJobs(ctx context.Context, staleSince time.Time) (int64, error)
- func (h *HybridLogStore) DroppedUploads() int64
- func (h *HybridLogStore) FindAll(ctx context.Context, query any, fields ...string) ([]*Log, error)
- func (h *HybridLogStore) FindAllDistinct(ctx context.Context, query any, fields ...string) ([]*Log, error)
- func (h *HybridLogStore) FindAsyncJobByID(ctx context.Context, id string) (*AsyncJob, error)
- func (h *HybridLogStore) FindByID(ctx context.Context, id string) (*Log, error)
- func (h *HybridLogStore) FindFirst(ctx context.Context, query any, fields ...string) (*Log, error)
- func (h *HybridLogStore) FindMCPToolLog(ctx context.Context, id string) (*MCPToolLog, error)
- func (h *HybridLogStore) Flush(ctx context.Context, since time.Time) error
- func (h *HybridLogStore) FlushMCPToolLogs(ctx context.Context, since time.Time) error
- func (h *HybridLogStore) GetAvailableMCPVirtualKeys(ctx context.Context, limit int, query string) ([]MCPToolLog, error)
- func (h *HybridLogStore) GetAvailableServerLabels(ctx context.Context, limit int, query string) ([]string, error)
- func (h *HybridLogStore) GetAvailableToolNames(ctx context.Context, limit int, query string) ([]string, error)
- func (h *HybridLogStore) GetCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*CostHistogramResult, error)
- func (h *HybridLogStore) GetDimensionCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, ...) (*DimensionCostHistogramResult, error)
- func (h *HybridLogStore) GetDimensionLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, ...) (*DimensionLatencyHistogramResult, error)
- func (h *HybridLogStore) GetDimensionRankings(ctx context.Context, filters SearchFilters, dimension RankingDimension) (*DimensionRankingResult, error)
- func (h *HybridLogStore) GetDimensionTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, ...) (*DimensionTokenHistogramResult, error)
- func (h *HybridLogStore) GetDistinctAliases(ctx context.Context, limit int, query string) ([]string, error)
- func (h *HybridLogStore) GetDistinctKeyPairs(ctx context.Context, idCol, nameCol string, limit int, query string) ([]KeyPairResult, error)
- func (h *HybridLogStore) GetDistinctMetadataKeys(ctx context.Context, limit int, query string) (map[string][]string, error)
- func (h *HybridLogStore) GetDistinctModels(ctx context.Context, limit int, query string) ([]string, error)
- func (h *HybridLogStore) GetDistinctRoutingEngines(ctx context.Context, limit int, query string) ([]string, error)
- func (h *HybridLogStore) GetDistinctStopReasons(ctx context.Context, limit int, query string) ([]string, error)
- func (h *HybridLogStore) GetHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*HistogramResult, error)
- func (h *HybridLogStore) GetLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*LatencyHistogramResult, error)
- func (h *HybridLogStore) GetMCPCostHistogram(ctx context.Context, filters MCPToolLogSearchFilters, bucketSizeSeconds int64) (*MCPCostHistogramResult, error)
- func (h *HybridLogStore) GetMCPHistogram(ctx context.Context, filters MCPToolLogSearchFilters, bucketSizeSeconds int64) (*MCPHistogramResult, error)
- func (h *HybridLogStore) GetMCPToolLogStats(ctx context.Context, filters MCPToolLogSearchFilters) (*MCPToolLogStats, error)
- func (h *HybridLogStore) GetMCPTopTools(ctx context.Context, filters MCPToolLogSearchFilters, limit int) (*MCPTopToolsResult, error)
- func (h *HybridLogStore) GetModelHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ModelHistogramResult, error)
- func (h *HybridLogStore) GetModelRankings(ctx context.Context, filters SearchFilters) (*ModelRankingResult, error)
- func (h *HybridLogStore) GetNodeUsageAfter(ctx context.Context, nodeID string, cursor NodeUsageCursor) (*NodeUsageAggregate, error)
- func (h *HybridLogStore) GetProviderCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderCostHistogramResult, error)
- func (h *HybridLogStore) GetProviderLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderLatencyHistogramResult, error)
- func (h *HybridLogStore) GetProviderTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderTokenHistogramResult, error)
- func (h *HybridLogStore) GetSessionLogs(ctx context.Context, sessionID string, pagination PaginationOptions) (*SessionDetailResult, error)
- func (h *HybridLogStore) GetSessionSummary(ctx context.Context, sessionID string) (*SessionSummaryResult, error)
- func (h *HybridLogStore) GetStats(ctx context.Context, filters SearchFilters) (*SearchStats, error)
- func (h *HybridLogStore) GetTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*TokenHistogramResult, error)
- func (h *HybridLogStore) GetUserRankings(ctx context.Context, filters SearchFilters) (*UserRankingResult, error)
- func (h *HybridLogStore) HasLogs(ctx context.Context) (bool, error)
- func (h *HybridLogStore) HasMCPToolLogs(ctx context.Context) (bool, error)
- func (h *HybridLogStore) IsLogEntryPresent(ctx context.Context, id string) (bool, error)
- func (h *HybridLogStore) Ping(ctx context.Context) error
- func (h *HybridLogStore) SearchLogs(ctx context.Context, filters SearchFilters, pagination PaginationOptions) (*SearchResult, error)
- func (h *HybridLogStore) SearchMCPToolLogs(ctx context.Context, filters MCPToolLogSearchFilters, ...) (*MCPToolLogSearchResult, error)
- func (h *HybridLogStore) Update(ctx context.Context, id string, entry any) error
- func (h *HybridLogStore) UpdateAsyncJob(ctx context.Context, id string, updates map[string]interface{}) error
- func (h *HybridLogStore) UpdateMCPToolLog(ctx context.Context, id string, entry any) error
- type KeyPairResult
- type LatencyHistogramBucket
- type LatencyHistogramResult
- type Log
- type LogRetentionManager
- type LogStore
- type LogStoreType
- type LogsCleaner
- type MCPCostHistogramBucket
- type MCPCostHistogramResult
- type MCPHistogramBucket
- type MCPHistogramResult
- type MCPToolLog
- type MCPToolLogSearchFilters
- type MCPToolLogSearchResult
- type MCPToolLogStats
- type MCPTopToolResult
- type MCPTopToolsResult
- type ModelHistogramBucket
- type ModelHistogramResult
- type ModelRankingEntry
- type ModelRankingResult
- type ModelRankingTrend
- type ModelRankingWithTrend
- type ModelUsageStats
- type NodeUsageAggregate
- type NodeUsageCursor
- type PaginationOptions
- type PostgresConfig
- type ProviderCostHistogramBucket
- type ProviderCostHistogramResult
- type ProviderLatencyHistogramBucket
- type ProviderLatencyHistogramResult
- type ProviderLatencyStats
- type ProviderTokenHistogramBucket
- type ProviderTokenHistogramResult
- type ProviderTokenStats
- type RDBLogStore
- func (s *RDBLogStore) BatchCreateIfNotExists(ctx context.Context, entries []*Log) error
- func (s *RDBLogStore) BatchCreateMCPToolLogsIfNotExists(ctx context.Context, entries []*MCPToolLog) error
- func (s *RDBLogStore) BulkUpdateCost(ctx context.Context, updates map[string]float64) error
- func (s *RDBLogStore) Close(ctx context.Context) error
- func (s *RDBLogStore) Create(ctx context.Context, entry *Log) error
- func (s *RDBLogStore) CreateAsyncJob(ctx context.Context, job *AsyncJob) error
- func (s *RDBLogStore) CreateIfNotExists(ctx context.Context, entry *Log) error
- func (s *RDBLogStore) CreateMCPToolLog(ctx context.Context, entry *MCPToolLog) error
- func (s *RDBLogStore) DeleteExpiredAsyncJobs(ctx context.Context) (int64, error)
- func (s *RDBLogStore) DeleteLog(ctx context.Context, id string) error
- func (s *RDBLogStore) DeleteLogs(ctx context.Context, ids []string) error
- func (s *RDBLogStore) DeleteLogsBatch(ctx context.Context, cutoff time.Time, batchSize int) (deletedCount int64, err error)
- func (s *RDBLogStore) DeleteMCPToolLogs(ctx context.Context, ids []string) error
- func (s *RDBLogStore) DeleteStaleAsyncJobs(ctx context.Context, staleSince time.Time) (int64, error)
- func (s *RDBLogStore) FindAll(ctx context.Context, query any, fields ...string) ([]*Log, error)
- func (s *RDBLogStore) FindAllDistinct(ctx context.Context, query any, fields ...string) ([]*Log, error)
- func (s *RDBLogStore) FindAsyncJobByID(ctx context.Context, id string) (*AsyncJob, error)
- func (s *RDBLogStore) FindByID(ctx context.Context, id string) (*Log, error)
- func (s *RDBLogStore) FindFirst(ctx context.Context, query any, fields ...string) (*Log, error)
- func (s *RDBLogStore) FindMCPToolLog(ctx context.Context, id string) (*MCPToolLog, error)
- func (s *RDBLogStore) Flush(ctx context.Context, since time.Time) error
- func (s *RDBLogStore) FlushMCPToolLogs(ctx context.Context, since time.Time) error
- func (s *RDBLogStore) GetAvailableMCPVirtualKeys(ctx context.Context, limit int, query string) ([]MCPToolLog, error)
- func (s *RDBLogStore) GetAvailableServerLabels(ctx context.Context, limit int, query string) ([]string, error)
- func (s *RDBLogStore) GetAvailableToolNames(ctx context.Context, limit int, query string) ([]string, error)
- func (s *RDBLogStore) GetCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*CostHistogramResult, error)
- func (s *RDBLogStore) GetDimensionCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, ...) (*DimensionCostHistogramResult, error)
- func (s *RDBLogStore) GetDimensionLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, ...) (*DimensionLatencyHistogramResult, error)
- func (s *RDBLogStore) GetDimensionRankings(ctx context.Context, filters SearchFilters, dimension RankingDimension) (*DimensionRankingResult, error)
- func (s *RDBLogStore) GetDimensionTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, ...) (*DimensionTokenHistogramResult, error)
- func (s *RDBLogStore) GetDistinctAliases(ctx context.Context, limit int, query string) ([]string, error)
- func (s *RDBLogStore) GetDistinctKeyPairs(ctx context.Context, idCol, nameCol string, limit int, query string) ([]KeyPairResult, error)
- func (s *RDBLogStore) GetDistinctMetadataKeys(ctx context.Context, limit int, query string) (map[string][]string, error)
- func (s *RDBLogStore) GetDistinctModels(ctx context.Context, limit int, query string) ([]string, error)
- func (s *RDBLogStore) GetDistinctRoutingEngines(ctx context.Context, limit int, query string) ([]string, error)
- func (s *RDBLogStore) GetDistinctStopReasons(ctx context.Context, limit int, query string) ([]string, error)
- func (s *RDBLogStore) GetHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*HistogramResult, error)
- func (s *RDBLogStore) GetLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*LatencyHistogramResult, error)
- func (s *RDBLogStore) GetMCPCostHistogram(ctx context.Context, filters MCPToolLogSearchFilters, bucketSizeSeconds int64) (*MCPCostHistogramResult, error)
- func (s *RDBLogStore) GetMCPHistogram(ctx context.Context, filters MCPToolLogSearchFilters, bucketSizeSeconds int64) (*MCPHistogramResult, error)
- func (s *RDBLogStore) GetMCPToolLogStats(ctx context.Context, filters MCPToolLogSearchFilters) (*MCPToolLogStats, error)
- func (s *RDBLogStore) GetMCPTopTools(ctx context.Context, filters MCPToolLogSearchFilters, limit int) (*MCPTopToolsResult, error)
- func (s *RDBLogStore) GetModelHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ModelHistogramResult, error)
- func (s *RDBLogStore) GetModelRankings(ctx context.Context, filters SearchFilters) (*ModelRankingResult, error)
- func (s *RDBLogStore) GetNodeUsageAfter(ctx context.Context, nodeID string, cursor NodeUsageCursor) (*NodeUsageAggregate, error)
- func (s *RDBLogStore) GetProviderCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderCostHistogramResult, error)
- func (s *RDBLogStore) GetProviderLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderLatencyHistogramResult, error)
- func (s *RDBLogStore) GetProviderTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderTokenHistogramResult, error)
- func (s *RDBLogStore) GetSessionLogs(ctx context.Context, sessionID string, pagination PaginationOptions) (*SessionDetailResult, error)
- func (s *RDBLogStore) GetSessionSummary(ctx context.Context, sessionID string) (*SessionSummaryResult, error)
- func (s *RDBLogStore) GetStats(ctx context.Context, filters SearchFilters) (*SearchStats, error)
- func (s *RDBLogStore) GetTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*TokenHistogramResult, error)
- func (s *RDBLogStore) GetUserRankings(ctx context.Context, filters SearchFilters) (*UserRankingResult, error)
- func (s *RDBLogStore) HasLogs(ctx context.Context) (bool, error)
- func (s *RDBLogStore) HasMCPToolLogs(ctx context.Context) (bool, error)
- func (s *RDBLogStore) IsLogEntryPresent(ctx context.Context, id string) (bool, error)
- func (s *RDBLogStore) Ping(ctx context.Context) error
- func (s *RDBLogStore) ScopedDB(ctx context.Context) *gorm.DB
- func (s *RDBLogStore) SearchLogs(ctx context.Context, filters SearchFilters, pagination PaginationOptions) (*SearchResult, error)
- func (s *RDBLogStore) SearchMCPToolLogs(ctx context.Context, filters MCPToolLogSearchFilters, ...) (*MCPToolLogSearchResult, error)
- func (s *RDBLogStore) Update(ctx context.Context, id string, entry any) error
- func (s *RDBLogStore) UpdateAsyncJob(ctx context.Context, id string, updates map[string]interface{}) error
- func (s *RDBLogStore) UpdateMCPToolLog(ctx context.Context, id string, entry any) error
- type RankingDimension
- type SQLiteConfig
- type SearchFilters
- type SearchResult
- type SearchStats
- type SessionDetailResult
- type SessionSummaryResult
- type SortBy
- type SortOrder
- type TokenHistogramBucket
- type TokenHistogramResult
- type UserRankingEntry
- type UserRankingResult
- type UserRankingTrend
- type UserRankingWithTrend
Constants ¶
const (
// DefaultAsyncJobResultTTL is the default TTL for async job results in seconds (1 hour).
DefaultAsyncJobResultTTL = 3600
)
Variables ¶
var ( ErrNotFound = fmt.Errorf("log not found") ErrJobInternal = fmt.Errorf("internal job store error") )
var ValidHistogramDimensions = map[HistogramDimension]bool{ DimensionProvider: true, DimensionTeam: true, DimensionCustomer: true, DimensionUser: true, DimensionBusinessUnit: true, }
ValidHistogramDimensions is the set of allowed dimension values
var ValidRankingDimensions = map[RankingDimension]bool{ RankingDimensionTeam: true, RankingDimensionCustomer: true, RankingDimensionBusinessUnit: true, RankingDimensionUser: true, }
Functions ¶
func BuildMCPToolTags ¶ added in v1.3.9
func BuildMCPToolTags(l *MCPToolLog) map[string]string
BuildMCPToolTags creates the object tag map from an MCP tool log's index fields. S3 allows max 10 tags per object.
func BuildTags ¶ added in v1.3.2
BuildTags creates the S3 object tag map from a Log's index fields. S3 allows max 10 tags per object; chosen for lifecycle rules and S3 Metadata Tables queryability.
func ClearPayload ¶ added in v1.3.2
func ClearPayload(l *Log)
ClearPayload zeros out both the TEXT payload columns and the Parsed virtual fields on a Log struct. Clearing the Parsed fields is necessary to prevent GORM's BeforeCreate/SerializeFields from re-populating TEXT columns. After calling this, the struct only contains index-weight data suitable for a lightweight DB INSERT.
func ClearPayloadFiltered ¶ added in v1.3.7
ClearPayloadFiltered zeros only the payload fields that are not present in the excluded set (i.e. the fields that will be sent to object storage). Fields in the excluded set stay in the DB and are left untouched. An empty/nil excluded map is equivalent to ClearPayload.
func DimensionColumnDef ¶ added in v1.3.14
func DimensionColumnDef(d RankingDimension) (idCol, nameCol string, ok bool)
func ExtractPayload ¶ added in v1.3.2
ExtractPayload reads the serialized TEXT payload fields from a Log into a map. The map keys are the DB column names.
func ExtractPayloadFiltered ¶ added in v1.3.7
ExtractPayloadFiltered is like ExtractPayload but omits fields present in the excluded set. An empty/nil excluded map is equivalent to ExtractPayload.
func MCPToolObjectKey ¶ added in v1.3.9
MCPToolObjectKey constructs the S3 object key for an MCP tool log entry.
func MarshalMCPToolLogPayload ¶ added in v1.3.9
func MarshalMCPToolLogPayload(l *MCPToolLog) ([]byte, error)
MarshalMCPToolLogPayload serializes a full MCP tool log for object storage. The object-store copy is intentionally complete; the DB row is only a lightweight index plus a short input preview.
func MarshalPayload ¶ added in v1.3.2
func MergeMCPToolLogPayloadFromJSON ¶ added in v1.3.9
func MergeMCPToolLogPayloadFromJSON(l *MCPToolLog, data []byte) error
MergeMCPToolLogPayloadFromJSON replaces an MCP tool log with the full object storage copy while preserving DB-local hydration state.
func MergePayloadFromJSON ¶ added in v1.3.2
MergePayloadFromJSON takes a JSON payload (as marshaled by MarshalPayload) and merges the fields back into the Log struct's serialized TEXT columns, then calls DeserializeFields to populate the Parsed virtual fields.
func PayloadFieldNames ¶ added in v1.3.2
func PayloadFieldNames() []string
PayloadFieldNames returns the list of DB column names that are payload fields.
func PrepareMCPToolDBEntry ¶ added in v1.3.9
func PrepareMCPToolDBEntry(l *MCPToolLog)
PrepareMCPToolDBEntry converts an MCP tool log to the lightweight DB form used by hybrid storage. It preserves indexed/display fields and metadata, keeps only a 200-character JSON-string argument preview, and clears result and error payloads.
Types ¶
type AsyncJob ¶ added in v1.2.22
type AsyncJob struct {
ID string `gorm:"primaryKey;type:varchar(255)" json:"id"`
Status schemas.AsyncJobStatus `gorm:"type:varchar(50);index:idx_async_jobs_status;not null" json:"status"`
RequestType schemas.RequestType `gorm:"type:varchar(50);index:idx_async_jobs_request_type;not null" json:"request_type"`
Response string `gorm:"type:text" json:"response"`
StatusCode int `gorm:"default:0" json:"status_code,omitempty"`
Error string `gorm:"type:text" json:"error,omitempty"`
VirtualKeyID *string `gorm:"type:varchar(255);index:idx_async_jobs_vk_id" json:"virtual_key_id,omitempty"`
ResultTTL int `gorm:"default:3600" json:"-"` // TTL in seconds, used to calculate ExpiresAt on completion
ExpiresAt *time.Time `gorm:"index:idx_async_jobs_expires_at" json:"expires_at,omitempty"`
CreatedAt time.Time `gorm:"index;not null" json:"created_at"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
}
AsyncJob represents an asynchronous job record in the database. Jobs are created when requests are submitted to async endpoints and updated when the background operation completes or fails.
func (*AsyncJob) ToResponse ¶ added in v1.2.22
func (j *AsyncJob) ToResponse() *schemas.AsyncJobResponse
ToResponse converts an AsyncJob database record to an AsyncJobResponse for JSON output.
type AsyncJobCleaner ¶ added in v1.2.22
type AsyncJobCleaner struct {
// contains filtered or unexported fields
}
AsyncJobCleaner manages the cleanup of expired async jobs.
func NewAsyncJobCleaner ¶ added in v1.2.22
func NewAsyncJobCleaner(store LogStore, logger schemas.Logger) *AsyncJobCleaner
NewAsyncJobCleaner creates a new AsyncJobCleaner instance.
func (*AsyncJobCleaner) StartCleanupRoutine ¶ added in v1.2.22
func (c *AsyncJobCleaner) StartCleanupRoutine()
StartCleanupRoutine starts a goroutine that periodically cleans up expired async jobs.
func (*AsyncJobCleaner) StopCleanupRoutine ¶ added in v1.2.22
func (c *AsyncJobCleaner) StopCleanupRoutine()
StopCleanupRoutine gracefully stops the cleanup goroutine.
type AsyncJobExecutor ¶ added in v1.2.22
type AsyncJobExecutor struct {
// contains filtered or unexported fields
}
AsyncJobExecutor manages async job creation and background execution.
func NewAsyncJobExecutor ¶ added in v1.2.22
func NewAsyncJobExecutor(logstore LogStore, governanceStore GovernanceStore, logger schemas.Logger) *AsyncJobExecutor
NewAsyncJobExecutor creates a new AsyncJobExecutor.
func (*AsyncJobExecutor) RetrieveJob ¶ added in v1.2.22
func (e *AsyncJobExecutor) RetrieveJob(ctx context.Context, jobID string, vkValue *string, operationType schemas.RequestType) (*AsyncJob, error)
RetrieveJob retrieves a job by its ID.
func (*AsyncJobExecutor) SubmitJob ¶ added in v1.2.22
func (e *AsyncJobExecutor) SubmitJob(bifrostCtx *schemas.BifrostContext, resultTTL int, operation AsyncOperation, operationType schemas.RequestType) (*AsyncJob, error)
SubmitJob creates a pending job, starts background execution, and returns the job record.
type AsyncOperation ¶ added in v1.2.22
type AsyncOperation func(ctx *schemas.BifrostContext) (any, *schemas.BifrostError)
AsyncOperation represents a function that can be executed asynchronously. It returns the response and an optional BifrostError.
type CleanerConfig ¶ added in v1.1.36
type CleanerConfig struct {
RetentionDays int
}
CleanerConfig holds configuration for the log cleaner
type Config ¶
type Config struct {
Enabled bool `json:"enabled"`
Type LogStoreType `json:"type"`
RetentionDays int `json:"retention_days"`
Config any `json:"config"`
ObjectStorage *objectstore.Config `json:"object_storage,omitempty"`
// ObjectStorageExcludeFields lists payload field names (DB column names) that
// should NOT be offloaded to object storage and instead remain in the database.
ObjectStorageExcludeFields []string `json:"object_storage_exclude_fields,omitempty"`
}
Config represents the configuration for the logs store.
func (*Config) UnmarshalJSON ¶
UnmarshalJSON is the custom unmarshal logic for Config
type CostHistogramBucket ¶ added in v1.2.13
type CostHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
TotalCost float64 `json:"total_cost"`
ByModel map[string]float64 `json:"by_model"`
}
CostHistogramBucket represents a single time bucket for cost data
type CostHistogramResult ¶ added in v1.2.13
type CostHistogramResult struct {
Buckets []CostHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
Models []string `json:"models"`
}
CostHistogramResult represents the cost histogram query result
type DimensionCostHistogramBucket ¶ added in v1.3.1
type DimensionCostHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
TotalCost float64 `json:"total_cost"`
ByDimension map[string]float64 `json:"by_dimension"`
}
DimensionCostHistogramBucket represents a single time bucket for dimension-grouped cost data
type DimensionCostHistogramResult ¶ added in v1.3.1
type DimensionCostHistogramResult struct {
Buckets []DimensionCostHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
Dimension HistogramDimension `json:"dimension"`
DimensionValues []string `json:"dimension_values"`
}
DimensionCostHistogramResult represents the dimension cost histogram query result
type DimensionLatencyHistogramBucket ¶ added in v1.3.1
type DimensionLatencyHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
ByDimension map[string]DimensionLatencyStats `json:"by_dimension"`
}
DimensionLatencyHistogramBucket represents a single time bucket for dimension-grouped latency data
type DimensionLatencyHistogramResult ¶ added in v1.3.1
type DimensionLatencyHistogramResult struct {
Buckets []DimensionLatencyHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
Dimension HistogramDimension `json:"dimension"`
DimensionValues []string `json:"dimension_values"`
}
DimensionLatencyHistogramResult represents the dimension latency histogram query result
type DimensionLatencyStats ¶ added in v1.3.1
type DimensionLatencyStats struct {
AvgLatency float64 `json:"avg_latency"`
P90Latency float64 `json:"p90_latency"`
P95Latency float64 `json:"p95_latency"`
P99Latency float64 `json:"p99_latency"`
TotalRequests int64 `json:"total_requests"`
}
DimensionLatencyStats represents latency statistics for a single dimension value
type DimensionRankingEntry ¶ added in v1.3.14
type DimensionRankingResult ¶ added in v1.3.14
type DimensionRankingResult struct {
Rankings []DimensionRankingWithTrend `json:"rankings"`
Dimension RankingDimension `json:"dimension"`
// TotalActualRequests / TotalAttributedRequests are only set for fan-out
// dimensions (team / business unit / customer) on Postgres. Attributed
// counts credit a request to every dimension value it touches, so their
// sum can exceed the real request count; actual is COUNT(DISTINCT id)
// over the same attributed population. Zero/omitted when not computed.
TotalActualRequests int64 `json:"total_actual_requests,omitempty"`
TotalAttributedRequests int64 `json:"total_attributed_requests,omitempty"`
}
type DimensionRankingTrend ¶ added in v1.3.14
type DimensionRankingWithTrend ¶ added in v1.3.14
type DimensionRankingWithTrend struct {
DimensionRankingEntry
Trend DimensionRankingTrend `json:"trend"`
}
type DimensionTokenHistogramBucket ¶ added in v1.3.1
type DimensionTokenHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
ByDimension map[string]DimensionTokenStats `json:"by_dimension"`
}
DimensionTokenHistogramBucket represents a single time bucket for dimension-grouped token data
type DimensionTokenHistogramResult ¶ added in v1.3.1
type DimensionTokenHistogramResult struct {
Buckets []DimensionTokenHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
Dimension HistogramDimension `json:"dimension"`
DimensionValues []string `json:"dimension_values"`
}
DimensionTokenHistogramResult represents the dimension token histogram query result
type DimensionTokenStats ¶ added in v1.3.1
type DimensionTokenStats struct {
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
TotalTokens int64 `json:"total_tokens"`
}
DimensionTokenStats represents token statistics for a single dimension value
type GovernanceStore ¶ added in v1.2.22
type GovernanceStore interface {
GetVirtualKey(ctx context.Context, vkValue string) (*configstoreTables.TableVirtualKey, bool)
}
GovernanceStore is an interface that provides access to the governance store.
type HistogramBucket ¶ added in v1.2.13
type HistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
Count int64 `json:"count"`
Success int64 `json:"success"`
Error int64 `json:"error"`
}
HistogramBucket represents a single time bucket in the histogram
type HistogramDimension ¶ added in v1.3.1
type HistogramDimension string
HistogramDimension represents a column that can be used as a grouping dimension in histograms
const ( DimensionProvider HistogramDimension = "provider" DimensionTeam HistogramDimension = "team_id" DimensionCustomer HistogramDimension = "customer_id" DimensionUser HistogramDimension = "user_id" DimensionBusinessUnit HistogramDimension = "business_unit_id" )
type HistogramResult ¶ added in v1.2.13
type HistogramResult struct {
Buckets []HistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
}
HistogramResult represents the histogram query result
type HybridLogStore ¶ added in v1.3.2
type HybridLogStore struct {
// contains filtered or unexported fields
}
HybridLogStore wraps an existing LogStore and offloads large payload fields to object storage while keeping a lightweight index in the DB.
Method routing:
- Delegated directly (40+ methods): all analytics, search, histogram, ranking, distinct, MCP, async job methods
- Intercepted: Create, CreateIfNotExists, BatchCreateIfNotExists, FindByID, Update, DeleteLog, DeleteLogs, DeleteLogsBatch, Close
func (*HybridLogStore) BatchCreateIfNotExists ¶ added in v1.3.2
func (h *HybridLogStore) BatchCreateIfNotExists(ctx context.Context, entries []*Log) error
BatchCreateIfNotExists inserts many lightweight DB rows in a single inner call, then enqueues one object-storage upload per inserted entry. Nil entries are skipped. On DB failure no uploads are enqueued.
func (*HybridLogStore) BatchCreateMCPToolLogsIfNotExists ¶ added in v1.3.9
func (h *HybridLogStore) BatchCreateMCPToolLogsIfNotExists(ctx context.Context, entries []*MCPToolLog) error
BatchCreateMCPToolLogsIfNotExists creates MCP tool logs in the DB and enqueues them for offload to object storage, if they do not already exist.
func (*HybridLogStore) BulkUpdateCost ¶ added in v1.3.2
BulkUpdateCost delegates to the inner store and updates the cost column for each (logID -> cost) pair in a single round trip.
func (*HybridLogStore) Close ¶ added in v1.3.2
func (h *HybridLogStore) Close(ctx context.Context) error
Close shuts the store down cleanly: marks the store closed (so further enqueues are dropped), closes the upload queue, waits for workers to drain any in-flight uploads, then closes the object store and the inner store. If ctx is cancelled before workers drain, the cancellation is logged but Close still waits for workers to exit to avoid closing dependencies mid-flight.
func (*HybridLogStore) Create ¶ added in v1.3.2
func (h *HybridLogStore) Create(ctx context.Context, entry *Log) error
Create writes a lightweight DB row (with payload fields stripped per excludedPayloadFields) and asynchronously offloads the full payload to object storage. The caller's entry is preserved on DB failure by writing to a shallow copy; on success, only ContentSummary is propagated back so the caller can observe what was persisted.
func (*HybridLogStore) CreateAsyncJob ¶ added in v1.3.2
func (h *HybridLogStore) CreateAsyncJob(ctx context.Context, job *AsyncJob) error
CreateAsyncJob creates a new async job.
func (*HybridLogStore) CreateIfNotExists ¶ added in v1.3.2
func (h *HybridLogStore) CreateIfNotExists(ctx context.Context, entry *Log) error
CreateIfNotExists writes the lightweight DB row only when no row with the same ID exists, then offloads the full payload to object storage on insert. Same payload-stripping and shallow-copy semantics as Create.
func (*HybridLogStore) CreateMCPToolLog ¶ added in v1.3.2
func (h *HybridLogStore) CreateMCPToolLog(ctx context.Context, entry *MCPToolLog) error
CreateMCPToolLog creates a new MCP tool log in the DB and enqueues it for offload to object storage.
func (*HybridLogStore) DeleteExpiredAsyncJobs ¶ added in v1.3.2
func (h *HybridLogStore) DeleteExpiredAsyncJobs(ctx context.Context) (int64, error)
DeleteExpiredAsyncJobs deletes async jobs that have not been updated since the given time.
func (*HybridLogStore) DeleteLog ¶ added in v1.3.2
func (h *HybridLogStore) DeleteLog(ctx context.Context, id string) error
DeleteLog removes a single log row from the DB and, when HasObject is true, also deletes the corresponding payload from object storage. Object-store delete failures are logged but do not fail the operation, since the DB row (the source of truth for visibility) is already gone.
func (*HybridLogStore) DeleteLogs ¶ added in v1.3.2
func (h *HybridLogStore) DeleteLogs(ctx context.Context, ids []string) error
DeleteLogs removes many log rows from the DB and batches a single DeleteBatch call against object storage for any rows that had HasObject set. Keys are collected before the DB delete so we can still identify object-store entries to clean up.
func (*HybridLogStore) DeleteLogsBatch ¶ added in v1.3.2
func (h *HybridLogStore) DeleteLogsBatch(ctx context.Context, cutoff time.Time, batchSize int) (int64, error)
DeleteLogsBatch deletes old DB rows older than cutoff in batches of batchSize. Object-store entries are intentionally NOT deleted here: the expectation is that the bucket has a lifecycle policy configured to expire objects on the same schedule, which is far cheaper than per-row DELETEs.
func (*HybridLogStore) DeleteMCPToolLogs ¶ added in v1.3.2
func (h *HybridLogStore) DeleteMCPToolLogs(ctx context.Context, ids []string) error
DeleteMCPToolLogs deletes MCP tool logs with the given IDs, including any associated object storage objects.
func (*HybridLogStore) DeleteStaleAsyncJobs ¶ added in v1.3.2
func (h *HybridLogStore) DeleteStaleAsyncJobs(ctx context.Context, staleSince time.Time) (int64, error)
DeleteStaleAsyncJobs deletes async jobs that have not been updated since the given time.
func (*HybridLogStore) DroppedUploads ¶ added in v1.3.2
func (h *HybridLogStore) DroppedUploads() int64
DroppedUploads returns the number of S3 uploads that were dropped.
func (*HybridLogStore) FindAll ¶ added in v1.3.2
FindAll returns all logs matching query. Each result is hydrated from object storage when the projection requires payload fields. Per-row hydration failures are logged inside hydrateLog and do not fail the call.
func (*HybridLogStore) FindAllDistinct ¶ added in v1.3.2
func (h *HybridLogStore) FindAllDistinct(ctx context.Context, query any, fields ...string) ([]*Log, error)
FindAllDistinct delegates to the inner store. No hydration is performed: distinct queries operate purely on DB-resident columns and never need the offloaded payload.
func (*HybridLogStore) FindAsyncJobByID ¶ added in v1.3.2
FindAsyncJobByID finds an async job by its ID.
func (*HybridLogStore) FindByID ¶ added in v1.3.2
FindByID loads a log row from the DB and hydrates its payload fields from object storage when HasObject is true. Object-store fetch failures are logged but not returned, so the caller still receives the DB row.
func (*HybridLogStore) FindFirst ¶ added in v1.3.2
FindFirst returns the first log matching query. When the projection asks for payload-bearing fields (or the projection is empty, implying full hydration), the result is hydrated from object storage; otherwise the DB row is returned as-is.
func (*HybridLogStore) FindMCPToolLog ¶ added in v1.3.2
func (h *HybridLogStore) FindMCPToolLog(ctx context.Context, id string) (*MCPToolLog, error)
FindMCPToolLog finds an MCP tool log by its ID and hydrates it with any associated object storage data.
func (*HybridLogStore) Flush ¶ added in v1.3.2
Flush delegates to the inner store and forces any buffered DB writes since the given timestamp to be persisted. Object-store uploads are independently queued and not affected.
func (*HybridLogStore) FlushMCPToolLogs ¶ added in v1.3.2
FlushMCPToolLogs flushes MCP tool logs that are older than the given time.
func (*HybridLogStore) GetAvailableMCPVirtualKeys ¶ added in v1.3.2
func (h *HybridLogStore) GetAvailableMCPVirtualKeys(ctx context.Context, limit int, query string) ([]MCPToolLog, error)
GetAvailableMCPVirtualKeys returns a list of MCP tool log virtual keys that match the given query.
func (*HybridLogStore) GetAvailableServerLabels ¶ added in v1.3.2
func (h *HybridLogStore) GetAvailableServerLabels(ctx context.Context, limit int, query string) ([]string, error)
GetAvailableServerLabels returns a list of server labels that match the given query.
func (*HybridLogStore) GetAvailableToolNames ¶ added in v1.3.2
func (h *HybridLogStore) GetAvailableToolNames(ctx context.Context, limit int, query string) ([]string, error)
GetAvailableToolNames returns a list of tool names that match the given query.
func (*HybridLogStore) GetCostHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*CostHistogramResult, error)
GetCostHistogram delegates to the inner store and returns a cost histogram bucketed by bucketSizeSeconds.
func (*HybridLogStore) GetDimensionCostHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetDimensionCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, dimension HistogramDimension) (*DimensionCostHistogramResult, error)
GetDimensionCostHistogram delegates to the inner store and returns a cost histogram bucketed by bucketSizeSeconds and grouped by the given dimension.
func (*HybridLogStore) GetDimensionLatencyHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetDimensionLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, dimension HistogramDimension) (*DimensionLatencyHistogramResult, error)
GetDimensionLatencyHistogram delegates to the inner store and returns a latency histogram bucketed by bucketSizeSeconds and grouped by the given dimension.
func (*HybridLogStore) GetDimensionRankings ¶ added in v1.3.14
func (h *HybridLogStore) GetDimensionRankings(ctx context.Context, filters SearchFilters, dimension RankingDimension) (*DimensionRankingResult, error)
func (*HybridLogStore) GetDimensionTokenHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetDimensionTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, dimension HistogramDimension) (*DimensionTokenHistogramResult, error)
GetDimensionTokenHistogram delegates to the inner store and returns a token histogram bucketed by bucketSizeSeconds and grouped by the given dimension.
func (*HybridLogStore) GetDistinctAliases ¶ added in v1.3.2
func (h *HybridLogStore) GetDistinctAliases(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctAliases delegates to the inner store and returns distinct alias values matching query, capped at limit.
func (*HybridLogStore) GetDistinctKeyPairs ¶ added in v1.3.2
func (h *HybridLogStore) GetDistinctKeyPairs(ctx context.Context, idCol, nameCol string, limit int, query string) ([]KeyPairResult, error)
GetDistinctKeyPairs delegates to the inner store and returns distinct (idCol, nameCol) pairs matching query, capped at limit. Used to populate id/name filters in the UI for virtual keys, providers, etc.
func (*HybridLogStore) GetDistinctMetadataKeys ¶ added in v1.3.2
func (h *HybridLogStore) GetDistinctMetadataKeys(ctx context.Context, limit int, query string) (map[string][]string, error)
GetDistinctMetadataKeys delegates to the inner store and returns distinct metadata keys (and their distinct values) matching query, capped at limit.
func (*HybridLogStore) GetDistinctModels ¶ added in v1.3.2
func (h *HybridLogStore) GetDistinctModels(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctModels delegates to the inner store and returns distinct model values matching query, capped at limit.
func (*HybridLogStore) GetDistinctRoutingEngines ¶ added in v1.3.2
func (h *HybridLogStore) GetDistinctRoutingEngines(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctRoutingEngines delegates to the inner store and returns distinct routing-engine values matching query, capped at limit.
func (*HybridLogStore) GetDistinctStopReasons ¶ added in v1.3.6
func (h *HybridLogStore) GetDistinctStopReasons(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctStopReasons delegates to the inner store and returns distinct stop-reason values matching query, capped at limit.
func (*HybridLogStore) GetHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*HistogramResult, error)
GetHistogram delegates to the inner store and returns a request-count histogram bucketed by bucketSizeSeconds.
func (*HybridLogStore) GetLatencyHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*LatencyHistogramResult, error)
GetLatencyHistogram delegates to the inner store and returns a latency histogram bucketed by bucketSizeSeconds.
func (*HybridLogStore) GetMCPCostHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetMCPCostHistogram(ctx context.Context, filters MCPToolLogSearchFilters, bucketSizeSeconds int64) (*MCPCostHistogramResult, error)
GetMCPCostHistogram returns the cost histogram for MCP tool logs.
func (*HybridLogStore) GetMCPHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetMCPHistogram(ctx context.Context, filters MCPToolLogSearchFilters, bucketSizeSeconds int64) (*MCPHistogramResult, error)
GetMCPHistogram delegates to the inner store and returns an MCP tool-call count histogram bucketed by bucketSizeSeconds.
func (*HybridLogStore) GetMCPToolLogStats ¶ added in v1.3.2
func (h *HybridLogStore) GetMCPToolLogStats(ctx context.Context, filters MCPToolLogSearchFilters) (*MCPToolLogStats, error)
GetMCPToolLogStats returns statistics about MCP tool logs that match the given filters.
func (*HybridLogStore) GetMCPTopTools ¶ added in v1.3.2
func (h *HybridLogStore) GetMCPTopTools(ctx context.Context, filters MCPToolLogSearchFilters, limit int) (*MCPTopToolsResult, error)
GetMCPTopTools returns the top tools used in MCP tool logs.
func (*HybridLogStore) GetModelHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetModelHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ModelHistogramResult, error)
GetModelHistogram delegates to the inner store and returns a per-model request histogram bucketed by bucketSizeSeconds.
func (*HybridLogStore) GetModelRankings ¶ added in v1.3.2
func (h *HybridLogStore) GetModelRankings(ctx context.Context, filters SearchFilters) (*ModelRankingResult, error)
GetModelRankings delegates to the inner store and returns ranked usage aggregates per model for the matching log rows.
func (*HybridLogStore) GetNodeUsageAfter ¶ added in v1.3.11
func (h *HybridLogStore) GetNodeUsageAfter(ctx context.Context, nodeID string, cursor NodeUsageCursor) (*NodeUsageAggregate, error)
GetNodeUsageAfter delegates to the inner store and returns usage aggregates for the given node since cursor, used by the cluster gossip path to ship incremental usage to peers.
func (*HybridLogStore) GetProviderCostHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetProviderCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderCostHistogramResult, error)
GetProviderCostHistogram delegates to the inner store and returns a per-provider cost histogram bucketed by bucketSizeSeconds.
func (*HybridLogStore) GetProviderLatencyHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetProviderLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderLatencyHistogramResult, error)
GetProviderLatencyHistogram delegates to the inner store and returns a per-provider latency histogram bucketed by bucketSizeSeconds.
func (*HybridLogStore) GetProviderTokenHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetProviderTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderTokenHistogramResult, error)
GetProviderTokenHistogram delegates to the inner store and returns a per-provider token histogram bucketed by bucketSizeSeconds.
func (*HybridLogStore) GetSessionLogs ¶ added in v1.3.2
func (h *HybridLogStore) GetSessionLogs(ctx context.Context, sessionID string, pagination PaginationOptions) (*SessionDetailResult, error)
GetSessionLogs delegates to the inner store and returns the paginated logs belonging to the given session.
func (*HybridLogStore) GetSessionSummary ¶ added in v1.3.2
func (h *HybridLogStore) GetSessionSummary(ctx context.Context, sessionID string) (*SessionSummaryResult, error)
GetSessionSummary delegates to the inner store and returns an aggregated summary for the given session.
func (*HybridLogStore) GetStats ¶ added in v1.3.2
func (h *HybridLogStore) GetStats(ctx context.Context, filters SearchFilters) (*SearchStats, error)
GetStats delegates to the inner store and returns aggregate statistics for the matching log rows.
func (*HybridLogStore) GetTokenHistogram ¶ added in v1.3.2
func (h *HybridLogStore) GetTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*TokenHistogramResult, error)
GetTokenHistogram delegates to the inner store and returns a token-usage histogram bucketed by bucketSizeSeconds.
func (*HybridLogStore) GetUserRankings ¶ added in v1.3.2
func (h *HybridLogStore) GetUserRankings(ctx context.Context, filters SearchFilters) (*UserRankingResult, error)
GetUserRankings delegates to the inner store and returns ranked usage aggregates per user for the matching log rows.
func (*HybridLogStore) HasLogs ¶ added in v1.3.2
func (h *HybridLogStore) HasLogs(ctx context.Context) (bool, error)
HasLogs delegates to the inner store and reports whether any log rows exist. The object store is not consulted.
func (*HybridLogStore) HasMCPToolLogs ¶ added in v1.3.2
func (h *HybridLogStore) HasMCPToolLogs(ctx context.Context) (bool, error)
HasMCPToolLogs returns whether there are any MCP tool logs in the store.
func (*HybridLogStore) IsLogEntryPresent ¶ added in v1.3.2
IsLogEntryPresent delegates to the inner store and reports whether a log row with the given ID exists.
func (*HybridLogStore) Ping ¶ added in v1.3.2
func (h *HybridLogStore) Ping(ctx context.Context) error
Ping delegates to the inner store's health check.
func (*HybridLogStore) SearchLogs ¶ added in v1.3.2
func (h *HybridLogStore) SearchLogs(ctx context.Context, filters SearchFilters, pagination PaginationOptions) (*SearchResult, error)
SearchLogs delegates to the inner store. Search operates on indexed DB columns (including ContentSummary); payloads are not hydrated here.
func (*HybridLogStore) SearchMCPToolLogs ¶ added in v1.3.2
func (h *HybridLogStore) SearchMCPToolLogs(ctx context.Context, filters MCPToolLogSearchFilters, pagination PaginationOptions) (*MCPToolLogSearchResult, error)
SearchMCPToolLogs searches for MCP tool logs that match the given filters and returns the results.
func (*HybridLogStore) Update ¶ added in v1.3.2
Update passes the update through to the inner store for index/scalar field updates. Payload-field changes are not re-offloaded here; the logging plugin owns that path and calls processUpload directly when it needs to.
func (*HybridLogStore) UpdateAsyncJob ¶ added in v1.3.2
func (h *HybridLogStore) UpdateAsyncJob(ctx context.Context, id string, updates map[string]interface{}) error
UpdateAsyncJob updates an async job with the given ID using the provided updates.
func (*HybridLogStore) UpdateMCPToolLog ¶ added in v1.3.2
UpdateMCPToolLog updates an existing MCP tool log with the given ID using the provided entry data.
type KeyPairResult ¶ added in v1.2.22
KeyPairResult represents an ID-Name pair returned from DISTINCT queries
type LatencyHistogramBucket ¶ added in v1.2.24
type LatencyHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
AvgLatency float64 `json:"avg_latency"`
P90Latency float64 `json:"p90_latency"`
P95Latency float64 `json:"p95_latency"`
P99Latency float64 `json:"p99_latency"`
TotalRequests int64 `json:"total_requests"`
}
LatencyHistogramBucket represents a single time bucket for latency data
type LatencyHistogramResult ¶ added in v1.2.24
type LatencyHistogramResult struct {
Buckets []LatencyHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
}
LatencyHistogramResult represents the latency histogram query result
type Log ¶
type Log struct {
ID string `gorm:"primaryKey;type:varchar(255)" json:"id"`
IncNumber *int64 `gorm:"column:inc_number" json:"inc_number,omitempty"`
ParentRequestID *string `gorm:"type:varchar(255);index" json:"parent_request_id"`
Timestamp time.Time `gorm:"index;index:idx_logs_ts_provider_status,priority:1;not null" json:"timestamp"`
Object string `gorm:"type:varchar(255);index;not null;column:object_type" json:"object"` // text.completion, chat.completion, or embedding
Provider string `gorm:"type:varchar(255);index;index:idx_logs_ts_provider_status,priority:2;not null" json:"provider"`
Model string `gorm:"type:varchar(255);index;not null" json:"model"`
Alias *string `gorm:"type:varchar(255);index" json:"alias,omitempty"` // Set when model was resolved via alias mapping; the original name the caller used
NumberOfRetries int `gorm:"default:0" json:"number_of_retries"`
FallbackIndex int `gorm:"default:0" json:"fallback_index"`
SelectedKeyID string `gorm:"type:varchar(255);index:idx_logs_selected_key_id" json:"selected_key_id"`
SelectedKeyName string `gorm:"type:varchar(255)" json:"selected_key_name"`
AttemptTrail string `gorm:"type:text" json:"-"` // JSON serialized []schemas.KeyAttemptRecord
VirtualKeyID *string `gorm:"type:varchar(255);index:idx_logs_virtual_key_id" json:"virtual_key_id"`
VirtualKeyName *string `gorm:"type:varchar(255)" json:"virtual_key_name"`
RoutingEnginesUsedStr *string `gorm:"type:varchar(255);column:routing_engines_used" json:"-"` // Comma-separated routing engines
RoutingRuleID *string `gorm:"type:varchar(255);index:idx_logs_routing_rule_id" json:"routing_rule_id"`
RoutingRuleName *string `gorm:"type:varchar(255)" json:"routing_rule_name"`
SelectedPromptName *string `gorm:"type:varchar(255)" json:"selected_prompt_name"`
SelectedPromptVersion *string `gorm:"type:varchar(64)" json:"selected_prompt_version"`
SelectedPromptID *string `gorm:"type:varchar(36)" json:"selected_prompt_id"`
UserID *string `gorm:"type:varchar(255);index:idx_logs_user_id" json:"user_id"`
UserName *string `gorm:"type:varchar(255)" json:"user_name"`
TeamID *string `gorm:"type:varchar(255);index:idx_logs_team_id" json:"team_id"`
TeamName *string `gorm:"type:varchar(255)" json:"team_name"`
CustomerID *string `gorm:"type:varchar(255);index:idx_logs_customer_id" json:"customer_id"`
CustomerName *string `gorm:"type:varchar(255)" json:"customer_name"`
BusinessUnitID *string `gorm:"type:varchar(255);index:idx_logs_business_unit_id" json:"business_unit_id"`
BusinessUnitName *string `gorm:"type:varchar(255)" json:"business_unit_name"`
TeamIDs *string `gorm:"type:text" json:"-"`
TeamNames *string `gorm:"type:text" json:"-"`
CustomerIDs *string `gorm:"type:text" json:"-"`
CustomerNames *string `gorm:"type:text" json:"-"`
BusinessUnitIDs *string `gorm:"type:text" json:"-"`
BusinessUnitNames *string `gorm:"type:text" json:"-"`
InputHistory string `gorm:"type:text" json:"-"` // JSON serialized []schemas.ChatMessage
ResponsesInputHistory string `gorm:"type:text" json:"-"` // JSON serialized []schemas.ResponsesMessage
OutputMessage string `gorm:"type:text" json:"-"` // JSON serialized *schemas.ChatMessage
ResponsesOutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.ResponsesMessage
EmbeddingOutput string `gorm:"type:text" json:"-"` // JSON serialized [][]float32
RerankOutput string `gorm:"type:text" json:"-"` // JSON serialized []schemas.RerankResult
OCROutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostOCRResponse
Params string `gorm:"type:text" json:"-"` // JSON serialized *schemas.ModelParameters
Tools string `gorm:"type:text" json:"-"` // JSON serialized []schemas.Tool
ToolCalls string `gorm:"type:text" json:"-"` // JSON serialized []schemas.ToolCall (For backward compatibility, tool calls are now in the content)
SpeechInput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.SpeechInput
TranscriptionInput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.TranscriptionInput
OCRInput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.OCRDocument
ImageGenerationInput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.ImageGenerationInput
ImageEditInput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.ImageEditInput
ImageVariationInput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.ImageVariationInput
VideoGenerationInput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.VideoGenerationInput
SpeechOutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostSpeech
TranscriptionOutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostTranscribe
ImageGenerationOutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostImageGenerationResponse
ListModelsOutput string `gorm:"type:text" json:"-"` // JSON serialized []schemas.Model
VideoGenerationOutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostVideoGenerationResponse
VideoRetrieveOutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostVideoRetrieveResponse
VideoDownloadOutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostVideoDownloadResponse
VideoListOutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostVideoListResponse
VideoDeleteOutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostVideoDeleteResponse
CacheDebug string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostCacheDebug
Latency *float64 `gorm:"index:idx_logs_latency" json:"latency,omitempty"`
TokenUsage string `gorm:"type:text" json:"-"` // JSON serialized *schemas.LLMUsage
Cost *float64 `gorm:"index" json:"cost,omitempty"` // Cost in dollars (total cost of the request - includes cache lookup cost)
Status string `gorm:"type:varchar(50);index;index:idx_logs_ts_provider_status,priority:3;not null" json:"status"` // "processing", "success", or "error"
StopReason *string `gorm:"type:varchar(50);index:idx_logs_stop_reason" json:"stop_reason,omitempty"` // Why the model stopped: "stop", "length", "content_filter", "tool_calls", etc.
ErrorDetails string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostError
Stream bool `gorm:"default:false" json:"stream"` // true if this was a streaming response
ContentSummary string `gorm:"type:text" json:"-"`
RawRequest string `gorm:"type:text" json:"raw_request"` // Populated when `send-back-raw-request` is on
RawResponse string `gorm:"type:text" json:"raw_response"` // Populated when `send-back-raw-response` is on
PassthroughRequestBody string `gorm:"type:text" json:"passthrough_request_body,omitempty"` // Raw body for passthrough requests (UTF-8)
PassthroughResponseBody string `gorm:"type:text" json:"passthrough_response_body,omitempty"` // Raw body for passthrough responses (UTF-8)
RoutingEngineLogs string `gorm:"type:text" json:"routing_engine_logs,omitempty"` // Formatted routing engine decision logs
PluginLogs string `gorm:"type:text" json:"plugin_logs,omitempty"` // JSON serialized plugin log entries grouped by plugin name
Metadata *string `gorm:"type:text" json:"-"` // JSON serialized map[string]interface{}
IsLargePayloadRequest bool `gorm:"default:false" json:"is_large_payload_request"`
IsLargePayloadResponse bool `gorm:"default:false" json:"is_large_payload_response"`
HasObject bool `gorm:"default:false" json:"-"` // True when payload is stored in object storage
// Cluster governance fields - attached by the logging plugin when running in a cluster
// so that leaders can recover disconnected node usage from the logs table.
ClusterNodeID *string `gorm:"type:varchar(255)" json:"cluster_node_id,omitempty"`
BudgetIDs *string `gorm:"type:text" json:"-"` // JSON serialized []string of budget IDs applicable to this request
RateLimitIDs *string `gorm:"type:text" json:"-"` // JSON serialized []string of rate limit IDs applicable to this request
// Denormalized token fields for easier querying
PromptTokens int `gorm:"default:0" json:"-"`
CompletionTokens int `gorm:"default:0" json:"-"`
TotalTokens int `gorm:"index:idx_logs_total_tokens;default:0" json:"-"`
CachedReadTokens int `gorm:"default:0" json:"-"`
CreatedAt time.Time `gorm:"index;not null" json:"created_at"`
// Virtual fields for JSON output - these will be populated when needed
RoutingEnginesUsed []string `gorm:"-" json:"routing_engines_used,omitempty"` // Virtual field deserialized from JSON
InputHistoryParsed []schemas.ChatMessage `gorm:"-" json:"input_history,omitempty"`
ResponsesInputHistoryParsed []schemas.ResponsesMessage `gorm:"-" json:"responses_input_history,omitempty"`
OutputMessageParsed *schemas.ChatMessage `gorm:"-" json:"output_message,omitempty"`
ResponsesOutputParsed []schemas.ResponsesMessage `gorm:"-" json:"responses_output,omitempty"`
EmbeddingOutputParsed []schemas.EmbeddingData `gorm:"-" json:"embedding_output,omitempty"`
RerankOutputParsed []schemas.RerankResult `gorm:"-" json:"rerank_output,omitempty"`
OCROutputParsed *schemas.BifrostOCRResponse `gorm:"-" json:"ocr_output,omitempty"`
ParamsParsed interface{} `gorm:"-" json:"params,omitempty"`
ToolsParsed []schemas.ChatTool `gorm:"-" json:"tools,omitempty"`
ToolCallsParsed []schemas.ChatAssistantMessageToolCall `gorm:"-" json:"tool_calls,omitempty"` // For backward compatibility, tool calls are now in the content
TokenUsageParsed *schemas.BifrostLLMUsage `gorm:"-" json:"token_usage,omitempty"`
ErrorDetailsParsed *schemas.BifrostError `gorm:"-" json:"error_details,omitempty"`
SpeechInputParsed *schemas.SpeechInput `gorm:"-" json:"speech_input,omitempty"`
TranscriptionInputParsed *schemas.TranscriptionInput `gorm:"-" json:"transcription_input,omitempty"`
OCRInputParsed *schemas.OCRDocument `gorm:"-" json:"ocr_input,omitempty"`
ImageGenerationInputParsed *schemas.ImageGenerationInput `gorm:"-" json:"image_generation_input,omitempty"`
ImageEditInputParsed *schemas.ImageEditInput `gorm:"-" json:"image_edit_input,omitempty"`
ImageVariationInputParsed *schemas.ImageVariationInput `gorm:"-" json:"image_variation_input,omitempty"`
SpeechOutputParsed *schemas.BifrostSpeechResponse `gorm:"-" json:"speech_output,omitempty"`
TranscriptionOutputParsed *schemas.BifrostTranscriptionResponse `gorm:"-" json:"transcription_output,omitempty"`
ImageGenerationOutputParsed *schemas.BifrostImageGenerationResponse `gorm:"-" json:"image_generation_output,omitempty"`
CacheDebugParsed *schemas.BifrostCacheDebug `gorm:"-" json:"cache_debug,omitempty"`
ListModelsOutputParsed []schemas.Model `gorm:"-" json:"list_models_output,omitempty"`
MetadataParsed map[string]interface{} `gorm:"-" json:"metadata,omitempty"`
VideoGenerationInputParsed *schemas.VideoGenerationInput `gorm:"-" json:"video_generation_input,omitempty"`
VideoGenerationOutputParsed *schemas.BifrostVideoGenerationResponse `gorm:"-" json:"video_generation_output,omitempty"`
VideoRetrieveOutputParsed *schemas.BifrostVideoGenerationResponse `gorm:"-" json:"video_retrieve_output,omitempty"`
VideoDownloadOutputParsed *schemas.BifrostVideoDownloadResponse `gorm:"-" json:"video_download_output,omitempty"`
VideoListOutputParsed *schemas.BifrostVideoListResponse `gorm:"-" json:"video_list_output,omitempty"`
VideoDeleteOutputParsed *schemas.BifrostVideoDeleteResponse `gorm:"-" json:"video_delete_output,omitempty"`
AttemptTrailParsed []schemas.KeyAttemptRecord `gorm:"-" json:"attempt_trail,omitempty"`
BudgetIDsParsed []string `gorm:"-" json:"budget_ids,omitempty"`
RateLimitIDsParsed []string `gorm:"-" json:"rate_limit_ids,omitempty"`
TeamIDsParsed []string `gorm:"-" json:"team_ids,omitempty"`
TeamNamesParsed []string `gorm:"-" json:"team_names,omitempty"`
CustomerIDsParsed []string `gorm:"-" json:"customer_ids,omitempty"`
CustomerNamesParsed []string `gorm:"-" json:"customer_names,omitempty"`
BusinessUnitIDsParsed []string `gorm:"-" json:"business_unit_ids,omitempty"`
BusinessUnitNamesParsed []string `gorm:"-" json:"business_unit_names,omitempty"`
// Populated in handlers after find using the virtual key id and key id
VirtualKey *tables.TableVirtualKey `gorm:"-" json:"virtual_key,omitempty"` // redacted
SelectedKey *schemas.Key `gorm:"-" json:"selected_key,omitempty"` // redacted
RoutingRule *tables.TableRoutingRule `gorm:"-" json:"routing_rule,omitempty"` // redacted
}
Log represents a complete log entry for a request/response cycle This is the GORM model with appropriate tags
func NewLogEntryFromMap ¶ added in v1.2.9
NewLogEntryFromMap creates a new Log from a map[string]interface{}
func (*Log) BeforeCreate ¶
BeforeCreate GORM hook to set created_at and serialize JSON fields
func (*Log) BuildContentSummary ¶
BuildContentSummary creates a searchable text summary
func (*Log) BuildInputContentSummary ¶ added in v1.3.2
BuildInputContentSummary extracts the last user message text from input fields. This is used in hybrid mode for the content_summary column, which powers full-text search and serves as a display fallback in the log list table. Only the last message is kept — the full conversation history lives in object storage and is merged back on FindByID.
func (*Log) DeserializeFields ¶
DeserializeFields converts JSON strings back to Go structs
func (*Log) SerializeFields ¶
SerializeFields converts Go structs to JSON strings for storage
type LogRetentionManager ¶ added in v1.1.36
type LogRetentionManager interface {
DeleteLogsBatch(ctx context.Context, cutoff time.Time, batchSize int) (deletedCount int64, err error)
}
LogRetentionManager defines the interface for managing log retention and deletion
type LogStore ¶
type LogStore interface {
Ping(ctx context.Context) error
Create(ctx context.Context, entry *Log) error
CreateIfNotExists(ctx context.Context, entry *Log) error
BatchCreateIfNotExists(ctx context.Context, entries []*Log) error
FindByID(ctx context.Context, id string) (*Log, error)
IsLogEntryPresent(ctx context.Context, id string) (bool, error)
FindFirst(ctx context.Context, query any, fields ...string) (*Log, error)
FindAll(ctx context.Context, query any, fields ...string) ([]*Log, error)
FindAllDistinct(ctx context.Context, query any, fields ...string) ([]*Log, error)
HasLogs(ctx context.Context) (bool, error)
SearchLogs(ctx context.Context, filters SearchFilters, pagination PaginationOptions) (*SearchResult, error)
GetSessionLogs(ctx context.Context, sessionID string, pagination PaginationOptions) (*SessionDetailResult, error)
GetSessionSummary(ctx context.Context, sessionID string) (*SessionSummaryResult, error)
GetStats(ctx context.Context, filters SearchFilters) (*SearchStats, error)
GetHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*HistogramResult, error)
GetTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*TokenHistogramResult, error)
GetCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*CostHistogramResult, error)
GetModelHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ModelHistogramResult, error)
GetLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*LatencyHistogramResult, error)
GetProviderCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderCostHistogramResult, error)
GetProviderTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderTokenHistogramResult, error)
GetProviderLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderLatencyHistogramResult, error)
GetModelRankings(ctx context.Context, filters SearchFilters) (*ModelRankingResult, error)
GetUserRankings(ctx context.Context, filters SearchFilters) (*UserRankingResult, error)
GetDimensionRankings(ctx context.Context, filters SearchFilters, dimension RankingDimension) (*DimensionRankingResult, error)
// GetDimensionCostHistogram returns time-bucketed cost data grouped by the specified dimension (e.g., team_id, customer_id).
GetDimensionCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, dimension HistogramDimension) (*DimensionCostHistogramResult, error)
// GetDimensionTokenHistogram returns time-bucketed token usage grouped by the specified dimension.
GetDimensionTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, dimension HistogramDimension) (*DimensionTokenHistogramResult, error)
// GetDimensionLatencyHistogram returns time-bucketed latency percentiles grouped by the specified dimension.
GetDimensionLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, dimension HistogramDimension) (*DimensionLatencyHistogramResult, error)
// GetNodeUsageAfter returns cumulative usage for rows after the provided stable
// cursor. When the cursor has both timestamp and log ID, rows with the same
// timestamp but greater log ID are included to avoid skipping same-timestamp rows.
GetNodeUsageAfter(ctx context.Context, nodeID string, cursor NodeUsageCursor) (*NodeUsageAggregate, error)
Update(ctx context.Context, id string, entry any) error
BulkUpdateCost(ctx context.Context, updates map[string]float64) error
Flush(ctx context.Context, since time.Time) error
Close(ctx context.Context) error
DeleteLog(ctx context.Context, id string) error
DeleteLogs(ctx context.Context, ids []string) error
DeleteLogsBatch(ctx context.Context, cutoff time.Time, batchSize int) (deletedCount int64, err error)
// Distinct value methods for filter data
GetDistinctModels(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctAliases(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctKeyPairs(ctx context.Context, idCol, nameCol string, limit int, query string) ([]KeyPairResult, error)
GetDistinctRoutingEngines(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctStopReasons(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctMetadataKeys(ctx context.Context, limit int, query string) (map[string][]string, error)
// MCP Tool Log histogram methods
GetMCPHistogram(ctx context.Context, filters MCPToolLogSearchFilters, bucketSizeSeconds int64) (*MCPHistogramResult, error)
GetMCPCostHistogram(ctx context.Context, filters MCPToolLogSearchFilters, bucketSizeSeconds int64) (*MCPCostHistogramResult, error)
GetMCPTopTools(ctx context.Context, filters MCPToolLogSearchFilters, limit int) (*MCPTopToolsResult, error)
// MCP Tool Log methods
CreateMCPToolLog(ctx context.Context, entry *MCPToolLog) error
BatchCreateMCPToolLogsIfNotExists(ctx context.Context, entries []*MCPToolLog) error
FindMCPToolLog(ctx context.Context, id string) (*MCPToolLog, error)
UpdateMCPToolLog(ctx context.Context, id string, entry any) error
SearchMCPToolLogs(ctx context.Context, filters MCPToolLogSearchFilters, pagination PaginationOptions) (*MCPToolLogSearchResult, error)
GetMCPToolLogStats(ctx context.Context, filters MCPToolLogSearchFilters) (*MCPToolLogStats, error)
HasMCPToolLogs(ctx context.Context) (bool, error)
DeleteMCPToolLogs(ctx context.Context, ids []string) error
FlushMCPToolLogs(ctx context.Context, since time.Time) error
GetAvailableToolNames(ctx context.Context, limit int, query string) ([]string, error)
GetAvailableServerLabels(ctx context.Context, limit int, query string) ([]string, error)
GetAvailableMCPVirtualKeys(ctx context.Context, limit int, query string) ([]MCPToolLog, error)
// Async Job methods
CreateAsyncJob(ctx context.Context, job *AsyncJob) error
FindAsyncJobByID(ctx context.Context, id string) (*AsyncJob, error)
UpdateAsyncJob(ctx context.Context, id string, updates map[string]interface{}) error
DeleteExpiredAsyncJobs(ctx context.Context) (int64, error)
DeleteStaleAsyncJobs(ctx context.Context, staleSince time.Time) (int64, error)
}
LogStore is the interface for the log store.
func NewLogStore ¶
NewLogStore creates a new log store based on the configuration. When ObjectStorage is configured, the returned store is wrapped with a HybridLogStore that offloads payloads to S3-compatible object storage.
type LogStoreType ¶
type LogStoreType string
LogStoreType represents the type of log store.
const ( LogStoreTypeSQLite LogStoreType = "sqlite" LogStoreTypePostgres LogStoreType = "postgres" )
LogStoreTypeSQLite is the type of log store for SQLite.
type LogsCleaner ¶ added in v1.1.36
type LogsCleaner struct {
// contains filtered or unexported fields
}
LogsCleaner manages the cleanup of old logs
func NewLogsCleaner ¶ added in v1.1.36
func NewLogsCleaner(manager LogRetentionManager, config CleanerConfig, logger schemas.Logger) *LogsCleaner
NewLogsCleaner creates a new LogsCleaner instance
func (*LogsCleaner) StartCleanupRoutine ¶ added in v1.1.36
func (c *LogsCleaner) StartCleanupRoutine()
StartCleanupRoutine starts a goroutine that periodically cleans up old logs
func (*LogsCleaner) StopCleanupRoutine ¶ added in v1.1.36
func (c *LogsCleaner) StopCleanupRoutine()
StopCleanupRoutine gracefully stops the cleanup goroutine
type MCPCostHistogramBucket ¶ added in v1.2.31
type MCPCostHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
TotalCost float64 `json:"total_cost"`
}
MCPCostHistogramBucket represents a single time bucket for MCP cost data
type MCPCostHistogramResult ¶ added in v1.2.31
type MCPCostHistogramResult struct {
Buckets []MCPCostHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
}
MCPCostHistogramResult represents the MCP cost histogram query result
type MCPHistogramBucket ¶ added in v1.2.31
type MCPHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
Count int64 `json:"count"`
Success int64 `json:"success"`
Error int64 `json:"error"`
}
MCPHistogramBucket represents a single time bucket for MCP tool call volume
type MCPHistogramResult ¶ added in v1.2.31
type MCPHistogramResult struct {
Buckets []MCPHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
}
MCPHistogramResult represents the MCP tool call volume histogram query result
type MCPToolLog ¶ added in v1.2.17
type MCPToolLog struct {
ID string `gorm:"primaryKey;type:varchar(255)" json:"id"`
RequestID string `gorm:"type:varchar(255);column:request_id;index:idx_mcp_logs_request_id" json:"request_id,omitempty"` // The original request ID from context
LLMRequestID *string `gorm:"type:varchar(255);column:llm_request_id;index:idx_mcp_logs_llm_request_id" json:"llm_request_id,omitempty"` // Links to the LLM request that triggered this tool call
Timestamp time.Time `gorm:"index;not null" json:"timestamp"`
ToolName string `gorm:"type:varchar(255);index:idx_mcp_logs_tool_name;not null" json:"tool_name"`
ServerLabel string `gorm:"type:varchar(255);index:idx_mcp_logs_server_label" json:"server_label,omitempty"` // MCP server that provided the tool
VirtualKeyID *string `gorm:"type:varchar(255);index:idx_mcp_logs_virtual_key_id" json:"virtual_key_id"`
VirtualKeyName *string `gorm:"type:varchar(255)" json:"virtual_key_name"`
UserID *string `gorm:"type:varchar(255);index:idx_mcp_logs_user_id" json:"user_id"`
TeamID *string `gorm:"type:varchar(255);index:idx_mcp_logs_team_id" json:"team_id"`
CustomerID *string `gorm:"type:varchar(255);index:idx_mcp_logs_customer_id" json:"customer_id"`
BusinessUnitID *string `gorm:"type:varchar(255);index:idx_mcp_logs_business_unit_id" json:"business_unit_id"`
Arguments string `gorm:"type:text" json:"-"` // JSON serialized tool arguments
Result string `gorm:"type:text" json:"-"` // JSON serialized tool result
ErrorDetails string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostError
Latency *float64 `gorm:"index:idx_mcp_logs_latency" json:"latency,omitempty"` // Execution time in milliseconds
Cost *float64 `gorm:"index:idx_mcp_logs_cost" json:"cost,omitempty"` // Cost in dollars (per execution cost)
Status string `gorm:"type:varchar(50);index:idx_mcp_logs_status;not null" json:"status"` // "processing", "success", or "error"
Metadata string `gorm:"type:text" json:"-"` // JSON serialized map[string]interface{}
HasObject bool `gorm:"default:false" json:"-"` // True when payload is stored in object storage
CreatedAt time.Time `gorm:"index;not null" json:"created_at"`
// Virtual fields for JSON output - populated when needed
ArgumentsParsed interface{} `gorm:"-" json:"arguments,omitempty"`
ResultParsed interface{} `gorm:"-" json:"result,omitempty"`
ErrorDetailsParsed *schemas.BifrostError `gorm:"-" json:"error_details,omitempty"`
MetadataParsed map[string]interface{} `gorm:"-" json:"metadata,omitempty"`
VirtualKey *tables.TableVirtualKey `gorm:"-" json:"virtual_key,omitempty"`
}
MCPToolLog represents a log entry for MCP tool executions This is separate from the main Log table since MCP tool calls have different fields
func (*MCPToolLog) AfterFind ¶ added in v1.2.17
func (l *MCPToolLog) AfterFind(tx *gorm.DB) error
AfterFind GORM hook to deserialize JSON fields
func (*MCPToolLog) BeforeCreate ¶ added in v1.2.17
func (l *MCPToolLog) BeforeCreate(tx *gorm.DB) error
BeforeCreate GORM hook to set created_at and serialize JSON fields
func (*MCPToolLog) DeserializeFields ¶ added in v1.2.17
func (l *MCPToolLog) DeserializeFields() error
DeserializeFields converts JSON strings back to Go structs
func (*MCPToolLog) SerializeFields ¶ added in v1.2.17
func (l *MCPToolLog) SerializeFields() error
SerializeFields converts Go structs to JSON strings for storage
func (MCPToolLog) TableName ¶ added in v1.2.17
func (MCPToolLog) TableName() string
TableName sets the table name for GORM
type MCPToolLogSearchFilters ¶ added in v1.2.17
type MCPToolLogSearchFilters struct {
ToolNames []string `json:"tool_names,omitempty"`
ServerLabels []string `json:"server_labels,omitempty"`
Status []string `json:"status,omitempty"`
VirtualKeyIDs []string `json:"virtual_key_ids,omitempty"`
LLMRequestIDs []string `json:"llm_request_ids,omitempty"`
StartTime *time.Time `json:"start_time,omitempty"`
EndTime *time.Time `json:"end_time,omitempty"`
MinLatency *float64 `json:"min_latency,omitempty"`
MaxLatency *float64 `json:"max_latency,omitempty"`
ContentSearch string `json:"content_search,omitempty"`
}
MCPToolLogSearchFilters represents the available filters for MCP tool log searches
type MCPToolLogSearchResult ¶ added in v1.2.17
type MCPToolLogSearchResult struct {
Logs []MCPToolLog `json:"logs"`
Pagination PaginationOptions `json:"pagination"`
HasLogs bool `json:"has_logs"`
}
MCPToolLogSearchResult represents the result of an MCP tool log search
type MCPToolLogStats ¶ added in v1.2.17
type MCPToolLogStats struct {
TotalExecutions int64 `json:"total_executions"`
SuccessRate float64 `json:"success_rate"`
AverageLatency float64 `json:"average_latency"`
TotalCost float64 `json:"total_cost"` // Total cost in dollars
}
MCPToolLogStats represents statistics for MCP tool log searches
type MCPTopToolResult ¶ added in v1.2.31
type MCPTopToolResult struct {
ToolName string `json:"tool_name"`
Count int64 `json:"count"`
Cost float64 `json:"cost"`
}
MCPTopToolResult represents a single tool's aggregated stats
type MCPTopToolsResult ¶ added in v1.2.31
type MCPTopToolsResult struct {
Tools []MCPTopToolResult `json:"tools"`
}
MCPTopToolsResult represents the top N MCP tools by call count
type ModelHistogramBucket ¶ added in v1.2.13
type ModelHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
ByModel map[string]ModelUsageStats `json:"by_model"`
}
ModelHistogramBucket represents a single time bucket for model usage
type ModelHistogramResult ¶ added in v1.2.13
type ModelHistogramResult struct {
Buckets []ModelHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
Models []string `json:"models"`
}
ModelHistogramResult represents the model histogram query result
type ModelRankingEntry ¶ added in v1.2.31
type ModelRankingEntry struct {
Model string `json:"model"`
Provider string `json:"provider"`
TotalRequests int64 `json:"total_requests"`
SuccessCount int64 `json:"success_count"`
SuccessRate float64 `json:"success_rate"`
TotalTokens int64 `json:"total_tokens"`
TotalCost float64 `json:"total_cost"`
AvgLatency float64 `json:"avg_latency"`
}
ModelRankingEntry represents aggregated stats for a single model over a time period.
type ModelRankingResult ¶ added in v1.2.31
type ModelRankingResult struct {
Rankings []ModelRankingWithTrend `json:"rankings"`
}
ModelRankingResult is the response for the model rankings endpoint.
type ModelRankingTrend ¶ added in v1.2.31
type ModelRankingTrend struct {
HasPreviousPeriod bool `json:"has_previous_period"`
RequestsTrend float64 `json:"requests_trend"`
TokensTrend float64 `json:"tokens_trend"`
CostTrend float64 `json:"cost_trend"`
LatencyTrend float64 `json:"latency_trend"`
}
ModelRankingTrend represents the percentage change compared to the previous period.
type ModelRankingWithTrend ¶ added in v1.2.31
type ModelRankingWithTrend struct {
ModelRankingEntry
Trend ModelRankingTrend `json:"trend"`
}
ModelRankingWithTrend combines ranking entry with trend data.
type ModelUsageStats ¶ added in v1.2.13
type ModelUsageStats struct {
Total int64 `json:"total"`
Success int64 `json:"success"`
Error int64 `json:"error"`
}
ModelUsageStats represents usage statistics for a single model
type NodeUsageAggregate ¶ added in v1.3.11
type NodeUsageAggregate struct {
BudgetCosts map[string]float64 `json:"budget_costs"` // budget_id -> cumulative cost
RateLimitRequests map[string]int64 `json:"rate_limit_requests"` // rate_limit_id -> successful request count
RateLimitTokens map[string]int64 `json:"rate_limit_tokens"` // rate_limit_id -> total tokens
RowCount int `json:"row_count"` // number of log rows included in the aggregate
MaxTimestamp time.Time `json:"max_timestamp"` // highest log timestamp included in the aggregate
MaxLogID string `json:"max_log_id"` // log ID tiebreaker for MaxTimestamp
NextCursor NodeUsageCursor `json:"next_cursor"` // stable cursor for the next incremental query
}
NodeUsageAggregate represents aggregated usage for a specific node from the logs table, broken down by the budget and rate-limit IDs that each log entry was tagged with. This ensures usage is attributed to the correct governance resource rather than spread uniformly across all resources the node was tracking.
type NodeUsageCursor ¶ added in v1.3.11
type NodeUsageCursor struct {
Timestamp time.Time `json:"timestamp"`
LogID string `json:"log_id"`
IncNumber *int64 `json:"inc_number,omitempty"`
}
NodeUsageCursor identifies the last log row included in a node usage scan. The initial scan uses Timestamp + LogID because each ghost has a timestamp lower bound. Once rows written with IncNumber are seen, subsequent scans use IncNumber because it is assigned by the database at insert time and therefore does not skip late async log writes.
type PaginationOptions ¶
type PaginationOptions struct {
Limit int `json:"limit"`
Offset int `json:"offset"`
SortBy string `json:"sort_by"` // "timestamp", "latency", "tokens", "cost"
Order string `json:"order"` // "asc", "desc"
TotalCount int64 `json:"total_count"` // Total number of items matching the query
}
PaginationOptions represents pagination parameters
type PostgresConfig ¶ added in v1.1.0
type PostgresConfig struct {
Host *schemas.EnvVar `json:"host"`
Port *schemas.EnvVar `json:"port"`
User *schemas.EnvVar `json:"user"`
Password *schemas.EnvVar `json:"password"`
DBName *schemas.EnvVar `json:"db_name"`
SSLMode *schemas.EnvVar `json:"ssl_mode"`
MaxIdleConns int `json:"max_idle_conns"`
MaxOpenConns int `json:"max_open_conns"`
// MatViewRefreshInterval controls how often the materialized views backing
// /api/logs/stats and the dashboard histograms are refreshed. Accepts any
// Go duration string ("30s", "5m", "1h"). Empty / unset uses the default
// (defaultMatViewRefreshInterval). Raise this when refresh CPU cost is
// material on the database instance — the matview path already has
// activity-gated short-circuiting (see matViewRefreshGate), so the longer
// interval mostly affects how quickly idle clusters notice the rolling
// 30-day filter window has aged.
MatViewRefreshInterval string `json:"matview_refresh_interval,omitempty"`
}
PostgresConfig represents the configuration for a Postgres database.
type ProviderCostHistogramBucket ¶ added in v1.2.25
type ProviderCostHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
TotalCost float64 `json:"total_cost"`
ByProvider map[string]float64 `json:"by_provider"`
}
ProviderCostHistogramBucket represents a single time bucket for provider cost data
type ProviderCostHistogramResult ¶ added in v1.2.25
type ProviderCostHistogramResult struct {
Buckets []ProviderCostHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
Providers []string `json:"providers"`
}
ProviderCostHistogramResult represents the provider cost histogram query result
type ProviderLatencyHistogramBucket ¶ added in v1.2.25
type ProviderLatencyHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
ByProvider map[string]ProviderLatencyStats `json:"by_provider"`
}
ProviderLatencyHistogramBucket represents a single time bucket for provider latency data
type ProviderLatencyHistogramResult ¶ added in v1.2.25
type ProviderLatencyHistogramResult struct {
Buckets []ProviderLatencyHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
Providers []string `json:"providers"`
}
ProviderLatencyHistogramResult represents the provider latency histogram query result
type ProviderLatencyStats ¶ added in v1.2.25
type ProviderLatencyStats struct {
AvgLatency float64 `json:"avg_latency"`
P90Latency float64 `json:"p90_latency"`
P95Latency float64 `json:"p95_latency"`
P99Latency float64 `json:"p99_latency"`
TotalRequests int64 `json:"total_requests"`
}
ProviderLatencyStats represents latency statistics for a single provider
type ProviderTokenHistogramBucket ¶ added in v1.2.25
type ProviderTokenHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
ByProvider map[string]ProviderTokenStats `json:"by_provider"`
}
ProviderTokenHistogramBucket represents a single time bucket for provider token data
type ProviderTokenHistogramResult ¶ added in v1.2.25
type ProviderTokenHistogramResult struct {
Buckets []ProviderTokenHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
Providers []string `json:"providers"`
}
ProviderTokenHistogramResult represents the provider token histogram query result
type ProviderTokenStats ¶ added in v1.2.25
type ProviderTokenStats struct {
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
TotalTokens int64 `json:"total_tokens"`
}
ProviderTokenStats represents token statistics for a single provider
type RDBLogStore ¶ added in v1.1.0
type RDBLogStore struct {
// contains filtered or unexported fields
}
RDBLogStore represents a log store that uses a SQLite database.
func (*RDBLogStore) BatchCreateIfNotExists ¶ added in v1.2.24
func (s *RDBLogStore) BatchCreateIfNotExists(ctx context.Context, entries []*Log) error
BatchCreateIfNotExists inserts multiple log entries in a single transaction. Uses ON CONFLICT DO NOTHING for idempotency.
func (*RDBLogStore) BatchCreateMCPToolLogsIfNotExists ¶ added in v1.3.9
func (s *RDBLogStore) BatchCreateMCPToolLogsIfNotExists(ctx context.Context, entries []*MCPToolLog) error
BatchCreateMCPToolLogsIfNotExists inserts multiple MCP tool log entries in a single transaction. Uses ON CONFLICT DO NOTHING for idempotency.
func (*RDBLogStore) BulkUpdateCost ¶ added in v1.1.49
BulkUpdateCost updates log costs in bulk, using a PostgreSQL-specific batched VALUES update when available and per-row updates for other dialects.
func (*RDBLogStore) Close ¶ added in v1.1.0
func (s *RDBLogStore) Close(ctx context.Context) error
Close closes the log store.
func (*RDBLogStore) Create ¶ added in v1.1.0
func (s *RDBLogStore) Create(ctx context.Context, entry *Log) error
Create inserts a new log entry into the database.
func (*RDBLogStore) CreateAsyncJob ¶ added in v1.2.22
func (s *RDBLogStore) CreateAsyncJob(ctx context.Context, job *AsyncJob) error
CreateAsyncJob creates a new async job record in the database.
func (*RDBLogStore) CreateIfNotExists ¶ added in v1.1.40
func (s *RDBLogStore) CreateIfNotExists(ctx context.Context, entry *Log) error
CreateIfNotExists inserts a new log entry only if it doesn't already exist. Uses ON CONFLICT DO NOTHING to handle duplicate key errors gracefully.
func (*RDBLogStore) CreateMCPToolLog ¶ added in v1.2.17
func (s *RDBLogStore) CreateMCPToolLog(ctx context.Context, entry *MCPToolLog) error
CreateMCPToolLog inserts a new MCP tool log entry into the database.
func (*RDBLogStore) DeleteExpiredAsyncJobs ¶ added in v1.2.22
func (s *RDBLogStore) DeleteExpiredAsyncJobs(ctx context.Context) (int64, error)
DeleteExpiredAsyncJobs deletes async jobs whose expires_at has passed. Only deletes jobs that have a non-null expires_at (i.e., completed or failed jobs). Deletes in batches to avoid long-running transactions that hold row locks.
func (*RDBLogStore) DeleteLog ¶ added in v1.1.36
func (s *RDBLogStore) DeleteLog(ctx context.Context, id string) error
DeleteLog deletes a log entry from the database by its ID.
func (*RDBLogStore) DeleteLogs ¶ added in v1.1.36
func (s *RDBLogStore) DeleteLogs(ctx context.Context, ids []string) error
DeleteLogs deletes multiple log entries from the database by their IDs.
func (*RDBLogStore) DeleteLogsBatch ¶ added in v1.1.36
func (s *RDBLogStore) DeleteLogsBatch(ctx context.Context, cutoff time.Time, batchSize int) (deletedCount int64, err error)
DeleteLogsBatch deletes logs older than the cutoff time in batches.
func (*RDBLogStore) DeleteMCPToolLogs ¶ added in v1.2.17
func (s *RDBLogStore) DeleteMCPToolLogs(ctx context.Context, ids []string) error
DeleteMCPToolLogs deletes multiple MCP tool log entries from the database by their IDs.
func (*RDBLogStore) DeleteStaleAsyncJobs ¶ added in v1.2.22
func (s *RDBLogStore) DeleteStaleAsyncJobs(ctx context.Context, staleSince time.Time) (int64, error)
DeleteStaleAsyncJobs deletes async jobs stuck in "processing" status since before the given time. This handles edge cases like marshal failures or server crashes that leave jobs permanently stuck.
func (*RDBLogStore) FindAllDistinct ¶ added in v1.2.24
func (s *RDBLogStore) FindAllDistinct(ctx context.Context, query any, fields ...string) ([]*Log, error)
FindAllDistinct finds all distinct log entries for the given fields. Uses SQL DISTINCT to return only unique combinations, avoiding loading all rows when only unique values are needed (e.g., for filter dropdowns).
func (*RDBLogStore) FindAsyncJobByID ¶ added in v1.2.22
FindAsyncJobByID retrieves an async job by its ID.
func (*RDBLogStore) FindByID ¶ added in v1.2.9
FindByID gets a log entry from the database by its ID.
func (*RDBLogStore) FindMCPToolLog ¶ added in v1.2.17
func (s *RDBLogStore) FindMCPToolLog(ctx context.Context, id string) (*MCPToolLog, error)
FindMCPToolLog retrieves a single MCP tool log entry by its ID.
func (*RDBLogStore) FlushMCPToolLogs ¶ added in v1.2.17
FlushMCPToolLogs deletes old processing MCP tool log entries from the database.
func (*RDBLogStore) GetAvailableMCPVirtualKeys ¶ added in v1.2.17
func (s *RDBLogStore) GetAvailableMCPVirtualKeys(ctx context.Context, limit int, query string) ([]MCPToolLog, error)
func (*RDBLogStore) GetAvailableServerLabels ¶ added in v1.2.17
func (*RDBLogStore) GetAvailableToolNames ¶ added in v1.2.17
func (s *RDBLogStore) GetAvailableToolNames(ctx context.Context, limit int, query string) ([]string, error)
GetAvailableToolNames returns all unique tool names from the MCP tool logs. Scoped to recent data to avoid full table scans.
func (*RDBLogStore) GetCostHistogram ¶ added in v1.2.13
func (s *RDBLogStore) GetCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*CostHistogramResult, error)
GetCostHistogram returns time-bucketed cost data with model breakdown for the given filters.
func (*RDBLogStore) GetDimensionCostHistogram ¶ added in v1.3.1
func (s *RDBLogStore) GetDimensionCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, dimension HistogramDimension) (*DimensionCostHistogramResult, error)
GetDimensionCostHistogram returns time-bucketed cost data grouped by the specified dimension. Uses the mv_logs_hourly materialized view on PostgreSQL when eligible; falls back to raw queries otherwise.
func (*RDBLogStore) GetDimensionLatencyHistogram ¶ added in v1.3.1
func (s *RDBLogStore) GetDimensionLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, dimension HistogramDimension) (*DimensionLatencyHistogramResult, error)
GetDimensionLatencyHistogram returns time-bucketed latency percentiles grouped by the specified dimension. Uses the mv_logs_hourly materialized view on PostgreSQL when eligible; falls back to raw queries otherwise. The fallback path computes AVG latency only (no percentiles) since percentile_cont is Postgres-specific.
func (*RDBLogStore) GetDimensionRankings ¶ added in v1.3.14
func (s *RDBLogStore) GetDimensionRankings(ctx context.Context, filters SearchFilters, dimension RankingDimension) (*DimensionRankingResult, error)
GetDimensionRankings returns entities ranked by usage with trend comparison, grouped by the given dimension.
func (*RDBLogStore) GetDimensionTokenHistogram ¶ added in v1.3.1
func (s *RDBLogStore) GetDimensionTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64, dimension HistogramDimension) (*DimensionTokenHistogramResult, error)
GetDimensionTokenHistogram returns time-bucketed token usage grouped by the specified dimension. Uses the mv_logs_hourly materialized view on PostgreSQL when eligible; falls back to raw queries otherwise.
func (*RDBLogStore) GetDistinctAliases ¶ added in v1.3.1
func (s *RDBLogStore) GetDistinctAliases(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctAliases returns all unique non-empty alias values using SELECT DISTINCT. Scoped to recent data to avoid full table scans. Matview path is DAC-aware (see GetDistinctModels). Scoped to recent data to avoid full table scans.
func (*RDBLogStore) GetDistinctKeyPairs ¶ added in v1.2.22
func (s *RDBLogStore) GetDistinctKeyPairs(ctx context.Context, idCol, nameCol string, limit int, query string) ([]KeyPairResult, error)
GetDistinctKeyPairs returns unique non-empty ID-Name pairs for the given columns using SELECT DISTINCT. idCol and nameCol must be valid column names (e.g., "selected_key_id", "selected_key_name").
Matview path is DAC-aware: each per-dimension matview carries the visibility columns (user_id, team_id, virtual_key_id), so a QueryScope on ctx applies on the matview directly. Until matViewsReady the raw-table fallback (also ScopedDB-aware) serves requests.
func (*RDBLogStore) GetDistinctMetadataKeys ¶ added in v1.2.28
func (s *RDBLogStore) GetDistinctMetadataKeys(ctx context.Context, limit int, query string) (map[string][]string, error)
GetDistinctMetadataKeys returns unique metadata keys and their distinct values from recent logs. It scans a bounded number of recent rows to avoid memory bloat on large tables.
func (*RDBLogStore) GetDistinctModels ¶ added in v1.2.22
func (s *RDBLogStore) GetDistinctModels(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctModels returns all unique non-empty model values using SELECT DISTINCT. Scoped to recent data to avoid full table scans.
func (*RDBLogStore) GetDistinctRoutingEngines ¶ added in v1.2.22
func (s *RDBLogStore) GetDistinctRoutingEngines(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctRoutingEngines returns all unique routing engine values from the comma-separated column. Scoped to recent data to avoid full table scans. Matview path is DAC-aware (see GetDistinctModels). Scoped to recent data to avoid full table scans.
func (*RDBLogStore) GetDistinctStopReasons ¶ added in v1.3.6
func (s *RDBLogStore) GetDistinctStopReasons(ctx context.Context, limit int, query string) ([]string, error)
GetDistinctStopReasons returns all unique non-empty stop_reason values using SELECT DISTINCT. Scoped to recent data to avoid full table scans. Matview path is DAC-aware (see GetDistinctModels). Scoped to recent data to avoid full table scans.
func (*RDBLogStore) GetHistogram ¶ added in v1.2.13
func (s *RDBLogStore) GetHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*HistogramResult, error)
GetHistogram returns time-bucketed request counts for the given filters.
func (*RDBLogStore) GetLatencyHistogram ¶ added in v1.2.24
func (s *RDBLogStore) GetLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*LatencyHistogramResult, error)
GetLatencyHistogram returns time-bucketed latency percentiles (avg, p90, p95, p99) for the given filters. PostgreSQL uses database-level percentile_cont aggregation (returns 1 row per bucket). MySQL and SQLite fall back to Go-based percentile computation (loads individual latency values).
func (*RDBLogStore) GetMCPCostHistogram ¶ added in v1.2.31
func (s *RDBLogStore) GetMCPCostHistogram(ctx context.Context, filters MCPToolLogSearchFilters, bucketSizeSeconds int64) (*MCPCostHistogramResult, error)
GetMCPCostHistogram returns time-bucketed MCP cost data for the given filters.
func (*RDBLogStore) GetMCPHistogram ¶ added in v1.2.31
func (s *RDBLogStore) GetMCPHistogram(ctx context.Context, filters MCPToolLogSearchFilters, bucketSizeSeconds int64) (*MCPHistogramResult, error)
GetMCPHistogram returns time-bucketed MCP tool call volume for the given filters.
func (*RDBLogStore) GetMCPToolLogStats ¶ added in v1.2.17
func (s *RDBLogStore) GetMCPToolLogStats(ctx context.Context, filters MCPToolLogSearchFilters) (*MCPToolLogStats, error)
GetMCPToolLogStats calculates statistics for MCP tool logs matching the given filters.
func (*RDBLogStore) GetMCPTopTools ¶ added in v1.2.31
func (s *RDBLogStore) GetMCPTopTools(ctx context.Context, filters MCPToolLogSearchFilters, limit int) (*MCPTopToolsResult, error)
GetMCPTopTools returns the top N MCP tools by call count for the given filters.
func (*RDBLogStore) GetModelHistogram ¶ added in v1.2.13
func (s *RDBLogStore) GetModelHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ModelHistogramResult, error)
GetModelHistogram returns time-bucketed model usage with success/error breakdown for the given filters.
func (*RDBLogStore) GetModelRankings ¶ added in v1.2.31
func (s *RDBLogStore) GetModelRankings(ctx context.Context, filters SearchFilters) (*ModelRankingResult, error)
GetModelRankings returns models ranked by usage with trend comparison to the previous period.
func (*RDBLogStore) GetNodeUsageAfter ¶ added in v1.3.11
func (s *RDBLogStore) GetNodeUsageAfter(ctx context.Context, nodeID string, cursor NodeUsageCursor) (*NodeUsageAggregate, error)
GetNodeUsageAfter returns per-budget cost and per-rate-limit request/token usage for a specific cluster node after a stable cursor. The first scan uses the timestamp/log-id lower bound for the ghost's detection point. Once DB-assigned inc_number values are observed, subsequent scans use inc_number so rows flushed late by the async log writer are not skipped.
func (*RDBLogStore) GetProviderCostHistogram ¶ added in v1.2.25
func (s *RDBLogStore) GetProviderCostHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderCostHistogramResult, error)
GetProviderCostHistogram returns time-bucketed cost data with provider breakdown for the given filters.
func (*RDBLogStore) GetProviderLatencyHistogram ¶ added in v1.2.25
func (s *RDBLogStore) GetProviderLatencyHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderLatencyHistogramResult, error)
GetProviderLatencyHistogram returns time-bucketed latency percentiles with provider breakdown for the given filters. PostgreSQL uses database-level percentile_cont aggregation. MySQL and SQLite fall back to Go-based percentile computation.
func (*RDBLogStore) GetProviderTokenHistogram ¶ added in v1.2.25
func (s *RDBLogStore) GetProviderTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*ProviderTokenHistogramResult, error)
GetProviderTokenHistogram returns time-bucketed token usage with provider breakdown for the given filters.
func (*RDBLogStore) GetSessionLogs ¶ added in v1.3.1
func (s *RDBLogStore) GetSessionLogs(ctx context.Context, sessionID string, pagination PaginationOptions) (*SessionDetailResult, error)
GetSessionLogs returns paginated logs for a single parent_request_id session.
func (*RDBLogStore) GetSessionSummary ¶ added in v1.3.1
func (s *RDBLogStore) GetSessionSummary(ctx context.Context, sessionID string) (*SessionSummaryResult, error)
GetSessionSummary returns aggregate totals for a single parent_request_id session.
func (*RDBLogStore) GetStats ¶ added in v1.1.31
func (s *RDBLogStore) GetStats(ctx context.Context, filters SearchFilters) (*SearchStats, error)
GetStats calculates statistics for logs matching the given filters.
func (*RDBLogStore) GetTokenHistogram ¶ added in v1.2.13
func (s *RDBLogStore) GetTokenHistogram(ctx context.Context, filters SearchFilters, bucketSizeSeconds int64) (*TokenHistogramResult, error)
GetTokenHistogram returns time-bucketed token usage for the given filters.
func (*RDBLogStore) GetUserRankings ¶ added in v1.3.1
func (s *RDBLogStore) GetUserRankings(ctx context.Context, filters SearchFilters) (*UserRankingResult, error)
GetUserRankings returns users ranked by usage with trend comparison to the previous period.
func (*RDBLogStore) HasLogs ¶ added in v1.1.36
func (s *RDBLogStore) HasLogs(ctx context.Context) (bool, error)
HasLogs checks if there are any logs in the database.
func (*RDBLogStore) HasMCPToolLogs ¶ added in v1.2.17
func (s *RDBLogStore) HasMCPToolLogs(ctx context.Context) (bool, error)
HasMCPToolLogs checks if there are any MCP tool logs in the database.
func (*RDBLogStore) IsLogEntryPresent ¶ added in v1.3.0
IsLogEntryPresent checks if a log entry is present in the database. Here we dont load entire log entry in memory - just check if it exists.
func (*RDBLogStore) Ping ¶ added in v1.1.8
func (s *RDBLogStore) Ping(ctx context.Context) error
Ping checks if the database is reachable.
func (*RDBLogStore) ScopedDB ¶ added in v1.3.11
func (s *RDBLogStore) ScopedDB(ctx context.Context) *gorm.DB
ScopedDB returns the underlying DB bound to ctx with any QueryScope on ctx pre-applied. Use this in read paths that should respect caller-driven row visibility; use s.db.WithContext(ctx) for writes and internal lookups that must bypass scoping.
func (*RDBLogStore) SearchLogs ¶ added in v1.1.0
func (s *RDBLogStore) SearchLogs(ctx context.Context, filters SearchFilters, pagination PaginationOptions) (*SearchResult, error)
SearchLogs searches for logs in the database without calculating statistics.
func (*RDBLogStore) SearchMCPToolLogs ¶ added in v1.2.17
func (s *RDBLogStore) SearchMCPToolLogs(ctx context.Context, filters MCPToolLogSearchFilters, pagination PaginationOptions) (*MCPToolLogSearchResult, error)
SearchMCPToolLogs searches for MCP tool logs in the database.
func (*RDBLogStore) UpdateAsyncJob ¶ added in v1.2.22
func (s *RDBLogStore) UpdateAsyncJob(ctx context.Context, id string, updates map[string]interface{}) error
UpdateAsyncJob updates an async job record with the provided fields.
func (*RDBLogStore) UpdateMCPToolLog ¶ added in v1.2.17
UpdateMCPToolLog updates an MCP tool log entry in the database.
type RankingDimension ¶ added in v1.3.14
type RankingDimension string
RankingDimension is the column used for grouping in dimension rankings.
const ( RankingDimensionTeam RankingDimension = "team" RankingDimensionCustomer RankingDimension = "customer" RankingDimensionBusinessUnit RankingDimension = "business_unit" RankingDimensionUser RankingDimension = "user" )
type SQLiteConfig ¶
type SQLiteConfig struct {
Path string `json:"path"`
}
SQLiteConfig represents the configuration for a SQLite database.
type SearchFilters ¶
type SearchFilters struct {
Providers []string `json:"providers,omitempty"`
Models []string `json:"models,omitempty"`
Aliases []string `json:"aliases,omitempty"`
Status []string `json:"status,omitempty"`
StopReasons []string `json:"stop_reasons,omitempty"` // For filtering by stop reason (stop, length, content_filter, refusal, tool_calls, etc.)
Objects []string `json:"objects,omitempty"` // For filtering by request type (chat.completion, text.completion, embedding)
ParentRequestID string `json:"parent_request_id,omitempty"`
SelectedKeyIDs []string `json:"selected_key_ids,omitempty"`
VirtualKeyIDs []string `json:"virtual_key_ids,omitempty"`
RoutingRuleIDs []string `json:"routing_rule_ids,omitempty"`
TeamIDs []string `json:"team_ids,omitempty"`
CustomerIDs []string `json:"customer_ids,omitempty"`
UserIDs []string `json:"user_ids,omitempty"`
BusinessUnitIDs []string `json:"business_unit_ids,omitempty"`
RoutingEngineUsed []string `json:"routing_engine_used,omitempty"` // For filtering by routing engine (routing-rule, governance, loadbalancing)
StartTime *time.Time `json:"start_time,omitempty"`
EndTime *time.Time `json:"end_time,omitempty"`
MinLatency *float64 `json:"min_latency,omitempty"`
MaxLatency *float64 `json:"max_latency,omitempty"`
MinTokens *int `json:"min_tokens,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
MinCost *float64 `json:"min_cost,omitempty"`
MaxCost *float64 `json:"max_cost,omitempty"`
MissingCostOnly bool `json:"missing_cost_only,omitempty"`
CacheHitTypes []string `json:"cache_hit_types,omitempty"` // For filtering by local-cache hit type ("direct", "semantic")
ContentSearch string `json:"content_search,omitempty"`
MetadataFilters map[string]string `json:"metadata_filters,omitempty"` // key=metadataKey, value=metadataValue for filtering by metadata
}
SearchFilters represents the available filters for log searches
type SearchResult ¶
type SearchResult struct {
Logs []Log `json:"logs"`
Pagination PaginationOptions `json:"pagination"`
Stats SearchStats `json:"stats"`
HasLogs bool `json:"has_logs"`
}
SearchResult represents the result of a log search
type SearchStats ¶
type SearchStats struct {
TotalRequests int64 `json:"total_requests"`
SuccessRate float64 `json:"success_rate"` // Percentage of individual attempts that succeeded
UserFacingSuccessRate float64 `json:"user_facing_success_rate"` // Percentage of user requests that ultimately succeeded (fallback chains counted as one request)
UserFacingTotalRequests int64 `json:"user_facing_total_requests"` // Count of root requests (fallback_index = 0) used as denominator for UserFacingSuccessRate
AverageLatency float64 `json:"average_latency"` // Average latency in milliseconds
TotalTokens int64 `json:"total_tokens"` // Total tokens used
TotalCost float64 `json:"total_cost"` // Total cost in dollars
CacheHitRateTotalRequests *int64 `json:"cache_hit_rate_total_requests,omitempty"` // Completed requests used as local-cache hit-rate denominator
DirectCacheHits *int64 `json:"direct_cache_hits,omitempty"` // Number of direct (exact) semantic cache hits
SemanticCacheHits *int64 `json:"semantic_cache_hits,omitempty"` // Number of semantic (fuzzy) cache hits
}
type SessionDetailResult ¶ added in v1.3.1
type SessionSummaryResult ¶ added in v1.3.1
type SessionSummaryResult struct {
SessionID string `json:"session_id"`
Count int64 `json:"count"`
TotalCost float64 `json:"total_cost"`
TotalTokens int64 `json:"total_tokens"`
StartedAt string `json:"started_at,omitempty"`
LatestAt string `json:"latest_at,omitempty"`
DurationMs int64 `json:"duration_ms"`
}
type TokenHistogramBucket ¶ added in v1.2.13
type TokenHistogramBucket struct {
Timestamp time.Time `json:"timestamp"`
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
TotalTokens int64 `json:"total_tokens"`
CachedReadTokens int64 `json:"cached_read_tokens"`
}
TokenHistogramBucket represents a single time bucket for token usage
type TokenHistogramResult ¶ added in v1.2.13
type TokenHistogramResult struct {
Buckets []TokenHistogramBucket `json:"buckets"`
BucketSizeSeconds int64 `json:"bucket_size_seconds"`
}
TokenHistogramResult represents the token histogram query result
type UserRankingEntry ¶ added in v1.3.1
type UserRankingEntry struct {
UserID string `json:"user_id"`
TotalRequests int64 `json:"total_requests"`
TotalTokens int64 `json:"total_tokens"`
TotalCost float64 `json:"total_cost"`
}
UserRankingEntry represents a single user's usage statistics.
type UserRankingResult ¶ added in v1.3.1
type UserRankingResult struct {
Rankings []UserRankingWithTrend `json:"rankings"`
}
UserRankingResult is the response for the user rankings endpoint.
type UserRankingTrend ¶ added in v1.3.1
type UserRankingTrend struct {
HasPreviousPeriod bool `json:"has_previous_period"`
RequestsTrend float64 `json:"requests_trend"`
TokensTrend float64 `json:"tokens_trend"`
CostTrend float64 `json:"cost_trend"`
}
UserRankingTrend represents the percentage change compared to the previous period.
type UserRankingWithTrend ¶ added in v1.3.1
type UserRankingWithTrend struct {
UserRankingEntry
Trend UserRankingTrend `json:"trend"`
}
UserRankingWithTrend combines ranking entry with trend data.