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 ¶
- Variables
- func WithBindValue(ctx context.Context, key string, value any) context.Context
- func WithRoute(ctx context.Context, route string) context.Context
- func WithSessionID(ctx context.Context, sessionID string) context.Context
- func WithTenant(ctx context.Context, tenant string) context.Context
- type BindingExplain
- type BindingSource
- type BoundArgument
- type Client
- func (c *Client) Close() error
- func (c *Client) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (c *Client) Explain(ctx context.Context, query string, args ...any) (*ExplainResult, error)
- func (c *Client) InvalidateAll() error
- func (c *Client) InvalidateTables(tables ...string) error
- func (c *Client) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)
- func (c *Client) QueryRowContext(ctx context.Context, query string, args ...any) *Row
- func (c *Client) Stats() StatsSnapshot
- type Dialect
- type ExplainResult
- type FeatureMap
- type Operation
- type Option
- func WithBindingConfidenceThreshold(threshold float64) Option
- func WithBindingMinTrials(trials int) Option
- func WithCacheTTL(ttl time.Duration) Option
- func WithEventChannelSize(size int) Option
- func WithLogDir(dir string) Option
- func WithMaxBindingRules(limit int) Option
- func WithMaxCacheBytes(bytes int64) Option
- func WithMaxCacheEntryBytes(bytes int64) Option
- func WithMaxCacheRows(rows int) Option
- func WithMaxContextOrder(order int) Option
- func WithMaxPredictionCandidates(limit int) Option
- func WithMaxSessions(limit int) Option
- func WithMaxStructuralFeaturesPerTemplate(limit int) Option
- func WithMaxStructuralNeighbors(limit int) Option
- func WithMaxStructuralTemplates(limit int) Option
- func WithMinEventsBeforePrefetch(events int) Option
- func WithPersistRawSQL(enabled bool) Option
- func WithPersistenceBatchSize(size int) Option
- func WithPersistenceInterval(interval time.Duration) Option
- func WithPredictionAlpha(alpha float64) Option
- func WithPredictionConfidenceThreshold(threshold float64) Option
- func WithPrefetchConcurrency(concurrency int) Option
- func WithPrefetchEnabled(enabled bool) Option
- func WithPrefetchMaxQPS(qps int) Option
- func WithPrefetchQueueSize(size int) Option
- func WithPrefetchTimeout(timeout time.Duration) Option
- func WithStructuralColdStartPenalty(penalty float64) Option
- func WithStructuralFallbackEnabled(enabled bool) Option
- func WithStructuralMinSimilarity(similarity float64) Option
- func WithStructuralPrefetchConfidence(threshold float64) Option
- type Prediction
- type Row
- type Rows
- type StatsSnapshot
- type StructuralNeighbor
- type Template
- type TemplateID
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrClientClosed = errors.New("predictivecache client is closed")
ErrClientClosed is returned when an operation starts after Client.Close.
Functions ¶
func WithBindValue ¶
WithBindValue provides a request-scoped value that may bind a predicted query argument with explicit confidence.
func WithSessionID ¶
WithSessionID identifies the bounded query history used for transition learning and prediction.
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 ¶
Open creates a database/sql connection and wraps it. Closing the returned client also closes the database handle.
func Wrap ¶
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 ¶
Close drains asynchronous work, flushes enabled persistence, and releases resources. It is safe to call more than once.
func (*Client) ExecContext ¶
ExecContext executes a statement and invalidates affected cached reads after a successful write.
func (*Client) Explain ¶
Explain normalizes query and returns current prediction and binding details without executing SQL or advancing learned session history.
func (*Client) InvalidateAll ¶
InvalidateAll clears all cached results and invalidates in-flight prefetches.
func (*Client) InvalidateTables ¶
InvalidateTables marks cached results that depend on the named tables stale. Applications should call this when writes occur outside PredictiveCache.
func (*Client) QueryContext ¶
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 ¶
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 ¶
FeatureMap contains weighted, inspectable PostgreSQL structural features.
type Option ¶
type Option func(*options)
Option configures a Client.
func WithBindingConfidenceThreshold ¶
WithBindingConfidenceThreshold sets the minimum executable binding-plan confidence in the range (0, 1].
func WithBindingMinTrials ¶
WithBindingMinTrials sets the observations required before a learned argument-binding rule may execute a prefetch.
func WithCacheTTL ¶
WithCacheTTL sets how long exact and prefetched result entries remain valid.
func WithEventChannelSize ¶
WithEventChannelSize sets the bounded asynchronous learning-event queue.
func WithLogDir ¶
WithLogDir enables local metadata persistence in the provided directory.
func WithMaxBindingRules ¶
WithMaxBindingRules limits learned argument-binding rules.
func WithMaxCacheBytes ¶
WithMaxCacheBytes sets the approximate total in-memory result-cache budget.
func WithMaxCacheEntryBytes ¶
WithMaxCacheEntryBytes sets the largest result that may enter the cache.
func WithMaxCacheRows ¶
WithMaxCacheRows sets the largest row count that may enter the cache.
func WithMaxContextOrder ¶
WithMaxContextOrder sets the predictor history depth from one through three.
func WithMaxPredictionCandidates ¶
WithMaxPredictionCandidates limits candidates evaluated after each event.
func WithMaxSessions ¶
WithMaxSessions limits retained in-memory request histories.
func WithMaxStructuralFeaturesPerTemplate ¶
WithMaxStructuralFeaturesPerTemplate limits indexed features per template.
func WithMaxStructuralNeighbors ¶
WithMaxStructuralNeighbors limits neighbors considered per cold template.
func WithMaxStructuralTemplates ¶
WithMaxStructuralTemplates limits templates retained by the structural index.
func WithMinEventsBeforePrefetch ¶
WithMinEventsBeforePrefetch sets the warm-up event count.
func WithPersistRawSQL ¶
WithPersistRawSQL permits persistence of original executable SQL text. It is disabled by default because SQL literals may contain application data.
func WithPersistenceBatchSize ¶
WithPersistenceBatchSize sets how many state changes trigger an early checkpoint when persistence is enabled.
func WithPersistenceInterval ¶
WithPersistenceInterval sets the maximum interval between dirty-state checkpoints when persistence is enabled.
func WithPredictionAlpha ¶
WithPredictionAlpha sets the backoff smoothing strength.
func WithPredictionConfidenceThreshold ¶
WithPredictionConfidenceThreshold sets the minimum transition confidence required for ordinary predictive prefetch.
func WithPrefetchConcurrency ¶
WithPrefetchConcurrency sets the number of background query workers.
func WithPrefetchEnabled ¶
WithPrefetchEnabled enables or disables predictive background queries. Prefetch is disabled by default.
func WithPrefetchMaxQPS ¶
WithPrefetchMaxQPS limits total background query starts per second.
func WithPrefetchQueueSize ¶
WithPrefetchQueueSize sets the bounded background job queue size.
func WithPrefetchTimeout ¶
WithPrefetchTimeout sets the deadline applied to each background query.
func WithStructuralColdStartPenalty ¶
WithStructuralColdStartPenalty downweights borrowed transition confidence.
func WithStructuralFallbackEnabled ¶
WithStructuralFallbackEnabled controls bounded structural cold-start prediction. It is unavailable in no-cgo builds.
func WithStructuralMinSimilarity ¶
WithStructuralMinSimilarity sets the minimum weighted Jaccard similarity for a structural neighbor.
func WithStructuralPrefetchConfidence ¶
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.
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) ColumnTypes ¶
func (r *Rows) ColumnTypes() ([]*sql.ColumnType, error)
ColumnTypes returns the result column metadata available from database/sql.
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
pcache-bench
command
|
|
|
pcache-bench-postgres
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. |