Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@

# PITOT_QUERY_CACHE_TTL; duration
# The oldest a dashboard panel, exemplar or trace detail result served from memory may be, measured from the end of the time window it covers (for traces and exemplars, from when their run started). A result younger than half the TTL is served as is; one younger than the TTL is served while one background run refreshes it; an older one is rerun. A request with Cache-Control: no-cache, such as a dashboard's manual refresh, always reruns. Zero disables the cache; concurrent identical requests still share one execution.
# Default: 10s
# Default: 1m
# PITOT_QUERY_CACHE_TTL=

# PITOT_RETENTION_DAYS; integer
Expand Down
13 changes: 8 additions & 5 deletions docs/proposals/0010-result-cache-extent-key.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Result-cache key normalization and an extent cache

Status: Draft
Status: Accepted
Date: 2026-11-15
Pull request: TBD
Pull request: [#529](https://github.com/labstack/pitot/pull/529) (Phases 1–2); Phases 3–4 remain open on [#477](https://github.com/labstack/pitot/issues/477)

## Summary

Expand Down Expand Up @@ -299,6 +299,9 @@ while 0007 moves summary-rollup maintenance and rollup-backed aggregate panels;
exercise cross-viewer sharing) and report the cache hit rate so a gain is not
mis-attributed.

**Build readiness.** Phases 1-2 are buildable now, cheap and low-risk, and ship
independently of 0007. Phases 3-4 follow, with Phase 4 gated behind 0007 and the
correctness tests above.
**Implementation.** Phases 1–2 raise the live TTL to one minute and share
whole-panel results by the effective panel spec, resolved interval, window and
referenced variables (including All and transitive dependencies). A relative
key records its span and shift. Execution still uses the exact requested
half-open bounds. Phase 3 will align relative windows. Phase 4 remains gated
behind Proposal 0007 and the extent correctness tests above.
2 changes: 1 addition & 1 deletion docs/proposals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ Earlier proposals predate the template and keep their original structure.
| 0007 | [Additive per-batch rollup aggregates](0007-additive-rollup-aggregates.md) | Draft |
| 0008 | [Mergeable latency sketch and derived service rollup](0008-mergeable-latency-sketch.md) | Implemented |
| 0009 | [Manifest catalog, write-ahead log, and parallel compaction](0009-manifest-catalog-wal-compaction.md) | Draft |
| 0010 | [Result-cache key normalization and an extent cache](0010-result-cache-extent-key.md) | Draft |
| 0010 | [Result-cache key normalization and an extent cache](0010-result-cache-extent-key.md) | Accepted |
| 0011 | [One cost-aware admission layer at the engine boundary](0011-engine-admission-classes.md) | Draft |
| 0012 | [Bounded trace ranking for drill-down](0012-bounded-trace-ranking.md) | Implemented |
| 0013 | [Indexed trace logs](0013-log-trace-lookup.md) | Implemented |
Expand Down
2 changes: 1 addition & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ type Config struct {
// an older one is rerun. A request with Cache-Control: no-cache, such as
// a dashboard's manual refresh, always reruns. Zero disables the cache;
// concurrent identical requests still share one execution.
QueryCacheTTL time.Duration `group:"server" env:"PITOT_QUERY_CACHE_TTL" default:"10s"`
QueryCacheTTL time.Duration `group:"server" env:"PITOT_QUERY_CACHE_TTL" default:"1m"`
// The DuckDB knobs below self-size where possible and otherwise default to
// values validated on the reference deployment target, a small shared VM
// (Hetzner CPX32: 4 vCPU, 8 GB RAM, 160 GB disk). There the self-sizing
Expand Down
2 changes: 1 addition & 1 deletion internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func TestLoadReturnsDefaults(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if cfg.Addr != "127.0.0.1:7520" || cfg.DataDir != "./data" || cfg.IngestBatchSize != 50000 || cfg.IngestMaxFutureSkew != 5*time.Minute || cfg.RollupInterval != time.Minute || cfg.RetentionDays != 30 || cfg.DefaultNamespace != "default" || !cfg.MCPEnabled || !cfg.AlertEnabled || cfg.AIProvider != "" {
if cfg.Addr != "127.0.0.1:7520" || cfg.DataDir != "./data" || cfg.IngestBatchSize != 50000 || cfg.IngestMaxFutureSkew != 5*time.Minute || cfg.RollupInterval != time.Minute || cfg.QueryCacheTTL != time.Minute || cfg.RetentionDays != 30 || cfg.DefaultNamespace != "default" || !cfg.MCPEnabled || !cfg.AlertEnabled || cfg.AIProvider != "" {
t.Fatal("built-in defaults were not resolved")
}
if cfg.DuckDBThreads != runtime.GOMAXPROCS(0) || cfg.DuckDBMaxConns < minDuckDBConns || cfg.DuckDBMaxConns > maxAutoDuckDBConns {
Expand Down
20 changes: 16 additions & 4 deletions internal/query/admission_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"slices"
"sync"
"testing"
"time"
Expand Down Expand Up @@ -408,6 +409,7 @@ func TestRefusedRefreshEmitsNeitherCachedNorTextPanels(t *testing.T) {
d := cacheDashboard()
uncached := d.Panels[0]
uncached.ID = "uncached"
uncached.Query = &Spec{From: "spans", Measures: []string{"count()"}}
d.Panels = append(d.Panels, uncached, Panel{ID: "note", Title: "Note", Viz: "text", Content: "hi"})
if _, err := e.Run(t.Context(), RunRequest{Dashboard: d, Panels: []string{d.Panels[0].ID}}); err != nil {
t.Fatal(err)
Expand Down Expand Up @@ -535,6 +537,9 @@ func TestFullRefreshCoalescesWithoutAnotherExecutionTicket(t *testing.T) {
for i := 1; i < 15; i++ {
p := d.Panels[0]
p.ID = fmt.Sprint("panel_", i)
q := *p.Query
q.Limit = i
p.Query = &q
d.Panels = append(d.Panels, p)
}
type answer struct {
Expand Down Expand Up @@ -564,7 +569,13 @@ func TestFullRefreshCoalescesWithoutAnotherExecutionTicket(t *testing.T) {
time.Sleep(time.Millisecond)
}
second := make(chan answer, 1)
go func() { r, err := e.Run(ctx, RunRequest{Dashboard: d}); second <- answer{r, err} }()
other := d
other.Name = "Second viewer"
other.Panels = slices.Clone(d.Panels)
for i := range other.Panels {
other.Panels[i].ID = fmt.Sprint("copy_", i)
}
go func() { r, err := e.Run(ctx, RunRequest{Dashboard: other}); second <- answer{r, err} }()
deadline = time.Now().Add(time.Second)
for {
e.cache.mu.Lock()
Expand All @@ -587,13 +598,14 @@ func TestFullRefreshCoalescesWithoutAnotherExecutionTicket(t *testing.T) {
time.Sleep(time.Millisecond)
}
close(gate.release)
for _, done := range []chan answer{first, second} {
for viewer, done := range []chan answer{first, second} {
want := []Dashboard{d, other}[viewer]
a := <-done
if a.err != nil || len(a.results) != 15 {
t.Fatalf("results=%d err=%v", len(a.results), a.err)
}
for _, r := range a.results {
if r.Status != StatusOK {
for i, r := range a.results {
if r.Status != StatusOK || r.ID != want.Panels[i].ID {
t.Fatalf("panel=%+v", r)
}
}
Expand Down
51 changes: 46 additions & 5 deletions internal/query/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"sync"
"time"
Expand All @@ -25,12 +26,22 @@ type Parser interface {

// Checked is what the database-backed checks produced.
type Checked struct {
SQL map[string]checkedPanelSQL // panel id → SQL identity from validation
SQLParams map[string][]string // panel id → referenced dashboard variables
AnnotationFilters map[string][]AnnotationFilter // panel id → projected annotation filters
Filters map[string][]Filter // panel id → filters
VarFilters map[string][]Filter // variable name → filters
Measures map[string][]Measure // panel id → measures
}

// Canonical is the validated one-minute expansion. BucketTemplate preserves
// the positions where a different execution step changes the SQL.
type checkedPanelSQL struct {
Canonical string
WindowColumns []string
BucketTemplate string
}

// isOperational reports whether err is the engine's or the caller's failure
// (cancellation, deadline, interrupt, closed database) rather than a fault in
// the spec. The engine reports a cancelled query as a bare interrupt.
Expand Down Expand Up @@ -62,6 +73,8 @@ type checkMemo struct {
}

type memoEntry struct {
sql checkedPanelSQL
sqlParams []string
vars map[string][]Filter
annotation []AnnotationFilter
filters []Filter
Expand Down Expand Up @@ -130,7 +143,11 @@ func checkWith(ctx context.Context, parser Parser, d *Dashboard, memo *checkMemo
// no panels after isolating invalid ones, but must still check variables.
func checkValidated(ctx context.Context, parser Parser, d *Dashboard, memo *checkMemo) (*Checked, Problems, error) {
var problems Problems
checked := &Checked{AnnotationFilters: map[string][]AnnotationFilter{}, Filters: map[string][]Filter{}, VarFilters: map[string][]Filter{}, Measures: map[string][]Measure{}}
checked := &Checked{
SQL: map[string]checkedPanelSQL{}, SQLParams: map[string][]string{},
AnnotationFilters: map[string][]AnnotationFilter{}, Filters: map[string][]Filter{},
VarFilters: map[string][]Filter{}, Measures: map[string][]Measure{},
}
earlier := map[string]Variable{}
vars := varsHash(d.Variables)
varsKey := memoKey(vars, nil)
Expand Down Expand Up @@ -169,6 +186,9 @@ func checkValidated(ctx context.Context, parser Parser, d *Dashboard, memo *chec
path := fmt.Sprintf("panels[%d]", i)
key := memoKey(vars, p)
if entry, ok := memo.get(key); ok {
if entry.sql.Canonical != "" {
checked.SQL[p.ID], checked.SQLParams[p.ID] = entry.sql, entry.sqlParams
}
if entry.annotation != nil {
checked.AnnotationFilters[p.ID] = entry.annotation
}
Expand Down Expand Up @@ -267,41 +287,62 @@ func checkValidated(ctx context.Context, parser Parser, d *Dashboard, memo *chec
}

case p.SQL != "":
if err := checkSQLPanel(ctx, parser, p, earlier); err != nil {
if err := checkSQLPanel(ctx, parser, p, earlier, checked); err != nil {
if isOperational(err) {
return nil, nil, err
}
problems = append(problems, sqlProblem(path+".sql", err))
}
}
if len(problems) == before {
memo.put(key, memoEntry{annotation: checked.AnnotationFilters[p.ID], filters: checked.Filters[p.ID], measures: checked.Measures[p.ID]})
memo.put(key, memoEntry{
sql: checked.SQL[p.ID], sqlParams: checked.SQLParams[p.ID],
annotation: checked.AnnotationFilters[p.ID], filters: checked.Filters[p.ID], measures: checked.Measures[p.ID],
})
}
}
return checked, problems, nil
}

func checkSQLPanel(ctx context.Context, parser Parser, p *Panel, vars map[string]Variable) error {
expanded, _, err := expandMacros(p.SQL, time.Minute)
func checkSQLPanel(ctx context.Context, parser Parser, p *Panel, vars map[string]Variable, checked *Checked) error {
expanded, windowColumns, err := expandMacros(p.SQL, time.Minute)
if err != nil {
return err
}
canonical, err := canonicalSQL(ctx, parser, expanded)
if err != nil {
return err
}
var params []string
query, describe, _, err := bindParams(canonical, func(name string) ([]any, bool, error) {
if name == "__from" || name == "__to" {
return []any{time.Time{}}, false, nil
}
if _, ok := vars[name]; !ok {
return nil, false, fmt.Errorf("$%s is not a dashboard variable", name)
}
params = append(params, name)
return []any{""}, false, nil
})
if err != nil {
return err
}
slices.Sort(params)
checked.SQLParams[p.ID] = slices.Compact(params)
identity := checkedPanelSQL{Canonical: canonical, WindowColumns: windowColumns}
if bucketMacro.MatchString(p.SQL) {
// Keep a symbolic step for keying only. The one-minute rendering
// alone would alias a literal interval at every other width.
template, _, err := expandPanelMacros(p.SQL, "pitot_panel_bucket_step")
if err == nil {
identity.BucketTemplate, err = canonicalSQL(ctx, parser, template)
}
if err != nil {
// A key-only rendering cannot invalidate an executable statement.
identity.BucketTemplate = p.SQL
}
}
checked.SQL[p.ID] = identity
_, _, err = parser.PrepareTelemetrySQL(ctx, query, describe, 1)
if err != nil || p.Viz != "state_timeline" {
return err
Expand Down
Loading
Loading