predictivecache

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: MIT Imports: 20 Imported by: 0

README

PredictiveCache

Go Reference Go version License

PredictiveCache is a local Go library that learns repeated SQL template transitions and prefetches likely next SELECTs using conservative online workload modeling.

It is built for read-heavy application paths where SQL access follows repeated request flows, such as:

select user by id
  -> select orders for that user
  -> select recommendations for that user

It does not replace the database optimizer, call external model services, or infer business meaning from SQL text. The current pre-v1 API is a database/sql wrapper with exact result caching, online transition prediction, conservative argument binding, optional metadata persistence, and PostgreSQL-first parsing.

Use it for repeated, bindable multi-query request flows with enough time for a background query to finish. Use a regular exact cache when the same SQL and arguments already repeat frequently.

Status

Implemented through Milestone 9:

  • A database/sql wrapper API: Open, Wrap, QueryContext, QueryRowContext, ExecContext, Explain, Stats, and Close.
  • PostgreSQL parsing, normalization, and fingerprinting through pg_query_go; a conservative no-cgo fallback remains available.
  • Bounded exact result caching with typed argument keys, TTL, row/entry/total byte limits, and PostgreSQL table-version invalidation.
  • A custom predictivecache.Rows implementation for live and cached rows.
  • Online order-1 through order-3 transition prediction conditioned by route and tenant.
  • Explainable PostgreSQL structural features, weighted Jaccard similarity, and a bounded inverted index for cold templates.
  • Conservative learned parameter binding with explicit rejection of incomplete or low-confidence plans.
  • Opt-in background prefetch with bounded queueing, worker concurrency, timeout, QPS limiting, duplicate suppression, and write-generation protection.
  • Public InvalidateTables and InvalidateAll hooks for writes that occur outside the wrapper.
  • Metrics for cache behavior, prediction accuracy, binding, invalidation, prefetch completion, hits, waste, errors, timeouts, and rejection reasons.
  • Optional local SQLite metadata persistence with background checkpoints, restart restoration, corrupt-state recovery, and shutdown flush.
  • A deterministic synthetic e-commerce benchmark, a structural cold-start benchmark, and a Go-native BenchBase-derived Twitter benchmark against real PostgreSQL.

Writes made through PredictiveCache invalidate cache entries that depend on the modified PostgreSQL tables. External database writes are not observed automatically; applications must call InvalidateTables or InvalidateAll. Explicit transaction support and a transparent database/sql/driver wrapper are later work.

Persistence is opt-in through WithLogDir. It stores normalized templates, transition counts, binding statistics, table versions, structural features, and metrics. It does not store sessions, query arguments, result rows, or cache entries. Original executable SQL is excluded unless WithPersistRawSQL(true) is explicitly enabled.

Quickstart

Prerequisites:

  • Go 1.22 or newer.
  • A C compiler for the default PostgreSQL parser build. CGO_ENABLED=0 selects the narrower fallback parser.
  • initdb and pg_ctl on PATH for the real PostgreSQL demo and integration tests.
  • No Docker or Colima requirement.

The PostgreSQL scripts create disposable clusters under /tmp. Set PCACHE_TMPDIR to an existing short-path directory when /tmp is unavailable.

Install the library:

go get github.com/Hetul3/PredictiveCache@latest
go get github.com/jackc/pgx/v5

Run the unit and simulator suite:

go test ./...

Run the real PostgreSQL demo:

./scripts/run-demo.sh

Expected final line:

DEMO PASS: a learned transition executed on PostgreSQL in the background and served the next query from cache

Run the synthetic e-commerce evaluation:

go run ./cmd/pcache-bench -requests 1200 -seed 7 -write-percent 0 -noise-percent 0

Current deterministic output:

MODE                   SELECTS  CACHE_HIT_RATE  CACHE_LIFT_VS_EXACT  PREFETCH_HIT_RATE  PREFETCH_WASTE_RATE  ACC@1  ACC@3  STRUCTURAL_ACCEPTED  STRUCTURAL_ACC@1  MEMORY_KB
no_cache               3600     0.000           0.000                0.000              0.000                0.996  0.996  0                    0.000             11
exact_cache            3600     0.031           0.000                0.000              0.000                0.996  0.996  0                    0.000             8318
predictive             3600     0.668           0.637                1.000              0.000                0.996  0.996  0                    0.000             8318
predictive_structural  3600     0.668           0.637                1.000              0.000                0.996  0.996  0                    0.000             8318

Run the structural cold-start evaluation:

go run ./cmd/pcache-bench -scenario structural-cold -cold-templates 24

Current deterministic output:

MODE                   SELECTS  CACHE_HIT_RATE  CACHE_LIFT_VS_EXACT  PREFETCH_HIT_RATE  PREFETCH_WASTE_RATE  ACC@1  ACC@3  STRUCTURAL_ACCEPTED  STRUCTURAL_ACC@1  MEMORY_KB
no_cache               248      0.000           0.000                0.000              0.000                0.797  0.992  0                    0.000             6
exact_cache            248      0.000           0.000                0.000              0.000                0.797  0.992  0                    0.000             130
predictive             248      0.302           0.302                0.735              0.265                0.797  0.992  0                    0.000             144
predictive_structural  248      0.399           0.399                0.792              0.208                0.992  0.992  24                   1.000             153

See BENCHMARKS.md for methodology, upstream benchmark provenance, and real PostgreSQL benchmark results.

See ARCHITECTURE.md for component diagrams, data-flow diagrams, sequence diagrams, cache state transitions, runtime concurrency, and deployment notes.

See PROJECT_JOURNEY.md for the problem definition, design process, experiments, approaches that were rejected, benchmark iterations, and final tradeoffs.

See demo/README.md for a working PostgreSQL example and a step-by-step guide to integrating the wrapper into an existing Go service.

Benchmark Map

The regular Go cache baseline in the PostgreSQL benchmark is github.com/hashicorp/golang-lru/v2, a fixed-size thread-safe LRU cache. It is used as an application-level exact cache keyed by SQL plus args.

Cache hit rate, three-trial means:

Scenario                         LRU exact      Predictive     Use Predictive?
Flow, 500 users, 5ms gap         ################# 82.6%  ################### 94.2%  Maybe
Flow, 5000 users, 5ms gap        #### 17.5%             ############## 72.4%       Yes
Flow, 5000 users, 2ms gap        #### 17.5%             ###### 27.5%              No
Twitter mix, 500 users, 2ms gap  ## 11.5%               ############## 68.8%      No
Flow, 500 users, tiny LRU        ## 7.6%                ################### 94.2%  Yes, if exact cache is capacity-bound

Latency and waste decide the borderline cases:

Scenario                         Best read
Flow, 500 users, 5ms gap         LRU p50 3.5us; exact repetition dominates, predictive adds hit-rate but not enough latency benefit.
Flow, 5000 users, 5ms gap        Predictive +54.9pp hit-rate lift, 99.8% prefetch hit, 0.2% waste, lower p95 than LRU.
Flow, 5000 users, 2ms gap        Predictive waste 73.0% and issues 56.4% more PostgreSQL queries than exact cache.
Twitter mix                      Predictive has no meaningful lift over table-aware exact caching and adds PostgreSQL work.
Tiny LRU capacity                Exact-key LRU collapses when capacity is too small for the working set.

Rule of thumb: use PredictiveCache for repeated, bindable multi-query request flows with enough time for background prefetch to land. Use a regular exact cache when the same SQL+args repeat frequently. Disable predictive prefetch for single-query mixes, result-dependent second-stage queries, or very tight local-DB call chains.

Architecture

Application code
  |
  v
PredictiveCache Client
  |
  +-- PostgreSQL parser and template registry
  |
  +-- exact cache key: dialect + template id + args + table versions
  |
  +-- bounded in-memory result cache
  |
  +-- real database execution through database/sql + pgx
  |
  +-- async query event processor
        |
        +-- transition predictor
        +-- binding rule learner
        +-- structural cold-start index
        +-- metrics and explain output
        +-- optional SQLite metadata checkpoint
        |
        v
      bounded background prefetch scheduler

The foreground query path performs parsing, cache lookup, and database execution. Model training, metadata checkpointing, and prefetch execution happen asynchronously.

Basic Use

import (
	"database/sql"
	"time"

	"github.com/Hetul3/PredictiveCache"
	_ "github.com/jackc/pgx/v5/stdlib"
)

db, err := sql.Open("pgx", dsn)
if err != nil {
	return err
}

client, err := predictivecache.Wrap(
	db,
	predictivecache.DialectPostgres,
	predictivecache.WithPrefetchEnabled(true),
	predictivecache.WithLogDir("./.predictivecache"),
)
if err != nil {
	return err
}
defer client.Close()

ctx := predictivecache.WithSessionID(request.Context(), sessionID)
ctx = predictivecache.WithRoute(ctx, "GET /users/:id")

rows, err := client.QueryContext(ctx, "select id, name from users where id = $1", userID)
if err != nil {
	return err
}
defer rows.Close()

QueryContext returns *predictivecache.Rows, not *sql.Rows. It supports the common Next, Scan, Columns, ColumnTypes, Close, and Err methods, plus FromCache.

Prefetch is disabled by default. Production users should tune warm-up thresholds, confidence thresholds, cache bounds, worker count, timeout, and QPS limit for their workload.

Structural fallback is enabled by default in cgo builds, but it only affects cold templates with no observed transition context. Disable it with WithStructuralFallbackEnabled(false).

When another process writes to the same database:

if err := client.InvalidateTables("users", "orders"); err != nil {
	return err
}

Use InvalidateAll when the affected tables are unknown.

Documentation

Document Purpose
Demo and integration guide Run the real demo and adopt the wrapper in an existing service.
Architecture Components, data flow, sequence diagrams, concurrency, and deployment.
Engineering journey Problem-solving process, experiments, failures, and tradeoffs.
Benchmarks Methodology, workloads, commands, results, and limits.
Engineering specification Detailed v1 design and rationale.
Contributing Development workflow and verification requirements.
Security Vulnerability reporting and security boundaries.
Releasing Semantic versioning and pkg.go.dev publication steps.

Demo Metrics

The real PostgreSQL demo trains a user-to-orders transition, triggers a prefetch, then proves the next query came from cache. A representative metrics line is:

Metrics: attempts=2 hits=2 wasted=0 cache_entries=4 cache_bytes=64

attempts counts background prefetch executions. hits counts prefetched entries later used by an application query and can vary slightly with background timing in the demo. wasted counts prefetched entries evicted, expired, or invalidated before first use. The benchmark command reports the higher-level rates used for evaluation: cache hit-rate lift over exact caching, prefetch hit rate, waste rate, prediction accuracy, structural fallback use, and memory.

Verification

# Unit, simulator, parser, wrapper, cache, predictor, binding, persistence, and scheduler tests
go test ./...

# Data-race validation
go test -race ./...

# Verify the conservative parser build without cgo
CGO_ENABLED=0 go test ./...

# Static analysis and module integrity
go vet ./...
go mod verify

# Real PostgreSQL integration and syntax coverage
./scripts/test-postgres-integration.sh
PCACHE_GO_TEST_FLAGS=-race ./scripts/test-postgres-integration.sh

# BenchBase-derived multi-trial comparison against disposable PostgreSQL
./scripts/run-benchbase-twitter.sh

Versioning

The module follows semantic versioning. The recommended first public tag is v0.1.0, which correctly signals that the API is not yet stable. See RELEASING.md for the exact tag, push, proxy indexing, and pkg.go.dev verification steps.

License

MIT

Documentation

Overview

Package predictivecache wraps database/sql access with bounded exact caching and conservative predictive prefetching for repeated PostgreSQL query flows.

The client learns transitions between normalized SQL templates online. When a likely next SELECT and all of its arguments can be bound confidently, the query may be executed in a bounded background worker and inserted into the same exact result cache used by foreground queries.

Predictive prefetch is disabled by default. Applications should identify request-local flows with WithSessionID and optionally WithRoute, then enable and tune prefetching only after reviewing Stats and Explain output.

Writes executed through Client invalidate affected table versions. If other database clients write to the same tables, applications must call Client.InvalidateTables or Client.InvalidateAll before relying on cached reads.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrClientClosed = errors.New("predictivecache client is closed")

ErrClientClosed is returned when an operation starts after Client.Close.

Functions

func WithBindValue

func WithBindValue(ctx context.Context, key string, value any) context.Context

WithBindValue provides a request-scoped value that may bind a predicted query argument with explicit confidence.

func WithRoute

func WithRoute(ctx context.Context, route string) context.Context

WithRoute attaches an application route used to condition predictions.

func WithSessionID

func WithSessionID(ctx context.Context, sessionID string) context.Context

WithSessionID identifies the bounded query history used for transition learning and prediction.

func WithTenant

func WithTenant(ctx context.Context, tenant string) context.Context

WithTenant attaches a tenant identifier used to isolate predictor contexts.

Types

type BindingExplain

type BindingExplain struct {
	TemplateID      TemplateID
	Executable      bool
	Confidence      float64
	Args            []BoundArgument
	SQL             string
	RejectionReason string
}

BindingExplain describes whether a predicted template can be executed safely.

type BindingSource

type BindingSource string

BindingSource identifies where a predicted argument value came from.

const (
	// BindingSourceContextValue uses an explicit WithBindValue value.
	BindingSourceContextValue BindingSource = "context_value"
	// BindingSourcePreviousArg reuses an argument from the previous query.
	BindingSourcePreviousArg BindingSource = "previous_arg"
	// BindingSourceRecentSemantic uses a recent same-name session value.
	BindingSourceRecentSemantic BindingSource = "recent_semantic_value"
)

type BoundArgument

type BoundArgument struct {
	Position int
	Name     string
	Value    string
	Type     string

	Source            BindingSource
	SourceArgPosition int
	Confidence        float64
	// contains filtered or unexported fields
}

BoundArgument explains one argument selected for a predicted query.

type Client

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

Client wraps database/sql query execution, exact caching, online transition learning, and optional predictive prefetching.

func Open

func Open(driverName string, dsn string, opts ...Option) (*Client, error)

Open creates a database/sql connection and wraps it. Closing the returned client also closes the database handle.

func Wrap

func Wrap(db *sql.DB, dialect Dialect, opts ...Option) (*Client, error)

Wrap adds caching and learning to an existing database/sql handle. Closing the returned client does not close db.

Example
db, err := sql.Open("pgx", "postgres://localhost/app")
if err != nil {
	log.Fatal(err)
}
defer db.Close()

client, err := predictivecache.Wrap(
	db,
	predictivecache.DialectPostgres,
	predictivecache.WithPrefetchEnabled(true),
)
if err != nil {
	log.Fatal(err)
}
defer client.Close()

ctx := predictivecache.WithSessionID(context.Background(), "request-123")
ctx = predictivecache.WithRoute(ctx, "GET /users/:id")

// Use client.QueryContext and client.ExecContext in place of the matching
// database/sql methods. QueryContext returns *predictivecache.Rows.
_ = ctx

func (*Client) Close

func (c *Client) Close() error

Close drains asynchronous work, flushes enabled persistence, and releases resources. It is safe to call more than once.

func (*Client) ExecContext

func (c *Client) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext executes a statement and invalidates affected cached reads after a successful write.

func (*Client) Explain

func (c *Client) Explain(ctx context.Context, query string, args ...any) (*ExplainResult, error)

Explain normalizes query and returns current prediction and binding details without executing SQL or advancing learned session history.

func (*Client) InvalidateAll

func (c *Client) InvalidateAll() error

InvalidateAll clears all cached results and invalidates in-flight prefetches.

func (*Client) InvalidateTables

func (c *Client) InvalidateTables(tables ...string) error

InvalidateTables marks cached results that depend on the named tables stale. Applications should call this when writes occur outside PredictiveCache.

func (*Client) QueryContext

func (c *Client) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

QueryContext executes a query or returns an exact cached result. Its Rows type follows the common database/sql Rows methods and reports cache origin.

Example
registerFakeOnce.Do(func() {
	sql.Register("predictivecache_fake", fakeDriver{})
})
db, _ := sql.Open("predictivecache_fake", "")
resetFakeDriver()
client, _ := Wrap(db, DialectPostgres)
defer client.Close()

rows, _ := client.QueryContext(context.Background(), "select id, name from users where id = $1", 42)
defer rows.Close()

for rows.Next() {
	var id int64
	var name string
	rows.Scan(&id, &name)
	fmt.Println(id, name)
}
Output:
1 Ada

func (*Client) QueryRowContext

func (c *Client) QueryRowContext(ctx context.Context, query string, args ...any) *Row

QueryRowContext executes a query expected to return at most one consumed row.

func (*Client) Stats

func (c *Client) Stats() StatsSnapshot

Stats returns a point-in-time copy of client metrics.

type Dialect

type Dialect string

Dialect identifies the SQL dialect parsed by a Client.

const (
	// DialectPostgres selects PostgreSQL parsing and normalization.
	DialectPostgres Dialect = "postgres"
)

type ExplainResult

type ExplainResult struct {
	Template             Template
	Cacheable            bool
	PredictionCandidates []Prediction
	PredictionSource     string
	ContextHistory       []TemplateID
	BindingCandidates    []BindingExplain
	StructuralNeighbors  []StructuralNeighbor
}

ExplainResult describes how the client normalized a query and what it would predict next. Explain does not execute a query or advance session history.

type FeatureMap

type FeatureMap map[string]float64

FeatureMap contains weighted, inspectable PostgreSQL structural features.

type Operation

type Operation uint8

Operation describes the parsed class of a SQL statement.

const (
	// OpSelect identifies a read statement.
	OpSelect Operation = iota + 1
	// OpWrite identifies a data-changing statement.
	OpWrite
	// OpUtility identifies a statement that is neither a cacheable read nor a
	// recognized data-changing operation.
	OpUtility
)

type Option

type Option func(*options)

Option configures a Client.

func WithBindingConfidenceThreshold

func WithBindingConfidenceThreshold(threshold float64) Option

WithBindingConfidenceThreshold sets the minimum executable binding-plan confidence in the range (0, 1].

func WithBindingMinTrials

func WithBindingMinTrials(trials int) Option

WithBindingMinTrials sets the observations required before a learned argument-binding rule may execute a prefetch.

func WithCacheTTL

func WithCacheTTL(ttl time.Duration) Option

WithCacheTTL sets how long exact and prefetched result entries remain valid.

func WithEventChannelSize

func WithEventChannelSize(size int) Option

WithEventChannelSize sets the bounded asynchronous learning-event queue.

func WithLogDir

func WithLogDir(dir string) Option

WithLogDir enables local metadata persistence in the provided directory.

func WithMaxBindingRules

func WithMaxBindingRules(limit int) Option

WithMaxBindingRules limits learned argument-binding rules.

func WithMaxCacheBytes

func WithMaxCacheBytes(bytes int64) Option

WithMaxCacheBytes sets the approximate total in-memory result-cache budget.

func WithMaxCacheEntryBytes

func WithMaxCacheEntryBytes(bytes int64) Option

WithMaxCacheEntryBytes sets the largest result that may enter the cache.

func WithMaxCacheRows

func WithMaxCacheRows(rows int) Option

WithMaxCacheRows sets the largest row count that may enter the cache.

func WithMaxContextOrder

func WithMaxContextOrder(order int) Option

WithMaxContextOrder sets the predictor history depth from one through three.

func WithMaxPredictionCandidates

func WithMaxPredictionCandidates(limit int) Option

WithMaxPredictionCandidates limits candidates evaluated after each event.

func WithMaxSessions

func WithMaxSessions(limit int) Option

WithMaxSessions limits retained in-memory request histories.

func WithMaxStructuralFeaturesPerTemplate

func WithMaxStructuralFeaturesPerTemplate(limit int) Option

WithMaxStructuralFeaturesPerTemplate limits indexed features per template.

func WithMaxStructuralNeighbors

func WithMaxStructuralNeighbors(limit int) Option

WithMaxStructuralNeighbors limits neighbors considered per cold template.

func WithMaxStructuralTemplates

func WithMaxStructuralTemplates(limit int) Option

WithMaxStructuralTemplates limits templates retained by the structural index.

func WithMinEventsBeforePrefetch

func WithMinEventsBeforePrefetch(events int) Option

WithMinEventsBeforePrefetch sets the warm-up event count.

func WithPersistRawSQL

func WithPersistRawSQL(enabled bool) Option

WithPersistRawSQL permits persistence of original executable SQL text. It is disabled by default because SQL literals may contain application data.

func WithPersistenceBatchSize

func WithPersistenceBatchSize(size int) Option

WithPersistenceBatchSize sets how many state changes trigger an early checkpoint when persistence is enabled.

func WithPersistenceInterval

func WithPersistenceInterval(interval time.Duration) Option

WithPersistenceInterval sets the maximum interval between dirty-state checkpoints when persistence is enabled.

func WithPredictionAlpha

func WithPredictionAlpha(alpha float64) Option

WithPredictionAlpha sets the backoff smoothing strength.

func WithPredictionConfidenceThreshold

func WithPredictionConfidenceThreshold(threshold float64) Option

WithPredictionConfidenceThreshold sets the minimum transition confidence required for ordinary predictive prefetch.

func WithPrefetchConcurrency

func WithPrefetchConcurrency(concurrency int) Option

WithPrefetchConcurrency sets the number of background query workers.

func WithPrefetchEnabled

func WithPrefetchEnabled(enabled bool) Option

WithPrefetchEnabled enables or disables predictive background queries. Prefetch is disabled by default.

func WithPrefetchMaxQPS

func WithPrefetchMaxQPS(qps int) Option

WithPrefetchMaxQPS limits total background query starts per second.

func WithPrefetchQueueSize

func WithPrefetchQueueSize(size int) Option

WithPrefetchQueueSize sets the bounded background job queue size.

func WithPrefetchTimeout

func WithPrefetchTimeout(timeout time.Duration) Option

WithPrefetchTimeout sets the deadline applied to each background query.

func WithStructuralColdStartPenalty

func WithStructuralColdStartPenalty(penalty float64) Option

WithStructuralColdStartPenalty downweights borrowed transition confidence.

func WithStructuralFallbackEnabled

func WithStructuralFallbackEnabled(enabled bool) Option

WithStructuralFallbackEnabled controls bounded structural cold-start prediction. It is unavailable in no-cgo builds.

func WithStructuralMinSimilarity

func WithStructuralMinSimilarity(similarity float64) Option

WithStructuralMinSimilarity sets the minimum weighted Jaccard similarity for a structural neighbor.

func WithStructuralPrefetchConfidence

func WithStructuralPrefetchConfidence(threshold float64) Option

WithStructuralPrefetchConfidence sets the minimum confidence for a structurally borrowed prefetch candidate.

type Prediction

type Prediction struct {
	TemplateID           TemplateID
	Probability          float64
	Confidence           float64
	ContextOrder         int
	Source               string
	BorrowedFrom         TemplateID
	StructuralSimilarity float64
	StructuralOverlap    []string
}

Prediction describes a likely next query template and its score.

type Row

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

Row is the result of QueryRowContext.

func (*Row) Scan

func (r *Row) Scan(dest ...any) error

Scan copies the first row into dest or returns sql.ErrNoRows.

type Rows

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

Rows represents either live database rows or a materialized cache entry. Callers should close Rows when iteration stops before Next returns false.

func (*Rows) Close

func (r *Rows) Close() error

Close releases live database resources and completes cache admission.

func (*Rows) ColumnTypes

func (r *Rows) ColumnTypes() ([]*sql.ColumnType, error)

ColumnTypes returns the result column metadata available from database/sql.

func (*Rows) Columns

func (r *Rows) Columns() ([]string, error)

Columns returns the result column names.

func (*Rows) Err

func (r *Rows) Err() error

Err reports the last iteration or scan error.

func (*Rows) FromCache

func (r *Rows) FromCache() bool

FromCache reports whether the rows were served from the result cache.

func (*Rows) Next

func (r *Rows) Next() bool

Next prepares the next row for Scan.

func (*Rows) Scan

func (r *Rows) Scan(dest ...any) error

Scan copies the current row into dest.

type StatsSnapshot

type StatsSnapshot struct {
	QueriesTotal                  uint64
	SelectsTotal                  uint64
	WritesTotal                   uint64
	ParseErrors                   uint64
	TemplatesTotal                int64
	EventsDropped                 uint64
	CacheHits                     uint64
	CacheMisses                   uint64
	CacheRejected                 uint64
	CacheInvalidations            uint64
	TableVersionInvalidations     uint64
	FullCacheInvalidations        uint64
	CacheStaleMisses              uint64
	CacheEntries                  int64
	CacheBytes                    int64
	PredictionsTotal              uint64
	PredictionsEvaluated          uint64
	PredictionAccuracyAt1         float64
	PredictionAccuracyAt3         float64
	TransitionContextsTotal       int64
	SessionsTotal                 int64
	BindingAttempts               uint64
	BindingAccepted               uint64
	BindingRejectedUnbound        uint64
	BindingRejectedLowConfidence  uint64
	BindingRulesTotal             int64
	PrefetchCandidates            uint64
	PrefetchAccepted              uint64
	PrefetchAttempts              uint64
	PrefetchCompleted             uint64
	PrefetchHits                  uint64
	PrefetchWasted                uint64
	PrefetchErrors                uint64
	PrefetchTimeouts              uint64
	PrefetchRejectedLowConfidence uint64
	PrefetchRejectedUnbound       uint64
	PrefetchRejectedDuplicate     uint64
	PrefetchRejectedQueueFull     uint64
	PrefetchRejectedStale         uint64
	StructuralFallbackCandidates  uint64
	StructuralFallbackAccepted    uint64
	StructuralFallbackEvaluated   uint64
	StructuralFallbackAccuracyAt1 float64
	StructuralTemplatesTotal      int64
	PersistenceLoads              uint64
	PersistenceFlushes            uint64
	PersistenceErrors             uint64
	PersistenceRecoveries         uint64
}

StatsSnapshot is a point-in-time copy of cache, prediction, binding, invalidation, prefetch, structural fallback, and persistence metrics.

type StructuralNeighbor

type StructuralNeighbor struct {
	TemplateID TemplateID
	Similarity float64
	Overlap    []string
}

StructuralNeighbor explains a structurally similar template considered during cold-start prediction.

type Template

type Template struct {
	ID                      TemplateID
	Name                    string
	CanonicalSQL            string
	ExecutableSQL           string
	ExecutableSQLReady      bool
	Fingerprint             string
	FingerprintHash         uint64
	Operation               Operation
	Cacheable               bool
	ArgNames                []string
	ReadTables              []string
	WriteTables             []string
	TableDependenciesKnown  bool
	StructuralFeatures      FeatureMap
	StructuralFeaturesKnown bool
	ResultBytes             int
	DBLatency               time.Duration
	ExpectedRows            int
	EstimatedCost           time.Duration
}

Template contains normalized SQL metadata used for caching and prediction.

type TemplateID

type TemplateID uint64

TemplateID identifies a normalized SQL template within a client.

Directories

Path Synopsis
cmd
pcache-bench command
demo
postgres command
internal
benchbase/twitter
Package twitter generates reproducible workloads derived from the BenchBase Twitter benchmark's transaction weights and SQL procedures.
Package twitter generates reproducible workloads derived from the BenchBase Twitter benchmark's transaction weights and SQL procedures.
sim

Jump to

Keyboard shortcuts

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