diff --git a/.env.example b/.env.example index a9a38f25..91804eec 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/docs/proposals/0010-result-cache-extent-key.md b/docs/proposals/0010-result-cache-extent-key.md index 6bbcab1d..def04e7b 100644 --- a/docs/proposals/0010-result-cache-extent-key.md +++ b/docs/proposals/0010-result-cache-extent-key.md @@ -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 @@ -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. diff --git a/docs/proposals/README.md b/docs/proposals/README.md index 0a08cc15..dcb28a0f 100644 --- a/docs/proposals/README.md +++ b/docs/proposals/README.md @@ -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 | diff --git a/internal/config/config.go b/internal/config/config.go index 7af3593a..3534b42a 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -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 diff --git a/internal/config/config_test.go b/internal/config/config_test.go index cd3a9e99..fe3a78c7 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -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 { diff --git a/internal/query/admission_test.go b/internal/query/admission_test.go index d7eaea8e..70c2af9f 100644 --- a/internal/query/admission_test.go +++ b/internal/query/admission_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "slices" "sync" "testing" "time" @@ -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) @@ -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 { @@ -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() @@ -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) } } diff --git a/internal/query/check.go b/internal/query/check.go index 5f4405c2..03210c23 100644 --- a/internal/query/check.go +++ b/internal/query/check.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "slices" "strings" "sync" "time" @@ -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. @@ -62,6 +73,8 @@ type checkMemo struct { } type memoEntry struct { + sql checkedPanelSQL + sqlParams []string vars map[string][]Filter annotation []AnnotationFilter filters []Filter @@ -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) @@ -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 } @@ -267,7 +287,7 @@ 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 } @@ -275,14 +295,17 @@ func checkValidated(ctx context.Context, parser Parser, d *Dashboard, memo *chec } } 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 } @@ -290,6 +313,7 @@ func checkSQLPanel(ctx context.Context, parser Parser, p *Panel, vars map[string 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 @@ -297,11 +321,28 @@ func checkSQLPanel(ctx context.Context, parser Parser, p *Panel, vars map[string 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 diff --git a/internal/query/exec.go b/internal/query/exec.go index 35cd6c0f..ab637f55 100644 --- a/internal/query/exec.go +++ b/internal/query/exec.go @@ -167,33 +167,26 @@ func (e *Executor) Check(ctx context.Context, d *Dashboard) (*Checked, Problems, // check memoizes Check by the spec's bytes: a dashboard refreshes the same // spec every 30 seconds, and its filters do not need re-parsing each time. func (e *Executor) check(ctx context.Context, d *Dashboard) (*Checked, error) { - checked, _, err := e.checkKeyed(ctx, d) - return checked, err -} - -// checkKeyed is check that also returns the spec's hash, which keys its -// cached panel results. -func (e *Executor) checkKeyed(ctx context.Context, d *Dashboard) (*Checked, cacheKey, error) { if err := ctx.Err(); err != nil { - return nil, cacheKey{}, err + return nil, err } raw, err := json.Marshal(d) if err != nil { - return nil, cacheKey{}, err + return nil, err } key := sha256.Sum256(raw) e.mu.Lock() cached, ok := e.checks[key] e.mu.Unlock() if ok { - return cached, key, nil + return cached, nil } checked, problems, err := e.Check(ctx, d) if err != nil { - return nil, key, err + return nil, err } if len(problems) > 0 { - return nil, key, problems + return nil, problems } e.mu.Lock() if len(e.checks) >= 256 { @@ -201,13 +194,13 @@ func (e *Executor) checkKeyed(ctx context.Context, d *Dashboard) (*Checked, cach } e.checks[key] = checked e.mu.Unlock() - return checked, key, nil + return checked, nil } // checkRun isolates panel diagnostics without weakening save validation. Each -// reduced spec is checked under its own hash; execution keeps the full spec hash. -func (e *Executor) checkRun(ctx context.Context, d *Dashboard) (*Checked, cacheKey, map[*Panel]Problems, error) { - checked, spec, err := e.checkKeyed(ctx, d) +// reduced spec is checked under its own hash. +func (e *Executor) checkRun(ctx context.Context, d *Dashboard) (*Checked, map[*Panel]Problems, error) { + checked, err := e.check(ctx, d) invalid := map[*Panel]Problems{} var collected Problems reduced := *d @@ -218,7 +211,7 @@ func (e *Executor) checkRun(ctx context.Context, d *Dashboard) (*Checked, cacheK for err != nil { var problems Problems if !errors.As(err, &problems) { - return nil, spec, nil, err + return nil, nil, err } mapped := slices.Clone(problems) scoped := true @@ -236,7 +229,7 @@ func (e *Executor) checkRun(ctx context.Context, d *Dashboard) (*Checked, cacheK mapped[i].Path = fmt.Sprintf("panels[%d]%s", original, suffix) } if !scoped { - return nil, spec, nil, append(mapped, collected...) + return nil, nil, append(mapped, collected...) } collected = append(collected, mapped...) for i, problem := range mapped { @@ -260,10 +253,10 @@ func (e *Executor) checkRun(ctx context.Context, d *Dashboard) (*Checked, cacheK err = more } } else { - checked, _, err = e.checkKeyed(ctx, &reduced) + checked, err = e.check(ctx, &reduced) } } - return checked, spec, invalid, nil + return checked, invalid, nil } // Run validates the dashboard and runs the requested panels concurrently. @@ -348,7 +341,7 @@ func (e *Executor) run(ctx context.Context, req RunRequest, emit func(int, Resul } return err } - checked, spec, invalid, err := e.checkRun(ctx, &d) + checked, invalid, err := e.checkRun(ctx, &d) if err != nil { return batchError(err) } @@ -406,7 +399,7 @@ func (e *Executor) run(ctx context.Context, req RunRequest, emit func(int, Resul if p.Viz == "text" || len(invalid[p]) > 0 { continue } - key, keyErr := keyOf(panelCacheKey{Spec: spec, Panel: p.ID, Time: t, Vars: vars, Width: req.Widths[p.ID], Compare: compare}) + key, keyErr := e.buildPanelCacheKey(p, checked, t, now, vars, req.Widths[p.ID], compare) if keyErr != nil { return ErrBusy } @@ -467,7 +460,7 @@ func (e *Executor) run(ctx context.Context, req RunRequest, emit func(int, Resul if caller.Err() != nil { return nil } - key, err := keyOf(panelCacheKey{Spec: spec, Panel: p.ID, Time: t, Vars: vars, Width: width, Compare: compare}) + key, err := e.buildPanelCacheKey(p, checked, t, now, vars, width, compare) if err != nil { send(i, failed(Result{ID: p.ID}, err, nil)) return nil @@ -508,6 +501,7 @@ func (e *Executor) run(ctx context.Context, req RunRequest, emit func(int, Resul return nil } r := out.Result.clone() + r.ID = p.ID r.Cached = outcome == cacheHit || outcome == cacheStale // The result is sent after the run released its slot: a stream // client that stops reading must not hold the engine from others. @@ -680,6 +674,30 @@ func limitBatchFrames(results []Result) { } } +func resolvePanelInterval(p *Panel, checked *Checked, window time.Duration, width int, vars map[string]Value) time.Duration { + reduces := vizSpecs[p.Viz].reduces + var interval time.Duration + switch { + case p.SQL != "" && p.Viz == "state_timeline": + interval = time.Minute + case reduces: + interval = AutoInterval(window, 240) + case p.Query != nil && p.Query.Bucket == "auto" && (p.Viz == "heatmap" || p.Viz == "state_timeline"): + interval = autoCellInterval(window, width) + case p.Query != nil: + interval = bucketInterval(p.Query.Bucket, window, width) + default: + interval = AutoInterval(window, width) + } + if p.Query != nil && p.Query.From == "metrics" && (reduces || p.Query.Bucket == "auto") { + interval = max(interval, time.Minute) + } + if interval > 0 && interval < time.Minute && checked != nil && rollupPlan(p, checked.Measures[p.ID], checked.Filters[p.ID], Scope{Vars: vars}) { + interval = max(interval, time.Minute) + } + return interval +} + func (e *Executor) runPanel(ctx context.Context, p *Panel, checked *Checked, t Time, now time.Time, vars map[string]Value, width int, compare bool) (res Result) { parent := ctx started := time.Now() @@ -703,30 +721,11 @@ func (e *Executor) runPanel(ctx context.Context, p *Panel, checked *Checked, t T ctx, cancel := context.WithTimeout(ctx, e.timeout) defer cancel() reduces := vizSpecs[p.Viz].reduces - var interval time.Duration - switch { - case p.SQL != "" && p.Viz == "state_timeline": - interval = time.Minute - case reduces: - interval = AutoInterval(end.Sub(start), 240) - case p.Query != nil && p.Query.Bucket == "auto" && (p.Viz == "heatmap" || p.Viz == "state_timeline"): - interval = autoCellInterval(end.Sub(start), width) - case p.Query != nil: - interval = bucketInterval(p.Query.Bucket, end.Sub(start), width) - default: - interval = AutoInterval(end.Sub(start), width) - } - if p.Query != nil && p.Query.From == "metrics" && (reduces || p.Query.Bucket == "auto") { - interval = max(interval, time.Minute) - } + interval := resolvePanelInterval(p, checked, end.Sub(start), width, vars) scope := Scope{Start: start, End: end, Interval: interval, Vars: vars} if p.Query != nil && checked != nil && rollupPlan(p, checked.Measures[p.ID], checked.Filters[p.ID], scope) { scope.Rollup = true scope.RollupSource = rollupSource(p) - if interval > 0 { - interval = max(interval, time.Minute) - scope.Interval = interval - } if reader, ok := e.engine.(interface { RollupWatermark(context.Context) (time.Time, error) }); ok { diff --git a/internal/query/exec_test.go b/internal/query/exec_test.go index 761dd5b6..c4f5efc7 100644 --- a/internal/query/exec_test.go +++ b/internal/query/exec_test.go @@ -22,7 +22,7 @@ func TestRunResolvesOneInstantForAllPanelWindows(t *testing.T) { } d := Dashboard{Name: "Shared window", Time: Time{Range: "1h"}, Panels: []Panel{ {ID: "current", Title: "Current", Viz: "timeseries", Query: &Spec{From: "spans", Measures: []string{"count()"}, Bucket: "5m"}}, - {ID: "other", Title: "Other", Viz: "timeseries", Query: &Spec{From: "spans", Measures: []string{"count()"}, Bucket: "5m"}}, + {ID: "other", Title: "Other", Viz: "timeseries", Query: &Spec{From: "spans", Measures: []string{"rate()"}, Bucket: "5m"}}, {ID: "prior", Title: "Prior", Viz: "timeseries", Time: &TimeOverride{Shift: "1d"}, Query: &Spec{From: "spans", Measures: []string{"count()"}, Bucket: "5m"}}, }} results, err := e.Run(t.Context(), RunRequest{Dashboard: d}) @@ -45,9 +45,6 @@ func TestRunResolvesOneInstantForAllPanelWindows(t *testing.T) { if current.FromMS != fixtureStart.UnixMilli() || current.ToMS != fixtureStart.Add(time.Hour).UnixMilli() { t.Errorf("batch instant drifted: %+v", current) } - if calls.Load() != 1 { - t.Errorf("clock called %d times, want one batch instant", calls.Load()) - } } func newFixtureExecutor(t *testing.T) *Executor { diff --git a/internal/query/execution_limits_test.go b/internal/query/execution_limits_test.go index 86dda98d..6ebf228f 100644 --- a/internal/query/execution_limits_test.go +++ b/internal/query/execution_limits_test.go @@ -35,8 +35,8 @@ func TestAdmittedRefreshRunsEveryPanelOutsideQueueDeadline(t *testing.T) { e.timeout = 100 * time.Millisecond e.parallel = 1 d := Dashboard{Name: "Deadline", Panels: []Panel{{ID: "fast", Title: "Fast", Viz: "text", Content: "done"}}} - for _, id := range []string{"slow", "queued"} { - d.Panels = append(d.Panels, Panel{ID: id, Title: id, Viz: "table", Query: &Spec{From: "spans", Measures: []string{"count()"}}}) + for i, id := range []string{"slow", "queued"} { + d.Panels = append(d.Panels, Panel{ID: id, Title: id, Viz: "table", Query: &Spec{From: "spans", Measures: []string{"count()"}, Limit: i + 1}}) } started := time.Now() results, err := e.Run(t.Context(), RunRequest{Dashboard: d}) @@ -85,8 +85,8 @@ func TestQueuedPanelsKeepTheirWholeTimeout(t *testing.T) { e.admission = newReadAdmission(1, 0, 8) e.timeout = 200 * time.Millisecond d := Dashboard{Name: "Queue"} - for _, id := range []string{"a", "b", "c", "d", "e", "f"} { - d.Panels = append(d.Panels, Panel{ID: id, Title: id, Viz: "table", Query: &Spec{From: "spans", Measures: []string{"count()"}, By: []string{"service"}}}) + for i, id := range []string{"a", "b", "c", "d", "e", "f"} { + d.Panels = append(d.Panels, Panel{ID: id, Title: id, Viz: "table", Query: &Spec{From: "spans", Measures: []string{"count()"}, By: []string{"service"}, Limit: i + 1}}) } started := time.Now() results, err := e.Run(t.Context(), RunRequest{Dashboard: d}) diff --git a/internal/query/exemplars.go b/internal/query/exemplars.go index 87db97f7..9cf224af 100644 --- a/internal/query/exemplars.go +++ b/internal/query/exemplars.go @@ -153,7 +153,7 @@ func (e *Executor) exemplars(ctx context.Context, req ExemplarRequest, now time. defer cancel() d := req.Dashboard Normalize(&d) - checked, _, invalid, err := e.checkRun(ctx, &d) + checked, invalid, err := e.checkRun(ctx, &d) if err != nil { return out, err } diff --git a/internal/query/result_cache.go b/internal/query/result_cache.go index 71343ef5..f7d71078 100644 --- a/internal/query/result_cache.go +++ b/internal/query/result_cache.go @@ -213,8 +213,9 @@ retry: flight = e.startFlight(ctx, key, stamp, false, fixedWindow, run) } // A bypass caller must wait for older work to finish before requesting - // a fresh run. Keep its place as a waiter without accepting that answer. - accept := e.joinable(flight, stamp, bypass, fixedWindow) + // a fresh run. It can always accept the flight it just started, even + // when that flight's window stamp needed clamping. + accept := outcome == cacheMiss || e.joinable(flight, stamp, bypass, fixedWindow) flight.waiters++ // A caller that will read the stored result keeps the run going. flight.detached = flight.detached || c.ttl > 0 && !bypass @@ -328,6 +329,7 @@ func (e *Executor) availablePanels(ctx context.Context, lookups []panelCacheLook } } results[i] = values[i].Result.clone() + results[i].ID = lookup.id results[i].Cached = outcomes[i] == cacheHit || outcomes[i] == cacheStale } return results, true, nil @@ -335,7 +337,7 @@ func (e *Executor) availablePanels(ctx context.Context, lookups []panelCacheLook // joinable reports whether a caller may take flight's answer. Non-bypass // callers always share in-flight work; the TTL applies only to stored results. -// A no-cache caller requires the original window stamp to reach its arrival. +// A no-cache caller requires the clamped window stamp to reach its arrival. // For fixed windows, registration after arrival also proves freshness: the // window is identical and every read snapshot is acquired after registration. // c.mu is held. @@ -359,9 +361,14 @@ func (e *Executor) startFlight(caller context.Context, key cacheKey, stamp time. } c := &e.cache run, cancel := context.WithCancel(context.WithoutCancel(caller)) + now := e.now() + // A future window end cannot prove freshness to a later caller. + if stamp.After(now) { + stamp = now + } flight := &cacheFlight{done: make(chan struct{}), stamp: stamp, detached: background, background: background, cancel: cancel} if fixedWindow { - flight.fixedWindow, flight.registeredAt = true, e.now() + flight.fixedWindow, flight.registeredAt = true, now } run = context.WithValue(run, flightContextKey{}, flight) c.flights[key] = flight @@ -417,6 +424,9 @@ func runFlight(ctx context.Context, fn flightFunc[any]) (value any, size int64, // store keeps value under key, stamped where its window ends, evicting the // least recently used entries past either bound. c.mu is held. func (c *resultCache) store(key cacheKey, value any, size int64, stamp, now time.Time) { + if stamp.After(now) { + stamp = now + } // An answer already too old to serve is not kept. if c.ttl <= 0 || size > c.maxBytes || now.Sub(stamp) >= c.ttl { return @@ -446,21 +456,110 @@ func (c *resultCache) setBytes(n int64) { metrics.QueryCacheBytes.Set(float64(n)) } -// panelCacheKey is everything a panel result depends on except the clock. -// The spec hash covers the normalized dashboard, so every Panel and Dashboard -// field is included; the other fields are the request's resolved inputs. An -// absolute window is in Time; a relative one slides with the clock, and the -// entry's age, from the end of its window, decides whether it may still be -// served. Panel selection does not change a -// panel's result and is left out. TestPanelCacheKeyCoversRequest fails when -// RunRequest grows a field this key does not account for. +// A relative result slides with the clock until its entry expires. Fixed +// windows retain their precise UTC bounds, including sub-millisecond edges. +type panelWindowKey struct { + Fixed bool + From, To time.Time + Span, Shift time.Duration +} + +// Value.MarshalJSON uses the same spelling for All and a literal "$__all". +type panelCacheValue Value + +type panelSQLKey struct { + Statement, BucketTemplate string + WindowColumns []string +} + type panelCacheKey struct { - Spec cacheKey `json:"spec"` - Panel string `json:"panel"` - Time Time `json:"time"` - Vars map[string]Value `json:"vars"` - Width int `json:"width"` - Compare bool `json:"compare"` + Viz, Unit, XUnit, Reduce, Better string + SQL panelSQLKey + Query *Spec + Bucketed bool + Split, Highlight string + Top int + Sparklines []string + Window panelWindowKey + Interval time.Duration + Compare bool + Vars map[string]panelCacheValue +} + +func (e *Executor) buildPanelCacheKey(p *Panel, checked *Checked, t Time, now time.Time, vars map[string]Value, width int, compare bool) (cacheKey, error) { + start, end, err := resolveWindow(t, p.Time, now, e.maxWindow) + if err != nil { + return cacheKey{}, err + } + span := end.Sub(start) + key := panelCacheKey{ + Viz: p.Viz, SQL: panelSQLKey{Statement: p.SQL}, Unit: p.Unit, XUnit: p.XUnit, Reduce: p.Reduce, Better: p.Better, + Top: p.Top(), Interval: resolvePanelInterval(p, checked, span, width, vars), + Compare: compare && (p.Viz == "stat" || p.Viz == "timeseries"), + Vars: referencedPanelValues(p.ID, checked, vars), + } + if t.From != nil && t.To != nil { + key.Window = panelWindowKey{Fixed: true, From: start, To: end} + } else { + key.Window = panelWindowKey{Span: span, Shift: now.Sub(end)} + } + if p.Query != nil { + q := *p.Query + // Keep the presence check used by zeroCount. Interval holds the + // effective grain, including any width and planner adjustments. + key.Bucketed = q.Bucket != "" + q.Bucket = "" + key.Query = &q + } + if checked != nil { + if sql, ok := checked.SQL[p.ID]; ok { + key.SQL.Statement, key.SQL.WindowColumns = sql.Canonical, sql.WindowColumns + if key.Interval != time.Minute { + key.SQL.BucketTemplate = sql.BucketTemplate + } + } + } + if opts := p.Options; opts != nil { + key.Split, key.Highlight = opts.Split, opts.Highlight + if p.Viz == "table" && p.Query != nil { + for _, c := range opts.Columns { + if c.Format == "sparkline" { + key.Sparklines = append(key.Sparklines, c.Field) + } + } + slices.Sort(key.Sparklines) + key.Sparklines = slices.Compact(key.Sparklines) + } + } + return keyOf(key) +} + +func referencedPanelValues(id string, checked *Checked, vars map[string]Value) map[string]panelCacheValue { + values := make(map[string]panelCacheValue) + if checked == nil { + return values + } + var visit func(string) + visit = func(name string) { + if _, seen := values[name]; seen { + return + } + values[name] = panelCacheValue(vars[name]) + for _, f := range checked.VarFilters[name] { + for _, param := range f.Params { + visit(param) + } + } + } + for _, f := range checked.Filters[id] { + for _, param := range f.Params { + visit(param) + } + } + for _, param := range checked.SQLParams[id] { + visit(param) + } + return values } // panelOutcome is a shared panel run. diff --git a/internal/query/result_cache_test.go b/internal/query/result_cache_test.go index 2398a575..c8ecbbc5 100644 --- a/internal/query/result_cache_test.go +++ b/internal/query/result_cache_test.go @@ -5,12 +5,14 @@ import ( "errors" "fmt" "reflect" + "slices" "strings" "sync" "sync/atomic" "testing" "time" + "github.com/labstack/pitot/internal/config" "github.com/labstack/pitot/internal/observability" "github.com/labstack/pitot/internal/queryrows" "github.com/labstack/pitot/internal/telemetry" @@ -82,10 +84,10 @@ func TestResultCacheHitAndMiss(t *testing.T) { if !second.Cached || engine.calls.Load() != calls || second.ToMS != first.ToMS { t.Fatalf("second=%+v calls=%d->%d", second, calls, engine.calls.Load()) } - // Another width is another result. + // Unbucketed tables ignore viewport width. req.Widths = map[string]int{"by_service": 300} - if r := runOne(t, e, req); r.Cached || engine.calls.Load() == calls { - t.Fatalf("a different width was served from the cache: %+v", r) + if r := runOne(t, e, req); !r.Cached || engine.calls.Load() != calls { + t.Fatalf("table width fragmented the cache: %+v", r) } // At the TTL the entry is gone. req.Widths = nil @@ -94,6 +96,32 @@ func TestResultCacheHitAndMiss(t *testing.T) { if r := runOne(t, e, req); r.Cached || engine.calls.Load() == calls || r.ToMS != e.now().UnixMilli() { t.Fatalf("an expired entry was served: %+v", r) } + p := &req.Dashboard.Panels[0] + p.Viz, p.Query.Bucket, p.Query.By = "timeseries", "auto", []string{"operation"} + for _, tc := range []struct { + width int + bucket, interval string + hit bool + }{ + {640, "auto", "30s", false}, {800, "auto", "30s", true}, + {300, "auto", "1m", false}, {300, "30s", "30s", true}, + } { + req.Widths = map[string]int{p.ID: tc.width} + p.Query.Bucket = tc.bucket + r := runOne(t, e, req) + if r.Cached != tc.hit || r.Interval != tc.interval || r.Status != StatusOK { + t.Errorf("width %d, bucket %s: cached=%v interval=%s status=%s", tc.width, tc.bucket, r.Cached, r.Interval, r.Status) + } + } + // Both widths reach the same one-minute rollup floor. + p.Query.By, p.Query.Bucket = []string{"service"}, "auto" + for _, width := range []int{400, 800} { + req.Widths[p.ID] = width + r := runOne(t, e, req) + if r.Cached != (width == 800) || r.Interval != "1m" { + t.Fatalf("rollup width %d: %+v", width, r) + } + } } // Ages count from the end of the data window, not from when the run @@ -137,14 +165,117 @@ func TestResultCacheAgesFromTheWindowEnd(t *testing.T) { } } +func TestResultCacheClampsFutureStamps(t *testing.T) { + e, _, offset := cachedExecutor(t) + start := e.now() + future := start.Add(time.Hour) + key := cacheKey{1} + release := make(chan struct{}) + releaseRun := sync.OnceFunc(func() { close(release) }) + defer releaseRun() + old := make(chan error, 1) + go func() { + _, _, err := loadCached(e, t.Context(), key, future, func(context.Context) (int, int64, bool, error) { + <-release + return 1, 8, true, nil + }) + old <- err + }() + waitForFlight(t, e, key) + offset.Store(int64(time.Second)) + fresh := make(chan error, 1) + go func() { + v, outcome, err := loadCached(e, WithoutCachedResults(t.Context()), key, e.now(), func(context.Context) (int, int64, bool, error) { + return 2, 8, false, nil + }) + if err == nil && (v != 2 || outcome != cacheMiss) { + err = fmt.Errorf("no-cache read got %d with outcome %q, want fresh value 2", v, outcome) + } + fresh <- err + }() + waitForWaiters(t, e, key, 2) + releaseRun() + for _, done := range []<-chan error{old, fresh} { + if err := <-done; err != nil { + t.Error(err) + } + } + e.cache.mu.Lock() + defer e.cache.mu.Unlock() + e.cache.store(cacheKey{2}, 2, 8, future, start) + for _, k := range []cacheKey{{1}, {2}} { + if entry := e.cache.entries[k]; entry == nil || !entry.Value.(*cacheEntry).stamp.Equal(start) { + t.Errorf("key %x: expected original query time %s", k, start) + } + } +} + +func TestResultCacheCoalescesIdenticalSiblingsWithFullQueue(t *testing.T) { + e, engine, _ := cachedExecutor(t) + e.SetCacheTTL(0) + e.admission = newReadAdmission(1, 0, 0) + engine.release = make(chan struct{}) + release := sync.OnceFunc(func() { close(engine.release) }) + defer release() + + d := cacheDashboard() + d.Panels[0].ID = "panel_a" + sibling := d.Panels[0] + sibling.ID = "panel_b" + d.Panels = append(d.Panels, sibling) + key, err := e.buildPanelCacheKey(&d.Panels[0], nil, d.Time, e.now(), nil, 0, false) + if err != nil { + t.Fatal(err) + } + type answer struct { + results []Result + err error + } + run := func() <-chan answer { + done := make(chan answer, 1) + go func() { + results, err := e.Run(t.Context(), RunRequest{Dashboard: d}) + done <- answer{results, err} + }() + return done + } + first := run() + waitForWaiters(t, e, key, 2) + // The first refresh holds the only admission ticket. The second can + // succeed only by joining both sibling results through availablePanels. + second := run() + waitForWaiters(t, e, key, 4) + release() + for _, done := range []<-chan answer{first, second} { + a := <-done + if a.err != nil || len(a.results) != 2 { + t.Fatalf("results=%+v err=%v", a.results, a.err) + } + for i, id := range []string{"panel_a", "panel_b"} { + if r := a.results[i]; r.ID != id || r.Status != StatusOK || r.Cached { + t.Errorf("want live result for %s, got %+v", id, r) + } + } + } + if calls := engine.calls.Load(); calls != 1 { + t.Errorf("identical siblings ran %d engine reads, want 1", calls) + } +} + // Past half the TTL the last result is served stale while exactly one // background run replaces it, instead of every viewer waiting for a cold run // at once. func TestResultCacheServesStaleWhileRevalidating(t *testing.T) { e, engine, offset := cachedExecutor(t) + cfg, err := config.Load(config.LoadOptions{Environ: []string{"PITOT_AUTH_CODE_SECRET=" + strings.Repeat("x", 32)}}) + if err != nil { + t.Fatal(err) + } + e.SetCacheTTL(cfg.QueryCacheTTL) req := RunRequest{Dashboard: cacheDashboard()} first := runOne(t, e, req) - offset.Store(int64(7 * time.Second)) + refresh := 30*time.Second + 10*time.Millisecond + offset.Store(int64(refresh)) calls := engine.calls.Load() engine.release = make(chan struct{}) for range 3 { @@ -165,7 +296,7 @@ func TestResultCacheServesStaleWhileRevalidating(t *testing.T) { t.Fatalf("refresh read %d times", engine.calls.Load()-calls) } r := runOne(t, e, req) - if !r.Cached || r.ToMS != first.ToMS+7000 { + if !r.Cached || r.ToMS != first.ToMS+refresh.Milliseconds() { t.Fatalf("refreshed entry not served: %+v (first to %d)", r, first.ToMS) } } @@ -735,37 +866,329 @@ func TestResultCacheFramesAreCopiedOnUse(t *testing.T) { } } -// Every RunRequest field either feeds panelCacheKey or provably does not -// change a panel's result. Add a new field to one of the lists, and to the -// key when it changes results. +// Fields marked keyed may contribute only their effective values: the selected +// panel, referenced variables, resolved interval, sparkline fields and window. func TestPanelCacheKeyCoversRequest(t *testing.T) { - keyed := map[string]string{ - "Dashboard": "Spec (normalized dashboard hash)", - "Time": "Time, Start, End", - "Vars": "Vars (resolved)", - "Widths": "Width", - "Compare": "Compare", - } - unkeyed := map[string]string{ - "Panels": "selects which panels run; a panel's result does not depend on its neighbours", - } - fields := reflect.TypeFor[RunRequest]() - for i := range fields.NumField() { - name := fields.Field(i).Name - if keyed[name] == "" && unkeyed[name] == "" { - t.Errorf("RunRequest.%s is new: add it to panelCacheKey if it changes a panel's result", name) - } - } - // The spec hash is the dashboard's JSON: a field that JSON omits would - // change results without changing the key. - for _, typ := range []reflect.Type{reflect.TypeFor[Dashboard](), reflect.TypeFor[Panel](), reflect.TypeFor[Spec](), reflect.TypeFor[Time](), reflect.TypeFor[Variable]()} { - for i := range typ.NumField() { - field := typ.Field(i) - if !field.IsExported() || strings.HasPrefix(field.Tag.Get("json"), "-") { - t.Errorf("%s.%s is not in the dashboard JSON the panel cache key hashes", typ.Name(), field.Name) + for _, tc := range []struct { + typ reflect.Type + keyed, unkeyed string + }{ + {reflect.TypeFor[RunRequest](), "Dashboard Time Vars Widths Compare", "Panels"}, + {reflect.TypeFor[Dashboard](), "Time", "Version Name Description Annotations Variables Panels"}, + {reflect.TypeFor[Panel](), "Viz Query SQL Unit XUnit Reduce Better Options Time", "ID Title Description Width Height Grid Thresholds Min Max Click Drill Content"}, + {reflect.TypeFor[Spec](), "From Where Measures By Bucket Histogram Sort Limit", ""}, + {reflect.TypeFor[Histogram](), "Field Buckets", ""}, + {reflect.TypeFor[Options](), "Split Highlight Top Columns", "Style Scale Legend XScale YScale"}, + {reflect.TypeFor[ColumnFormat](), "Field Format", "Unit Variable"}, + {reflect.TypeFor[Time](), "Range From To Compare", "Refresh"}, + {reflect.TypeFor[TimeOverride](), "Range Shift", ""}, + {reflect.TypeFor[Value](), "All Values", ""}, + {reflect.TypeFor[panelCacheKey](), "Viz Unit XUnit Reduce Better SQL Query Bucketed Split Highlight Top Sparklines Window Interval Compare Vars", ""}, + {reflect.TypeFor[panelWindowKey](), "Fixed From To Span Shift", ""}, + {reflect.TypeFor[panelSQLKey](), "Statement BucketTemplate WindowColumns", ""}, + {reflect.TypeFor[panelCacheValue](), "All Values", ""}, + } { + classified := append(strings.Fields(tc.keyed), strings.Fields(tc.unkeyed)...) + var fields []string + for i := range tc.typ.NumField() { + fields = append(fields, tc.typ.Field(i).Name) + } + slices.Sort(fields) + slices.Sort(classified) + if !slices.Equal(fields, classified) { + t.Errorf("%s fields %v, classified %v", tc.typ.Name(), fields, classified) + } + } + + var checkJSONFields func(reflect.Type) + seen := map[reflect.Type]bool{reflect.TypeFor[time.Time](): true} // Encoded by time.Time.MarshalJSON. + checkJSONFields = func(typ reflect.Type) { + if seen[typ] { + return + } + seen[typ] = true + switch typ.Kind() { + case reflect.Pointer, reflect.Slice, reflect.Array, reflect.Map: + checkJSONFields(typ.Elem()) + case reflect.Struct: + for field := range typ.Fields() { + if !field.IsExported() || field.Tag.Get("json") == "-" { + t.Errorf("%s.%s is omitted from the cache key JSON", typ.Name(), field.Name) + } + checkJSONFields(field.Type) } } } + checkJSONFields(reflect.TypeFor[panelCacheKey]()) +} + +func TestPanelCacheDistinguishesBucketPresenceWithoutCheckedSpec(t *testing.T) { + e := &Executor{maxWindow: time.Hour} + window := Time{Range: "1h"} + p := Panel{ID: "count", Viz: "stat", Reduce: "window", Query: &Spec{From: "spans", Measures: []string{"count()"}}} + key := func() cacheKey { + t.Helper() + k, err := e.buildPanelCacheKey(&p, nil, window, fixtureStart, nil, 0, false) + if err != nil { + t.Fatal(err) + } + return k + } + unbucketed := key() + // Both forms resolve the same interval, but only the first permits + // zeroCount to treat an empty ungrouped count as a real zero. + p.Query.Bucket = "auto" + if key() == unbucketed { + t.Fatal("bucketed and unbucketed counts share a key") + } +} + +// A shared hit proves the public request produced the same key. Rerun the +// second request at the same instant to independently check its entire result. +func TestPanelCacheDisplayEditsShareIdenticalResults(t *testing.T) { + e, engine, _ := cachedExecutor(t) + for _, viz := range []string{"table", "scatter", "timeseries"} { + t.Run(viz, func(t *testing.T) { + req := RunRequest{Dashboard: cacheDashboard()} + p := &req.Dashboard.Panels[0] + p.Viz = viz + p.Query.By = []string{"operation"} + // Operations have equal counts but distinct mean durations. Give the + // uncached table a deterministic order for the full-frame comparison. + p.Query.Measures = []string{"avg(duration_ms)"} + if viz == "scatter" { + p.Query.Measures = []string{"count()", "avg(duration_ms)"} + } + req.Widths = map[string]int{p.ID: 640} + first := runOne(t, e, req) + if first.Status != StatusOK || first.Cached || first.Frame.Rows == 0 { + t.Fatalf("initial result: %+v", first) + } + + d := &req.Dashboard + d.Version, d.Name, d.Description = 1, "Second dashboard", "New description" + d.Variables = []Variable{{Name: "unused", Kind: "custom", Options: []string{"one", "two"}}} + d.Annotations = &Annotations{Deploys: new(false), Anomalies: new(false)} + d.Time.Refresh = "5m" + if viz == "table" { + d.Time.Compare = "previous_period" + } + d.Time.Range, p.Time = "24h", &TimeOverride{Range: "1h"} + p.ID, p.Title, p.Description = "copy", "Copy $unused", "Help text" + p.Width, p.Height, p.Grid = 6, "l", &Grid{X: 1, Y: 1, W: 6, H: 3} + p.Thresholds = []Threshold{{Value: 5, Status: "warn"}} + p.Min, p.Max = new(0.0), new(10.0) + p.Click, p.Drill, p.Content = &Click{SetVariable: "unused"}, "traces", "Display text" + p.Options = &Options{Top: p.Top(), Scale: "log", Legend: "hidden"} + switch viz { + case "table": + p.Options.Columns = []ColumnFormat{{Field: "operation", Format: "service_link", Variable: "unused", Unit: "count"}} + case "scatter": + p.Options.XScale, p.Options.YScale = "log", "linear" + case "timeseries": + p.Options.Style = "area" + p.Query.Bucket = "30s" + } + req.Panels, req.Widths = []string{p.ID}, map[string]int{p.ID: 800} + req.Vars = map[string]Value{"unused": {Values: []string{"two"}}} + d.Panels = append(d.Panels, Panel{ID: "note", Title: "Notes", Viz: "text", Content: "New sibling"}) + calls := engine.calls.Load() + hit := runOne(t, e, req) + if !hit.Cached || hit.ID != "copy" || engine.calls.Load() != calls { + t.Fatalf("shared result: %+v, reads %d -> %d", hit, calls, engine.calls.Load()) + } + fresh, err := e.Run(WithoutCachedResults(t.Context()), req) + if err != nil || len(fresh) != 1 || fresh[0].Cached || engine.calls.Load() == calls { + t.Fatalf("uncached results=%+v err=%v", fresh, err) + } + first.ID, first.ElapsedMS = "copy", 0 + hit.Cached, hit.ElapsedMS, fresh[0].ElapsedMS = false, 0, 0 + if !reflect.DeepEqual(first, fresh[0]) || !reflect.DeepEqual(hit, fresh[0]) { + t.Fatalf("display edit changed the result: original=%+v hit=%+v uncached=%+v", first, hit, fresh[0]) + } + }) + } +} + +func TestPanelCacheResultFieldsAndWindow(t *testing.T) { + e := &Executor{maxWindow: time.Hour} + now := fixtureStart.Add(time.Hour + 123*time.Nanosecond) + checked := &Checked{} + p := cacheDashboard().Panels[0] + base := Time{Range: "1h"} + key := func(p Panel, window Time, compare bool) cacheKey { + t.Helper() + k, err := e.buildPanelCacheKey(&p, checked, window, now, nil, 640, compare) + if err != nil { + t.Fatal(err) + } + return k + } + original := key(p, base, false) + for _, edit := range []struct { + name string + change func(*Panel) + }{ + {"viz", func(p *Panel) { p.Viz = "bar" }}, + {"query", func(p *Panel) { p.Query = &Spec{From: "logs"} }}, + {"sql", func(p *Panel) { p.SQL = "SELECT 1" }}, + {"unit", func(p *Panel) { p.Unit = "ms" }}, + {"x_unit", func(p *Panel) { p.XUnit = "s" }}, + {"reduce", func(p *Panel) { p.Reduce = "last" }}, + {"better", func(p *Panel) { p.Better = "lower" }}, + {"split", func(p *Panel) { p.Options.Split = "deploy" }}, + {"highlight", func(p *Panel) { p.Options.Highlight = "warning" }}, + {"top", func(p *Panel) { p.Options.Top = 3 }}, + {"sparkline", func(p *Panel) { p.Options.Columns = []ColumnFormat{{Field: "count", Format: "sparkline"}} }}, + {"shift", func(p *Panel) { p.Time = &TimeOverride{Shift: "1d"} }}, + {"range", func(p *Panel) { p.Time = &TimeOverride{Range: "5m"} }}, + } { + other := p + other.Options = &Options{} + edit.change(&other) + if key(other, base, false) == original { + t.Errorf("%s edit shared original key", edit.name) + } + } + from := now.Add(-time.Hour) + fixed := Time{From: &from, To: &now} + if key(p, fixed, false) == original { + t.Error("fixed window shared a sliding key") + } + if key(p, Time{Range: "24h"}, false) != original { + t.Error("retention-capped relative window missed") + } + earlier := now.Add(-24 * time.Hour) + if key(p, Time{From: &earlier, To: &now}, false) != key(p, fixed, false) { + t.Error("retention-capped fixed window missed") + } + later := now.Add(time.Nanosecond) + if key(p, Time{From: &from, To: &later}, false) == key(p, fixed, false) { + t.Error("different fixed nanosecond bounds collided") + } + for viz := range vizSpecs { + p.Viz = viz + if got := key(p, base, true) != key(p, base, false); got != (viz == "timeseries" || viz == "stat") { + t.Errorf("%s compare affected key=%v", viz, got) + } + } + p.Viz = "table" + a, b := ColumnFormat{Field: "a", Format: "sparkline"}, ColumnFormat{Field: "b", Format: "sparkline"} + p.Options = &Options{Columns: []ColumnFormat{a, b}} + trends := key(p, base, false) + p.Options.Columns = []ColumnFormat{b, a, b} + if key(p, base, false) != trends { + t.Error("equivalent sparkline sets missed") + } +} + +func TestPanelCacheIntervalFloorsUseEffectiveFilters(t *testing.T) { + e := &Executor{maxWindow: time.Hour} + p := Panel{ID: "rate", Viz: "timeseries", Query: &Spec{From: "spans", Measures: []string{"count()"}, Bucket: "auto"}} + checked := &Checked{ + Measures: map[string][]Measure{p.ID: {{Func: "count"}}}, + Filters: map[string][]Filter{p.ID: {{Columns: []string{"operation"}, Params: []string{"op"}}}}, + } + for _, tc := range []struct { + source string + op Value + want time.Duration + }{ + {"spans", Value{All: true}, time.Minute}, + {"spans", Value{Values: []string{AllValue}}, 30 * time.Second}, + {"metrics", Value{Values: []string{"get"}}, time.Minute}, + } { + p.Query.From = tc.source + vars := map[string]Value{"op": tc.op} + key := func(width int) cacheKey { + t.Helper() + k, err := e.buildPanelCacheKey(&p, checked, Time{Range: "1h"}, fixtureStart, vars, width, false) + if err != nil { + t.Fatal(err) + } + return k + } + if got := resolvePanelInterval(&p, checked, time.Hour, 800, vars); got != tc.want { + t.Errorf("%s op=%+v: interval=%s want %s", tc.source, tc.op, got, tc.want) + } + if shared := key(400) == key(800); shared != (tc.want == time.Minute) { + t.Errorf("%s op=%+v: shared=%v", tc.source, tc.op, shared) + } + } +} + +func TestPanelCacheReferencedVariables(t *testing.T) { + e, _, _ := cachedExecutor(t) + d := shopDashboard() + d.Variables = append(d.Variables, + Variable{Name: "op", Kind: "query", From: "spans", Field: "operation", Where: []string{"attributes['http.route'] = $route"}, IncludeAll: true}, + Variable{Name: "unused", Kind: "text"}) + sql := "SELECT service FROM spans WHERE $__window(start_time) AND (service = $service OR operation = $op OR operation = $op) AND service <> '$unused'" + d.Panels = []Panel{ + {ID: "structured", Title: "Operations", Viz: "table", Query: &Spec{From: "spans", Where: []string{"operation = $op"}, Measures: []string{"count()"}}}, + {ID: "sql", Title: "Services", Viz: "table", SQL: sql}, + } + Normalize(&d) + for range 2 { // The second Check must restore SQL metadata from the panel memo. + checked, problems, err := e.Check(t.Context(), &d) + if err != nil || len(problems) > 0 || !slices.Equal(checked.SQLParams["sql"], []string{"op", "service"}) { + t.Fatalf("checked=%+v problems=%v err=%v", checked, problems, err) + } + for _, p := range d.Panels { + vars := map[string]Value{} + for _, name := range []string{"service", "route", "op", "unused"} { + vars[name] = Value{Values: []string{"one"}} + } + key := func() cacheKey { + t.Helper() + k, err := e.buildPanelCacheKey(&p, checked, d.Time, e.now(), vars, 640, false) + if err != nil { + t.Fatal(err) + } + return k + } + original := key() + for name, old := range vars { + vars[name] = Value{Values: []string{"two"}} + if got := key() != original; got != (name != "unused") { + t.Errorf("%s: changing $%s affected key=%v", p.ID, name, got) + } + vars[name] = old + } + vars["op"] = Value{All: true} + all := key() + vars["op"] = Value{Values: []string{AllValue}} + if all == original || all == key() { + t.Errorf("%s: All collides with a bound string", p.ID) + } + } + } +} + +func TestPanelCacheSQLIdentity(t *testing.T) { + e, _, offset := cachedExecutor(t) + offset.Store(int64(1234*time.Millisecond + time.Nanosecond)) + req := RunRequest{Dashboard: cacheDashboard()} + p := &req.Dashboard.Panels[0] + p.Query = nil + p.SQL = "SELECT $__bucket(start_time) AS t FROM spans WHERE $__window(start_time) ORDER BY 1" + dynamic := runOne(t, e, req) + if dynamic.ToMS != e.now().UnixMilli() || dynamic.FromMS != e.now().Add(-time.Hour).UnixMilli() { + t.Fatalf("bucketed SQL window was rounded: %+v", dynamic) + } + p.SQL = strings.Replace(p.SQL, "SELECT ", "select /* dynamic */ ", 1) + if r := runOne(t, e, req); !r.Cached || r.SQL != dynamic.SQL { + t.Fatalf("canonical bucket macro missed: %+v", r) + } + p.SQL = "SELECT time_bucket(INTERVAL '60 seconds', start_time::TIMESTAMP_NS) AS t FROM spans WHERE $__window(start_time) ORDER BY 1" + fixed := runOne(t, e, req) + if dynamic.Status != StatusOK || fixed.Status != StatusOK || fixed.Cached || dynamic.SQL == fixed.SQL { + t.Fatalf("dynamic=%+v fixed=%+v", dynamic, fixed) + } + p.SQL = strings.Replace(p.SQL, "SELECT ", "select /* edited */ ", 1) + if r := runOne(t, e, req); !r.Cached || r.SQL != fixed.SQL { + t.Fatalf("canonical SQL missed: %+v", r) + } } func TestResultCacheServesExemplars(t *testing.T) { diff --git a/internal/query/service_input.go b/internal/query/service_input.go index 9526afae..518e7fa7 100644 --- a/internal/query/service_input.go +++ b/internal/query/service_input.go @@ -149,7 +149,7 @@ func (e *Executor) EmptyGuidance(ctx context.Context, req RunRequest) (string, s defer cancel() d := req.Dashboard Normalize(&d) - checked, _, invalid, err := e.checkRun(ctx, &d) + checked, invalid, err := e.checkRun(ctx, &d) if err != nil { return "", "", err } diff --git a/internal/query/sqlpanel.go b/internal/query/sqlpanel.go index a0fd8169..f6cff4f6 100644 --- a/internal/query/sqlpanel.go +++ b/internal/query/sqlpanel.go @@ -24,6 +24,14 @@ var ( // Its snapshot covers that window plus the metric lookback before it, so an // explicit lookback predicate of up to ten minutes stays visible. func expandMacros(sql string, interval time.Duration) (string, []string, error) { + seconds := int64(interval / time.Second) + if seconds <= 0 { + seconds = 60 + } + return expandPanelMacros(sql, fmt.Sprintf("INTERVAL '%d seconds'", seconds)) +} + +func expandPanelMacros(sql, bucketStep string) (string, []string, error) { if !windowMacro.MatchString(sql) { return "", nil, errors.New("SQL panels must filter time with $__window(time_column)") } @@ -41,11 +49,7 @@ func expandMacros(sql string, interval time.Duration) (string, []string, error) } return column + " >= $__from::TIMESTAMP_NS::TIMESTAMPTZ_NS AND " + column + " < $__to::TIMESTAMP_NS::TIMESTAMPTZ_NS" }) - seconds := int64(interval / time.Second) - if seconds <= 0 { - seconds = 60 - } - out = bucketMacro.ReplaceAllString(out, fmt.Sprintf(`time_bucket(INTERVAL '%d seconds', $1::TIMESTAMP_NS)`, seconds)) + out = bucketMacro.ReplaceAllString(out, "time_bucket("+bucketStep+", ${1}::TIMESTAMP_NS)") for _, m := range macroToken.FindAllStringSubmatch(stripQuoted(out), -1) { if m[1] != "from" && m[1] != "to" { return "", nil, fmt.Errorf("unknown macro $__%s; use $__window(column) or $__bucket(column)", m[1]) diff --git a/internal/query/variables.go b/internal/query/variables.go index bbf23609..28da0165 100644 --- a/internal/query/variables.go +++ b/internal/query/variables.go @@ -28,7 +28,7 @@ func (e *Executor) ResolveVariables(ctx context.Context, req ResolveRequest) (ma defer cancel() d := req.Dashboard Normalize(&d) - checked, _, _, err := e.checkRun(ctx, &d) + checked, _, err := e.checkRun(ctx, &d) if err != nil { return nil, err } diff --git a/site/src/content/docs/docs/reference/configuration/server.mdx b/site/src/content/docs/docs/reference/configuration/server.mdx index 4d756f09..efb8ff80 100644 --- a/site/src/content/docs/docs/reference/configuration/server.mdx +++ b/site/src/content/docs/docs/reference/configuration/server.mdx @@ -24,7 +24,7 @@ Vendor credentials and endpoints keep the vendor's documented names. | `PITOT_HEALTHCHECK_KEY_FILE` | string | — | | `PITOT_PPROF_ENABLED` | boolean | `false` | | `PITOT_PUBLIC_URL` | string | — | -| `PITOT_QUERY_CACHE_TTL` | duration | `10s` | +| `PITOT_QUERY_CACHE_TTL` | duration | `1m` | | `PITOT_TLS_CERT_FILE` | string | — | | `PITOT_TLS_CLIENT_CA_FILE` | string | — | | `PITOT_TLS_KEY_FILE` | string | — |