query

package
v0.0.0-...-0301fe8 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 33 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package panel defines Pitot's dashboard spec: the typed, validated contract between the agent, the API, storage and the browser renderer. The Go types are the single source of the JSON Schema the MCP tools publish.

Index

Constants

View Source
const (
	StatusOK      = "ok"
	StatusEmpty   = "empty"
	StatusError   = "error"
	StatusInvalid = "invalid"
)
View Source
const AllValue = "$__all"

AllValue selects All for a variable that offers it.

View Source
const BatchDeadlineError = "Not run: other queries kept the server busy. Refresh to try again."

BatchDeadlineError is shared by HTTP and MCP batch callers. It means the panel never started: other queries held the engine until a batch deadline passed, its own request's or, for a request that joined an identical run already waiting, the one that started that run, which may be sooner. A panel that started and ran too long reports TimeoutError.

View Source
const BatchTimeoutError = "Panels took longer than 12 seconds. Narrow the time range or reduce the number of panels."

BatchTimeoutError describes the shared response budget.

View Source
const BusyMessage = "The server is busy with other queries. Try again in a few seconds."

BusyMessage presents ErrBusy to clients.

View Source
const MaxPanels = 40

MaxPanels is the most panels one dashboard may hold.

View Source
const ReadFailure = "Could not read the requested data. Try again."
View Source
const ReasonBusy = "busy"

ReasonBusy marks a result that was not run because of BatchDeadlineError.

View Source
const SQLTimestampGuide = "Compare time columns with TIMESTAMP 'YYYY-MM-DD HH:MM:SS' (UTC), or cast TIMESTAMPTZ literals with ::TIMESTAMPTZ_NS."

SQLTimestampGuide is the time-literal rule shared by diagnostics and MCP guidance.

View Source
const SpecVersion = 1

SpecVersion is the only dashboard spec version Pitot reads.

View Source
const TimeoutError = "The query took longer than 10 seconds. Narrow the time range or add filters."

TimeoutError describes the executor's per-panel time limit.

Variables

View Source
var ErrBusy = errors.New("the server is busy: the read queue is full")

ErrBusy answers a request turned away before it started: every panel of a batch, an exemplar or a trace-detail read refused at the queue bound or left waiting past the batch deadline. HTTP answers it 503 with Retry-After.

View Source
var ErrSchemaBusy = errors.New("schema discovery is busy; try again shortly")

ErrSchemaBusy answers a new window and namespace when the cache holds only in-flight entries, and a caller whose deadline passes while its discovery is still running. Cached keys are always served.

View Source
var ErrSchemaNotCached = errors.New("schema is not cached")

ErrSchemaNotCached answers a Cached request for a key with no schema yet.

Functions

func AutoInterval

func AutoInterval(window time.Duration, widthPx int) time.Duration

AutoInterval picks the finest standard interval, 10 seconds or longer, that keeps a series at one point per four pixels or fewer, so a 24-hour line stays legible instead of becoming a band.

func BucketNames

func BucketNames() []string

BucketNames lists auto followed by the registered intervals in duration order.

func BypassesCache

func BypassesCache(ctx context.Context) bool

BypassesCache reports whether ctx was marked by WithoutCachedResults.

func FieldAliases

func FieldAliases(field string) map[string]string

FieldAliases returns an isolated snapshot of a field's aliases.

func FieldVocabularies

func FieldVocabularies() map[string]FieldVocabulary

FieldVocabularies returns isolated snapshots, shared by all query frontends.

func FilterFunctionNames

func FilterFunctionNames() []string

FilterFunctionNames lists named filter functions, excluding SQL operators.

func LowCardinalityColumns

func LowCardinalityColumns(signal string) []string

LowCardinalityColumns returns columns whose common values the schema lists.

func Normalize

func Normalize(d *Dashboard)

Normalize trims text and fills defaults in place. It never rejects.

func ParseSpan

func ParseSpan(s string) (time.Duration, bool)

ParseSpan reads a span such as 90m, 6h or 2d.

func PresentDiagnosis

func PresentDiagnosis(message string) string

PresentDiagnosis bounds product-authored prose without interpreting observed telemetry values as engine errors or filesystem paths.

func PresentError

func PresentError(err error, kind ErrorKind) string

PresentError logs the complete cause and publishes only the chosen audience's message. It never changes cancellation identity at the calling boundary.

func PresentMessage

func PresentMessage(message string) string

PresentMessage presents engine and operational error text. Engine source excerpts are expanded server SQL. Keep only the first line and candidate names.

func PresentedError

func PresentedError(err error, kind ErrorKind) error

PresentedError preserves the cause for errors.Is/As while publishing a message.

func SQLRelations

func SQLRelations() map[string]SQLRelationSchema

SQLRelations is the shared catalog for discovery and generated documentation.

func Shape

func Shape(q *Spec, viz string, vars map[string]Variable, prepared ...[]Measure) (Problems, []VizRequirement)

Shape checks query-only structure without normalizing or using an engine. A nil vars map omits declaration checks. All problem paths are query-relative.

func SignalNames

func SignalNames() []string

SignalNames lists the queryable signals in display order.

func WithoutCachedResults

func WithoutCachedResults(ctx context.Context) context.Context

WithoutCachedResults marks ctx as a request that must not be answered from a stored result, as Cache-Control: no-cache asks. It may still join a run that started after it arrived, and its result is stored for others.

Types

type AnnotationFilter

type AnnotationFilter struct {
	Filter          Filter
	NamespaceScoped bool
}

type AnnotationMatch

type AnnotationMatch struct {
	Services        []AnnotationService `json:"services"`
	NamespaceScoped bool                `json:"namespace_scoped,omitempty"`
	Limited         bool                `json:"limited,omitempty"`
}

type AnnotationService

type AnnotationService struct {
	Namespace string `json:"namespace"`
	Service   string `json:"service"`
}

type Annotations

type Annotations struct {
	Deploys   *bool `json:"deploys,omitempty" jsonschema:"Draw deploys; default true"`
	Anomalies *bool `json:"anomalies,omitempty" jsonschema:"Draw detector anomalies; default true"`
}

type AttributeSchema

type AttributeSchema struct {
	Key      string   `json:"key"`
	Scope    string   `json:"scope"`
	Type     string   `json:"type"`
	Count    int64    `json:"count"`
	Services string   `json:"services,omitempty"`
	Values   []Option `json:"values,omitempty"`
	// Types lists every scalar type seen when rows disagree, e.g. a status
	// code stored as a number by one service and as text by another.
	Types []string `json:"types,omitempty"`
	// Numbers lists the sampled values some rows store as numbers, with
	// those rows' counts, when rows disagree on the type.
	Numbers []Option `json:"numbers,omitempty"`
	// Indexed marks a standard key stored in a typed column (batch format
	// 6): it reads as Type whatever type rows sent.
	Indexed bool `json:"indexed,omitempty"`
}

type Checked

type Checked struct {
	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
}

Checked is what the database-backed checks produced.

type Click

type Click struct {
	SetVariable string `json:"set_variable" jsonschema:"Variable set to the clicked value"`
}

type Column

type Column struct {
	Name string `json:"name"`
	Type string `json:"type"`
	Role string `json:"role"`
	Unit string `json:"unit,omitempty"`
}

Column describes one frame column.

type ColumnFormat

type ColumnFormat struct {
	Field    string `json:"field"`
	Format   string `json:"format" jsonschema:"unit, bar, status, sparkline, trace_link, service_link or log_template"`
	Unit     string `json:"unit,omitempty"`
	Variable string `json:"variable,omitempty" jsonschema:"service_link: query or custom variable to select"`
}

type ColumnSchema

type ColumnSchema struct {
	Field
	Values []Option `json:"values,omitempty"`
}

type Compiled

type Compiled struct {
	HasTotals bool

	SQL           string
	Args          []any
	Columns       []Column
	TrendInterval time.Duration
	TrendStart    time.Time
	// contains filtered or unexported fields
}

Compiled is one statement ready to run.

type Dashboard

type Dashboard struct {
	Version     int          `json:"version,omitempty" jsonschema:"Spec version; omit or 1"`
	Name        string       `json:"name" jsonschema:"Short unique dashboard name, at most 80 characters"`
	Description string       `json:"description,omitempty" jsonschema:"What the dashboard is for, at most 280 characters"`
	Time        Time         `json:"time,omitzero" jsonschema:"Default time range, refresh and comparison"`
	Variables   []Variable   `json:"variables,omitempty" jsonschema:"Variables referenced as $name in filters, titles and SQL"`
	Annotations *Annotations `json:"annotations,omitempty" jsonschema:"Deploy and anomaly markers on time panels"`
	Panels      []Panel      `json:"panels" jsonschema:"Panels in display order"`
}

type Engine

type Engine interface {
	Parser
	QueryContext(ctx context.Context, query string, args ...any) (queryrows.Rows, error)
}

Engine is the query engine the executor runs on. *engine.Duck implements it; QueryContext binds the Parquet snapshot for the window in the context.

type ErrorKind

type ErrorKind bool

ErrorKind selects the publication boundary, independently of the cause's text. Authored queries receive diagnostics; operational causes stay in logs.

const (
	ReadError ErrorKind = false
	SQLError  ErrorKind = true
)

type Executor

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

func NewExecutor

func NewExecutor(engine Engine, retentionDays int) *Executor

func (*Executor) AdmitReader

func (e *Executor) AdmitReader(inner queryrows.Queryer) queryrows.Queryer

AdmitReader wraps a read surface so every read it issues passes through the interactive admission lane. The observability readers, annotations, and variable-option queries otherwise call the engine directly and compete for the read pool without being admitted, so a saturating dashboard oversubscribes the pool, starves admitted panels, and defeats the deadline shedding the pool size is meant to enforce. Routing those reads through admission restores the invariant that no more reads run concurrently than the pool can serve, and turns excess load into a bounded ErrBusy shed rather than unbounded queueing inside the engine.

The admission slot is held for the lifetime of the returned rows and released when they close, mirroring how the engine holds a pool connection until its rows close. Callers already close every result set before issuing the next read, so one interactive slot is never held across acquiring another.

func (*Executor) AdmitTraceDetail

func (e *Executor) AdmitTraceDetail(inner TraceDetailReader) TraceDetailReader

AdmitTraceDetail admits each indexed trace read as one interactive read. The trace's logs were a DuckDB query admitted through AdmitReader; they are now read from logs.fidx beside the spans, and the pair keeps the slot, deadline and shedding that query had. Trace detail reached through CachedTraces is already admitted and uses the raw engine.

func (*Executor) CachedTraces

func (e *Executor) CachedTraces(reader TraceReader) TraceReader

CachedTraces answers trace-detail reads through the executor's result cache, keyed by the trace, its scope and the span limit.

func (*Executor) Check

func (e *Executor) Check(ctx context.Context, d *Dashboard) (*Checked, Problems, error)

Check runs Validate's database-backed checks: every filter expression and every SQL panel, through DuckDB's parser. It reports all problems it finds; an operational failure (cancelled request, expired deadline, closed database) is the error, never a Problem. The dashboard must already be normalized. Results are remembered per panel, so an edit re-checks only what changed.

func (*Executor) Close

func (e *Executor) Close()

Close cancels the schema discoveries still running and waits for them to release their read connections.

func (*Executor) EmptyGuidance

func (e *Executor) EmptyGuidance(ctx context.Context, req RunRequest) (string, string, error)

EmptyGuidance is used only after a complete fragment returned no matching data. Reuse checked filters and resolved variables to find exact service scopes.

func (*Executor) Exemplars

func (e *Executor) Exemplars(ctx context.Context, req ExemplarRequest) (ExemplarResponse, error)

Exemplars answers a selection's sample traces or logs through the result cache, keyed by the canonical request, so a burst of identical drill-downs runs once. Relative windows end now, the stamp of a cached answer.

func (*Executor) InteractiveRefusals

func (e *Executor) InteractiveRefusals() uint64

InteractiveRefusals counts interactive requests refused before execution.

func (*Executor) Pressure

func (e *Executor) Pressure() bool

Pressure reports queued reads or a fully occupied admission pool.

func (*Executor) ResolveVariables

func (e *Executor) ResolveVariables(ctx context.Context, req ResolveRequest) (map[string][]Option, error)

ResolveVariables lists the options of every query, custom and constant variable, resolving them in order so a variable that filters on an earlier one sees that variable's current value.

func (*Executor) ResolveWindow

func (e *Executor) ResolveWindow(start, end time.Time) (time.Time, time.Time, error)

ResolveWindow applies the executor's time bounds before callers validate or execute a tool, so guidance and all subsequent queries use the same interval.

func (*Executor) Run

func (e *Executor) Run(ctx context.Context, req RunRequest) ([]Result, error)

Run validates the dashboard and runs the requested panels concurrently. Dashboard-level faults return Problems; invalid or failed panels report their failures in their own results, so one broken panel cannot blank a dashboard. Results are in panel order and share one response budget.

func (*Executor) Schema

func (e *Executor) Schema(ctx context.Context, req SchemaRequest) (*Schema, error)

Schema describes what telemetry exists: columns with their common values, attribute keys and values sampled from recent rows, metric names and services. It is the agent's map before it drafts panels. An entry is fresh for a minute and then served stale while one background refresh runs. Concurrent callers of a new key share one discovery, which runs on after they leave, until the executor closes, so the next request finds it cached. Discoveries are bounded: two run at a time, each waits at most discoverWait for a slot and runs at most discoverRun, windows are the fixed set and a namespace must have data in the last 24h. A Cached request is answered at once.

func (*Executor) ServiceGuidance

func (e *Executor) ServiceGuidance(ctx context.Context, start, end time.Time, namespace, service string) (string, error)

ServiceGuidance returns an empty message for an exact observed service name. Retained names remain valid even when the requested window has no traffic. Rollups are the common, cheap path; inventory covers publication/rollup lag and services that emit only logs or metrics. Neither uses a capped name list.

func (*Executor) SetCacheTTL

func (e *Executor) SetCacheTTL(d time.Duration)

SetCacheTTL sets the oldest answer the result cache may serve; zero disables storing results. Call it before serving requests.

func (*Executor) SetRollupReader

func (e *Executor) SetRollupReader(reader RollupReader)

func (*Executor) Stream

func (e *Executor) Stream(ctx context.Context, req RunRequest, emit func(Result)) error

Stream is Run with each result handed to emit as soon as its panel finishes, so a slow panel does not hold back the others. emit is never called concurrently, and only after the spec has checked out, so a caller can still answer Problems as a whole. Each result has its own response budget: the panel-order budget Run shares would need every result first.

func (*Executor) Validate

func (e *Executor) Validate(ctx context.Context, d *Dashboard) error

Validate normalizes d and runs every check, returning Problems or nil.

type Exemplar

type Exemplar struct {
	TraceID    string    `json:"trace_id"`
	Namespace  string    `json:"namespace"`
	Service    string    `json:"service"`
	Operation  string    `json:"operation"`
	DurationMS float64   `json:"duration_ms"`
	Status     string    `json:"status"`
	Start      time.Time `json:"start"`
}

type ExemplarRequest

type ExemplarRequest struct {
	Dashboard  Dashboard         `json:"dashboard" jsonschema:"Complete v1 dashboard specification; every panel is executed"`
	PanelID    string            `json:"panel_id" jsonschema:"ID of the selected panel in dashboard"`
	Kind       string            `json:"kind,omitempty" jsonschema:"Selection signal: traces or logs; defaults from the selected panel"`
	Time       *Time             `json:"time,omitempty" jsonschema:"Optional dashboard time override: exact from/to or a relative range"`
	From       time.Time         `json:"from" jsonschema:"Selection start as an RFC3339Nano UTC timestamp"`
	To         time.Time         `json:"to" jsonschema:"Selection end as an RFC3339Nano UTC timestamp, after from"`
	Dimensions map[string]string `json:"dimensions,omitempty" jsonschema:"Exact dimension values of the selected series or row"`
	Bucket     *SelectionBucket  `json:"bucket,omitempty" jsonschema:"Optional selected bucket with its exact bounds"`
	Vars       map[string]Value  `json:"vars,omitempty" jsonschema:"Resolved variable values: strings or lists; preserves $__all and empty lists"`
}

type ExemplarResponse

type ExemplarResponse struct {
	Logs      *Frame     `json:"logs,omitempty"`
	Traces    []Exemplar `json:"traces"`
	Truncated bool       `json:"truncated,omitempty"`
}

type Field

type Field struct {
	Name        string    `json:"name"`
	Type        FieldType `json:"type"`
	Unit        string    `json:"unit,omitempty"`
	Description string    `json:"description,omitempty"`
}

func SignalColumns

func SignalColumns(signal string) ([]Field, bool)

SignalColumns returns a copy of every catalog column in display order.

type FieldRef

type FieldRef struct {
	Text   string
	Column string
	Key    string
	Type   FieldType
	Unit   string
}

FieldRef is a validated reference to a column or an attribute lookup.

type FieldType

type FieldType string
const (
	TypeString FieldType = "string"
	TypeNumber FieldType = "number"
	TypeTime   FieldType = "time"
	TypeMap    FieldType = "map"
	TypeBool   FieldType = "bool"
)

type FieldVocabulary

type FieldVocabulary struct {
	Signal  string
	Order   []string
	Aliases map[string]string
}

FieldVocabulary is the closed value vocabulary for a catalog field.

type Filter

type Filter struct {
	ScopeEquality   *SQLExpr `json:"-"` // Original checked tree, before parameter casts.
	RoutePopulation bool     `json:"-"` // Checked nonempty http.route population, safe for bounded endpoint summaries.
	Columns         []string `json:"-"` // Checked column dependencies, including attribute roots.
	// Expr is DuckDB's canonical rendering of the checked expression; it is
	// the only text ever embedded in SQL.
	Expr string `json:"expr"`
	// Source is the author's text, kept for messages.
	Source   string          `json:"source"`
	Params   []string        `json:"params,omitempty"`
	InParams map[string]bool `json:"-"`
	// PatternParams are variables used as patterns; their values are bounded
	// when bound.
	PatternParams map[string]bool `json:"-"`
	// EqField is the field compared when the filter is `field = value`; the
	// empty-panel diagnosis lists values seen for it.
	EqField        string `json:"-"`
	EqLiteral      string `json:"-"`
	EqParam        string `json:"-"`
	EqValue        bool   `json:"-"`
	DisplayField   string `json:"-"`
	DisplayLiteral string `json:"-"`
	DisplayParam   string `json:"-"`
	NameInAnd      bool   `json:"-"`
	// Negated is a whole entry that is one negated term as PitotQL lowers it
	// (proposal 0004, section 0.7); on the traces viz it excludes traces.
	Negated bool `json:"-"`
}

Filter is one checked filter expression.

type FixIt

type FixIt struct {
	Label string   `json:"label"`
	Span  TextSpan `json:"span"`
	Text  string   `json:"text"`
}

FixIt is an alternative text replacement the author may choose to apply.

type Frame

type Frame struct {
	Periods   map[string]Time    `json:"periods,omitempty"`
	Trends    map[string][][]any `json:"trends,omitempty"`
	Note      string             `json:"note,omitempty"`
	Health    *HealthFrame       `json:"health,omitempty"`
	Columns   []Column           `json:"columns"`
	Values    [][]any            `json:"values"`
	Rows      int                `json:"rows"`
	Totals    []any              `json:"totals,omitempty"`
	Truncated bool               `json:"truncated,omitempty"`
	Trend     *Trend             `json:"trend,omitempty"`
	// contains filtered or unexported fields
}

Frame is a columnar query result: one array of values per column.

type Grid

type Grid struct {
	X int `json:"x"`
	Y int `json:"y"`
	W int `json:"w"`
	H int `json:"h"`
}

type HealthFrame

type HealthFrame struct {
	Health          string                     `json:"health"`
	Counts          observability.HealthCounts `json:"counts"`
	TotalSpans      int64                      `json:"total_spans"`
	ErrorRate       float64                    `json:"error_rate"`
	ServiceCount    int                        `json:"service_count"`
	ErrorTrendTimes []int64                    `json:"error_trend_times"`
	ErrorTrend      []float64                  `json:"error_trend"`
}

type Histogram

type Histogram struct {
	Field   string `` /* 212-byte string literal not displayed */
	Buckets string `json:"buckets,omitempty"`
}

type Measure

type Measure struct {
	Text     string
	Func     string
	Field    *FieldRef
	Q        float64
	Alias    string
	Unit     string
	Additive bool
	Expr     MeasureExpr
	Leaves   int
	Rank     RankRule
	// contains filtered or unexported fields
}

Measure is one parsed aggregate.

func MeasureFromExpr

func MeasureFromExpr(signal string, e MeasureExpr, alias string, specs []MeasureSpec) (Measure, string, string)

MeasureFromExpr validates an already parsed frontend expression. The structured parser and text frontends share this AST and its budgets and metadata.

func ParseMeasure

func ParseMeasure(signal, text string) (Measure, error)

ParseMeasure parses one stored aggregate measure for the named signal.

func (Measure) IsExpression

func (m Measure) IsExpression() bool

type MeasureBinary

type MeasureBinary struct {
	Op   byte
	L, R MeasureExpr
}

type MeasureCall

type MeasureCall struct {
	Func  string
	Field *FieldRef
	Q     float64
}

type MeasureConst

type MeasureConst struct {
	Value float64
	Text  string
}

type MeasureCountIf

type MeasureCountIf struct {
	Filter string
	Expr   string
}

type MeasureExpr

type MeasureExpr interface {
	// contains filtered or unexported methods
}

MeasureExpr is a bounded aggregate expression. Only checked CountIf.Expr is compiled; its source is retained for diagnostics and direction inference.

func ReadMeasureExpression

func ReadMeasureExpression(g MeasureGrammar, minPrecedence, depth int) (MeasureExpr, int)

ReadMeasureExpression is the single precedence and grouping grammar used by structured measures and PitotQL. The result is panel's aggregate AST directly.

type MeasureGrammar

type MeasureGrammar struct {
	Peek     func() string
	Take     func()
	Position func() int
	CanAtom  func() bool
	Atom     func() MeasureExpr
	Node     func(MeasureExpr, int, ...MeasureExpr) MeasureExpr
	Group    func(MeasureExpr, int)
	Enter    func(int)
	Leave    func()
	Depth    func(int) bool
	OK       func() bool
	Fail     func(MeasureSyntaxCode, string, int)
}

MeasureGrammar adapts tokens, terminals and source locations to the shared arithmetic grammar. Each frontend owns its field and predicate syntax only.

type MeasureNeg

type MeasureNeg struct{ X MeasureExpr }

type MeasureSpec

type MeasureSpec struct {
	Name     string
	Args     int
	Numeric  bool
	Additive bool
	Unit     string
	Signals  []string
	Quantile float64
}

MeasureSpec describes a registered aggregate without exposing mutable tables.

func MeasureSpecs

func MeasureSpecs() []MeasureSpec

MeasureSpecs lists registered measures, sorted by name.

type MeasureSyntaxCode

type MeasureSyntaxCode uint8

MeasureSyntaxCode identifies syntax failures independently of frontend copy.

const (
	MeasureMissingAtom MeasureSyntaxCode = iota
	MeasureMissingOperand
	MeasureMissingClose
)

type MetricSchema

type MetricSchema struct {
	Name        string `json:"name"`
	Unit        string `json:"unit,omitempty"`
	Type        string `json:"type"`
	Temporality string `json:"temporality,omitempty"`
	Count       int64  `json:"count"`
}

type Option

type Option struct {
	Value string `json:"value"`
	Count int64  `json:"count,omitempty"`
}

type Options

type Options struct {
	Split   string         `json:"split,omitempty" jsonschema:"bar: deploy, comparing before and since the latest deploy"`
	Columns []ColumnFormat `json:"columns,omitempty" jsonschema:"table column formats"`

	Highlight string `json:"highlight,omitempty" jsonschema:"logs and log_patterns: literal redacted-body search, at most 200 characters"`
	Style     string `json:"style,omitempty" jsonschema:"timeseries: line, area, bars or stacked (additive measures only)"`
	Scale     string `json:"scale,omitempty" jsonschema:"linear or log"`
	Top       int    `` /* 365-byte string literal not displayed */
	Legend    string `json:"legend,omitempty" jsonschema:"auto or hidden"`
	XScale    string `json:"x_scale,omitempty" jsonschema:"scatter x axis: linear or log"`
	YScale    string `json:"y_scale,omitempty" jsonschema:"scatter y axis: linear or log"`
}

type Panel

type Panel struct {
	ID          string        `json:"id" jsonschema:"Stable identifier: lowercase letters, digits and underscores; edits address panels by id"`
	Title       string        `json:"title" jsonschema:"Panel title, at most 80 characters; may reference $variables"`
	Description string        `json:"description,omitempty" jsonschema:"Help text, at most 280 characters"`
	Viz         string        `` /* 279-byte string literal not displayed */
	Width       int           `json:"width,omitempty" jsonschema:"Grid columns from 1 to 12; default depends on viz"`
	Height      string        `json:"height,omitempty" jsonschema:"s, m or l; default depends on viz"`
	Query       *Spec         `json:"query,omitempty" jsonschema:"Structured query; exactly one of query or sql, except text panels"`
	SQL         string        `` /* 262-byte string literal not displayed */
	Unit        string        `` /* 129-byte string literal not displayed */
	XUnit       string        `json:"x_unit,omitempty" jsonschema:"scatter x axis unit; unit describes y"`
	Reduce      string        `json:"reduce,omitempty" jsonschema:"stat and gauge: window (default), last, mean, min, max or sum"`
	Thresholds  []Threshold   `json:"thresholds,omitempty" jsonschema:"Up to 4 status boundaries"`
	Better      string        `json:"better,omitempty" jsonschema:"lower or higher; inferred for known measures"`
	Min         *float64      `json:"min,omitempty" jsonschema:"gauge: scale minimum"`
	Max         *float64      `json:"max,omitempty" jsonschema:"gauge: scale maximum"`
	Options     *Options      `json:"options,omitempty"`
	Click       *Click        `json:"click,omitempty" jsonschema:"Clicking a bar, row or series sets a variable"`
	Drill       string        `json:"drill,omitempty" jsonschema:"traces or logs: what a click on a point opens"`
	Time        *TimeOverride `json:"time,omitempty" jsonschema:"Override the dashboard time for this panel"`
	Content     string        `json:"content,omitempty" jsonschema:"text panels: Markdown, at most 4000 characters"`
	Grid        *Grid         `json:"grid,omitempty" jsonschema:"Position set by the server or by dragging; omit when authoring"`
}

func (*Panel) Top

func (p *Panel) Top() int

Top limits categorical series or independently coloured item rows.

type Parser

type Parser interface {
	ParseSQL(ctx context.Context, query string) (map[string]any, error)
	RenderSQL(ctx context.Context, node map[string]any) (string, error)
	PrepareTelemetrySQL(ctx context.Context, query, describe string, maxRows int) (string, []bool, error)
}

Parser is the slice of the query engine that checks SQL text. *engine.Duck implements it.

type Problem

type Problem struct {
	Path    string    `json:"path"`
	Message string    `json:"message"`
	Hint    string    `json:"hint,omitempty"`
	Span    *TextSpan `json:"span,omitempty"`
	FixIts  []FixIt   `json:"fix_its,omitempty"`
	// contains filtered or unexported fields
}

Problem is one reason a spec cannot be saved or run, addressed by a JSON path so the author can fix exactly that field.

func DiagnosisProblem

func DiagnosisProblem(path, message, hint string) Problem

DiagnosisProblem marks product-authored guidance so subsequent error adapters never reinterpret it as engine or filesystem failures.

type Problems

type Problems []Problem

Problems is a validation result; empty means valid. It is an error so a caller can return it unchanged and an adapter can unwrap it with errors.As.

func Diagnoses

func Diagnoses(problems Problems) Problems

Diagnoses presents PitotQL problems, which quote the user's own text (often URL paths), as product-authored guidance rather than engine errors.

func PresentProblems

func PresentProblems(problems Problems) Problems

PresentProblems copies diagnostics so HTTP, previews, receipts and MCP share the same wording without mutating a cached validation result.

func Validate

func Validate(d *Dashboard) Problems

Validate checks everything that does not need the database. Filter expressions and SQL text are checked by Check.

func (Problems) Error

func (p Problems) Error() string

type RankRule

type RankRule struct {
	Rule, Better  string
	Floor         int
	SupportColumn string
}

type Ranking

type Ranking struct {
	Rule          string   `json:"rule"`
	Better        string   `json:"better"`
	Floor         int      `json:"floor"`
	SupportColumn string   `json:"support_column"`
	BelowFloor    int      `json:"below_floor"`
	TieBreakers   []string `json:"tie_breakers"`
}

type ResolveRequest

type ResolveRequest struct {
	Dashboard Dashboard        `json:"dashboard" jsonschema:"Complete v1 dashboard specification; every panel is executed"`
	Time      *Time            `json:"time,omitempty" jsonschema:"Optional dashboard time override: exact from/to or a relative range"`
	Vars      map[string]Value `json:"vars,omitempty" jsonschema:"Resolved variable values: strings or lists; preserves $__all and empty lists"`
}

type Result

type Result struct {
	Problems        Problems         `json:"problems,omitempty"`
	Ranking         *Ranking         `json:"ranking,omitempty"`
	AnnotationScope *AnnotationMatch `json:"annotation_scope,omitempty"`
	AnnotationError string           `json:"annotation_error,omitempty"`
	ID              string           `json:"id"`
	Status          string           `json:"status"`
	Frame           *Frame           `json:"frame,omitempty"`
	Previous        *Frame           `json:"previous,omitempty"`
	Error           string           `json:"error,omitempty"`
	// Reason classifies an error for clients that word it themselves:
	// "busy" means the panel never started (see BatchDeadlineError).
	Reason    string `json:"reason,omitempty"`
	Retryable bool   `json:"retryable,omitempty"`
	Diagnosis string `json:"diagnosis,omitempty"`
	SQL       string `json:"sql,omitempty"`
	Interval  string `json:"interval,omitempty"`
	ElapsedMS int64  `json:"elapsed_ms"`
	FromMS    int64  `json:"from_ms"`
	ToMS      int64  `json:"to_ms"`
	FreshToMS int64  `json:"fresh_to_ms,omitempty"`
	Better    string `json:"better,omitempty"`
	// ShiftMS is how far Previous sits behind Frame, so a client can overlay it
	// without guessing from the first populated bucket.
	ShiftMS int64 `json:"shift_ms,omitempty"`
	// Cached marks a result served from the result cache rather than run for
	// this request; see PITOT_QUERY_CACHE_TTL.
	Cached bool `json:"cached,omitempty"`
	// contains filtered or unexported fields
}

type RunRequest

type RunRequest struct {
	Dashboard Dashboard        `json:"dashboard"`
	Panels    []string         `json:"panels,omitempty"`
	Time      *Time            `json:"time,omitempty"`
	Vars      map[string]Value `json:"vars,omitempty"`
	Widths    map[string]int   `json:"widths,omitempty"`
	Compare   *bool            `json:"compare,omitempty"`
}

type SQLColumnSchema

type SQLColumnSchema struct {
	Field
	SQLType string `json:"sql_type"`
}

type SQLExpr

type SQLExpr struct {
	Class, Type                             string
	Children                                []*SQLExpr
	Left, Right, Child, Input, Lower, Upper *SQLExpr
	Columns                                 []string
	Function                                string
	Arguments                               []*SQLExpr
	CastType                                string
	TryCast                                 bool
	LiteralKind, LiteralText                string
	Identifier                              string
	Negated, Distinct, HasOrder, HasFilter  bool
	Grouped                                 bool // explicit parentheses in a byte-checked local lowering
}

SQLExpr is the shared typed view of an engine expression. Unrecognized classes remain visible so consumers can reject them or preserve the original SQL. Engine rendering still receives the original, lossless statement tree.

func SQLExpression

func SQLExpression(raw any) *SQLExpr

SQLExpression builds a typed expression view for validation and inspection. Statement checks and lossless tree rewrites still use the engine JSON maps; unknown fields remain in that original tree for rendering.

type SQLRelationSchema

type SQLRelationSchema struct {
	Description string            `json:"description"`
	Columns     []SQLColumnSchema `json:"columns"`
}

SQLRelationSchema describes a panel-SQL-only relation. Its rows are not raw events, so it deliberately has neither a signal time column nor sample counts.

type Schema

type Schema struct {
	SQLRelations map[string]SQLRelationSchema `json:"sql_relations"`
	Window       string                       `json:"window"`
	Signals      map[string]SignalSchema      `json:"signals"`
	Services     []Option                     `json:"services"`
	Measures     []string                     `json:"measures"`
	Buckets      []string                     `json:"buckets"`
	Units        []string                     `json:"units"`
}

type SchemaRequest

type SchemaRequest struct {
	Window    string
	Namespace string
	// Cached answers only from the cache, never waiting for a discovery.
	Cached bool
}

type Scope

type Scope struct {
	Start, End   time.Time
	FreshTo      time.Time // Ingest horizon for minute rollups.
	RollupSource string
	Rollup       bool
	NoTop        bool          // Table trends select displayed tuples after aggregation.
	Interval     time.Duration // bucket width; zero means no time grouping
	Vars         map[string]Value
}

Scope is everything a compiled query depends on besides the spec.

type SelectionBucket

type SelectionBucket struct {
	Lower float64  `json:"lower"`
	Upper *float64 `json:"upper,omitempty"`
}

type SignalSchema

type SignalSchema struct {
	TimeColumn string            `json:"time_column"`
	Columns    []ColumnSchema    `json:"columns"`
	Attributes []AttributeSchema `json:"attributes"`
	Metrics    []MetricSchema    `json:"metrics,omitempty"`
}

type Spec

type Spec struct {
	From      string     `json:"from" jsonschema:"spans, logs or metrics"`
	Where     []string   `` /* 131-byte string literal not displayed */
	Measures  []string   `` /* 623-byte string literal not displayed */
	By        []string   `json:"by,omitempty" jsonschema:"Up to 3 grouping fields: columns or attributes['key']"`
	Bucket    string     `json:"bucket,omitempty" jsonschema:"auto or 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h, 1d; required for timeseries"`
	Histogram *Histogram `json:"histogram,omitempty" jsonschema:"heatmap and histogram panels (milestone 2)"`
	Sort      string     `` /* 154-byte string literal not displayed */
	Limit     int        `` /* 179-byte string literal not displayed */
}

type TextSpan

type TextSpan struct {
	Start int `json:"start"`
	End   int `json:"end"`
}

TextSpan uses code-point offsets, with an exclusive end.

type Threshold

type Threshold struct {
	Value  float64 `json:"value"`
	Status string  `json:"status" jsonschema:"ok, warn or bad"`
	Label  string  `json:"label,omitempty"`
}

type Time

type Time struct {
	Range   string     `json:"range,omitempty" jsonschema:"Relative range: 5m, 15m, 1h, 3h, 6h, 12h, 24h, 2d, 7d or 30d"`
	From    *time.Time `json:"from,omitempty" jsonschema:"Absolute start (RFC 3339); use with to instead of range"`
	To      *time.Time `json:"to,omitempty" jsonschema:"Absolute end (RFC 3339)"`
	Refresh string     `json:"refresh,omitempty" jsonschema:"off, 10s, 30s, 1m or 5m; default 30s"`
	Compare string     `json:"compare,omitempty" jsonschema:"previous_period to compare with the preceding range"`
}

type TimeOverride

type TimeOverride struct {
	Range string `json:"range,omitempty" jsonschema:"Replace the dashboard range, e.g. 30d"`
	Shift string `json:"shift,omitempty" jsonschema:"Move the dashboard range back, e.g. 1d"`
}

type TraceDetailReader

type TraceDetailReader interface {
	TraceDetail(context.Context, telemetry.TraceQuery) (telemetry.TraceDetail, error)
}

TraceDetailReader reads a trace's spans and logs from the batch indexes, as the engine does.

type TraceReader

type TraceReader interface {
	Trace(ctx context.Context, scope observability.Scope, traceID, service string, limit int) (observability.Result[observability.TraceDetail], error)
}

TraceReader reads one trace's detail, as observability.Service does.

type Trend

type Trend struct {
	StartMS int64 `json:"start_ms"`
	StepMS  int64 `json:"step_ms"`
}

Trend locates each point in a row panel's dense trend array.

type Value

type Value struct {
	All    bool
	Values []string
}

Value is a variable's current value. JSON: a string, a list of strings, or "$__all".

func (Value) MarshalJSON

func (v Value) MarshalJSON() ([]byte, error)

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(data []byte) error

type Variable

type Variable struct {
	Name       string   `json:"name" jsonschema:"Identifier referenced as $name: lowercase letters, digits, underscores"`
	Kind       string   `json:"kind" jsonschema:"query, custom, constant or text"`
	From       string   `json:"from,omitempty" jsonschema:"query variables: spans, logs or metrics"`
	Field      string   `json:"field,omitempty" jsonschema:"query variables: a column or attributes['key'] whose distinct values are the options"`
	Where      []string `json:"where,omitempty" jsonschema:"query variables: filter expressions; may reference earlier variables"`
	Options    []string `json:"options,omitempty" jsonschema:"custom variables: the fixed options"`
	Value      string   `json:"value,omitempty" jsonschema:"constant variables: the value"`
	Default    string   `json:"default,omitempty" jsonschema:"Initial value; $__all selects All when include_all is true"`
	Multi      bool     `json:"multi,omitempty" jsonschema:"Allow several values; use as IN $name"`
	IncludeAll bool     `json:"include_all,omitempty" jsonschema:"Offer All, which removes filters that reference this variable"`
}

type VizCompat

type VizCompat struct {
	Viz      string           `json:"viz"`
	Requires []VizRequirement `json:"requires"`
}

VizCompat identifies a visualization accepting the query as written.

func CompatibleVizzes

func CompatibleVizzes(q *Spec, vars map[string]Variable, prepared ...[]Measure) []VizCompat

CompatibleVizzes lists the query visualizations accepting the query unchanged.

type VizRequirement

type VizRequirement string

VizRequirement identifies panel configuration required beyond the query.

const (
	RequiresMinMax     VizRequirement = "min_max"
	RequiresThresholds VizRequirement = "thresholds"
)

Jump to

Keyboard shortcuts

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