query

package
v0.5.0 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: 38 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 query reads a collection of stored messages by refs, as a table: the columns a query selects, its rows filtered and sorted. A ref names a field by its path in the message (usage.cost_usd) and may cross to another collection through a field that holds an id (wish_id->title), as its (djinn.v1.ref) option declares. The schema comes from the descriptor: a column's type never depends on the values a row holds. A collection adds refs computed in Go (prompt::size), and a query may aggregate its rows: groups by refs, a time truncated to its day, week or month, and measures named ref::fn (running::median).

The store keeps each entity as a protobuf payload, its *_id fields aside as columns: an equality on one of them narrows the rows SQLite reads, and everything else runs in Go, on the decoded messages.

A table writes itself in Arrow, typed, for the window, or as aligned text and CSV, for the command line; Handler serves Djinn's collections as QueryService, its filters, sorts, groups and measures read from their texts.

Index

Constants

View Source
const MetaKey = "djinn"

MetaKey is the key of a field's metadata in Arrow.

Variables

View Source
var ErrInvalid = errors.New("invalid query")

ErrInvalid wraps the errors of a query that cannot run as written: an unknown or hidden ref, a value of the wrong type, an empty group.

View Source
var QuestionRefs = []Derived{
	Derive("context::size", TypeInt, "The context's size in tokens, estimated as its characters divided by 4, "+
		"rounded up: the context itself stays hidden.",
		func(q *planv1.Question) any { return size(q.GetContext()) }).WithUnit(tokens),
	Derive("answer.note::size", TypeInt, "The answer's note size in tokens, estimated as its characters divided by 4, "+
		"rounded up.", func(q *planv1.Question) any { return size(q.GetAnswer().GetNote()) }).WithUnit(tokens),
	Derive("answer::delay", TypeDuration, "How long the question waited for its answer (answer.create_time - "+
		"create_time), whoever answered.", func(q *planv1.Question) any {
		return between(q.GetCreateTime(), q.GetAnswer().GetCreateTime())
	}),
}

QuestionRefs are the derived refs of the questions.

View Source
var TaskRefs = []Derived{
	Derive("prompt::size", TypeInt, "The size in tokens of the task's first prompt, the text it was given, estimated "+
		"as its characters divided by 4, rounded up: the prompt itself stays hidden.",
		func(t *planv1.Task) any { return tokensOf(t.GetPromptLength()) }).WithUnit(tokens),
	Derive("integration::delay", TypeDuration, "From the task's end to its work's commit into its wish's integration "+
		"branch (integration.update_time - end_time), for a work committed only.", func(t *planv1.Task) any {
		if t.GetIntegration().GetState() != planv1.IntegrationState_INTEGRATION_STATE_COMMITTED {
			return nil
		}
		return between(t.GetEndTime(), t.GetIntegration().GetUpdateTime())
	}),
	DeriveEnum("type", "What the task is, for every task, as plan.Kind reads it: its kind, work when it holds none.",
		plan.Kind),
}

TaskRefs are the derived refs of the tasks.

Functions

func Handler

func Handler(r store.Reader) (string, http.Handler, error)

Handler serves QueryService on the store r. Every method only reads: a worker calls them as the developer does.

func Label

func Label(col Column) string

Label is a short name of col for a person, in English, from its ref: Wish title for wish_id->title, Running (median) for running::median.

Types

type Aggregation

type Aggregation struct {
	By       []GroupBy
	Measures []Measure
	// Location is where a day, a week or a month starts: the machine's local time when nil.
	Location *time.Location
}

Aggregation turns a query's rows into groups: a row per group of rows whose By refs hold the same values, with a column per group ref, then a column per measure. Without By, the whole set is one group, and the table one row, even when no row holds: its count is 0, its other measures null. Otherwise a group holds one row at least, but for the bins of GroupBy.Bounds: an empty period never shows, an empty bin does. Rows come ordered by their groups' values, nulls last, before the query's sorts, which name the table's columns.

type Catalog

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

Catalog holds the collections a query reads, one per message type: a jump reads its target by its type.

func Collections

func Collections(r store.Reader, now func() time.Time) (*Catalog, error)

Collections are the collections QueryService reads, by the name its Collection enum gives each (COLLECTION_TASKS is TASKS), with their usual columns and their derived refs. The tasks come with their times, as of now (Timed).

func NewCatalog

func NewCatalog(collections ...Collection) (*Catalog, error)

NewCatalog checks the collections: a name and a type each once, and default refs that compile.

func (*Catalog) Run

func (c *Catalog) Run(ctx context.Context, q Query) (*Table, error)

Run runs q. Its errors wrap ErrInvalid when q cannot run as written.

func (*Catalog) Schema

func (c *Catalog) Schema(name string) ([]Column, error)

Schema gives the refs of a collection: its own, without jumps, then its derived ones.

type Collection

type Collection struct {
	// Name is how a query names it, such as TASKS.
	Name   string
	Source Source
	// Defaults are the refs a query without selects reads: every ref of the schema when empty.
	Defaults []string
	// Derived are the refs it computes in Go, besides its fields' (TaskRefs, QuestionRefs).
	Derived []Derived
}

Collection is a source a query names.

type Column

type Column struct {
	// Ref is how a query names it: code, usage.cost_usd, wish_id->title.
	Ref  string
	Type Type
	// List is a repeated field: its value is a []any of Type, nil when empty.
	List bool
	// Field is the field read last, past the jumps: its descriptor holds its comment, its enum, its options. It is
	// nil for a derived ref, and for a count of rows.
	Field protoreflect.FieldDescriptor
	// Enum is the enum of a TypeEnum column: its field's, or the one a derived ref declares.
	Enum protoreflect.EnumDescriptor
	// Jump is the full name of the message whose id the field holds, by its (djinn.v1.ref) option: the ref
	// Ref+"->"+r reads r there.
	Jump protoreflect.FullName
	// Doc says what a derived ref is.
	Doc string
	// Unit is the unit of its numbers, when they have one: usd, tokens. A time or a duration has none: its type says
	// it.
	Unit string

	// In an aggregated table, Of is the ref a group or a measure reads ("" for a count of rows), Fn the measure's
	// function, Granularity the period a group of times truncates them to, and Bounds the bounds of a group's bins,
	// in Type.
	Of          string
	Fn          Fn
	Granularity Granularity
	Bounds      []any
}

Column is one ref of a collection.

func Schema

Schema gives the refs of md, flattened: a nested message's fields as path.field, never a hidden field, nor a map, nor a repeated message, nor a message that holds itself. Jumps are not followed: Column.Jump names their target.

type Derived

type Derived struct {
	Ref  string
	Type Type
	// Doc says what it is, as a field's comment would.
	Doc string
	// Unit is the unit of its numbers, when they have one (WithUnit).
	Unit string
	// Enum is the enum of its values, for a TypeEnum (DeriveEnum).
	Enum protoreflect.EnumDescriptor
	// contains filtered or unexported fields
}

Derived is a ref a collection computes in Go, where no field holds the value: the size of a hidden text, the time between two of its fields. A query reads it as any ref, across a jump too (wait_question_id->answer::delay). Its name holds :: by convention, after the field it reads: prompt::size.

func Derive

func Derive[M proto.Message](ref string, typ Type, doc string, get func(M) any) Derived

Derive declares a derived ref of the collection whose messages are M's. get gives a value of typ, as Column says, or nil when absent: never a zero for a value it cannot compute.

func DeriveEnum

func DeriveEnum[M proto.Message, E protoreflect.Enum](ref, doc string, get func(M) E) Derived

DeriveEnum declares a derived ref whose values are those of the enum E: get gives one, never its zero, or nil.

func (Derived) WithUnit

func (d Derived) WithUnit(unit string) Derived

WithUnit gives d the unit of its numbers.

type Equal

type Equal struct {
	Ref   string
	Value any
}

Equal holds when Ref's value is Value: text compared ignoring case, as the store compares it.

type Filter

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

Filter keeps the rows it holds for. A null value holds for none but IsNull, and In with IncludeNull. On a list, a filter holds when it holds for one of the list's values.

type Fn

type Fn int

Fn is a measure's function.

const (
	// Count counts the rows, or the rows where Ref is not null: an int, 0 for none.
	Count Fn = iota + 1
	// Sum adds ints, floats or durations, of the type it reads.
	Sum
	// Avg is the mean of ints or floats as a float, of durations as a duration.
	Avg
	// Min and Max take ints, floats, durations or times, of the type they read.
	Min
	Max
	// Median and P90 interpolate between the two closest values (as Postgres's percentile_cont does): a float for
	// ints and floats, a duration for durations.
	Median
	P90
)

The functions of a measure, and the types they take. A list only counts, as a row whose list is not empty.

func (Fn) String

func (f Fn) String() string

type Granularity

type Granularity int

Granularity is the period a group truncates a time to.

const (
	// Day starts at midnight.
	Day Granularity = iota + 1
	// Week starts on Monday at midnight.
	Week
	// Month starts on its first day at midnight.
	Month
)

The granularities of a group.

func (Granularity) String

func (g Granularity) String() string

type Group

type Group struct {
	Op      Op
	Filters []Filter
}

Group joins filters: one at least.

type GroupBy

type GroupBy struct {
	Ref string
	// Granularity truncates a time to the start of its period: the column is then named Ref::day, ::week or ::month,
	// and holds that start, in UTC.
	Granularity Granularity
	// Bounds split a number or a duration into bins, two bounds at least, each above the one before, of the ref's type
	// or a text that reads as one (10s, 1m). A value goes to the bin of the greatest bound at or below it, the first
	// bound's when it is below them all: the first bin holds every value below the second bound, the last one every
	// value from the last bound up. The column is then named Ref::bins and holds the bin's bound. Unlike a period,
	// every bin shows, a count of 0 for an empty one, beside each set of the other groups' values that rows hold.
	Bounds []any
}

GroupBy groups rows by a ref's value, which cannot be a list. Text groups as written, case included; null is a group of its own.

type In

type In struct {
	Ref         string
	Values      []any
	IncludeNull bool
}

In holds when Ref's value is one of Values, or null with IncludeNull.

type IsNull

type IsNull struct {
	Ref string
}

IsNull holds when Ref's value is absent.

type Measure

type Measure struct {
	// Ref is the ref read: empty for a count of rows.
	Ref   string
	Fn    Fn
	Alias string
}

Measure computes a function over the values of a ref in each group. Every function skips the nulls: the count counts the values, the others are null for a group without value. Its column is named Alias, or Ref::fn (running::median), or count for a count of rows.

type Meta

type Meta struct {
	Ref   string `json:"ref"`
	Label string `json:"label"`
	// Unit is the unit of the numbers, when they have one: usd, tokens.
	Unit string `json:"unit,omitempty"`
	// Type is Djinn's type of the column: string, enum, int, float, bool, time or duration.
	Type string `json:"type"`
	List bool   `json:"list,omitempty"`
	// Of, Fn, Granularity and Bounds are an aggregated column's: the ref it reads, its function, the period of a group
	// of times, the bounds of a group's bins (durations in milliseconds, as the column holds them).
	Of          string `json:"of,omitempty"`
	Fn          string `json:"fn,omitempty"`
	Granularity string `json:"granularity,omitempty"`
	Bounds      []any  `json:"bounds,omitempty"`
}

Meta is the "djinn" metadata of each field of a table in Arrow, as JSON.

type Op

type Op int

Op is how a Group joins its filters.

const (
	// And holds when every filter holds.
	And Op = iota + 1
	// Or holds when one filter holds.
	Or
	// Not holds when the filters, joined as And, do not.
	Not
)

The ops of a Group.

type Query

type Query struct {
	Collection string
	// Filters all hold for a row the table keeps.
	Filters []Filter
	// Sorts order the rows, the first one first; then rows keep the source's order, oldest first. A null comes
	// last either way.
	Sorts []Sort
	// Selects are the refs of the table's columns, in order: the collection's defaults when empty.
	Selects []string
	// Limit keeps the first rows only, when above 0.
	Limit int
	// Aggregation, when set, makes the table a row per group, its columns the groups' and the measures': it
	// selects them, and the sorts name them.
	Aggregation *Aggregation
}

Query asks a collection for a table.

func Request

Request turns a QueryService request, its typed messages, into a Query. Its errors wrap ErrInvalid.

type Range

type Range struct {
	Ref              string
	Gt, Gte, Lt, Lte any
}

Range holds when Ref's value, a number, a time or a duration, is within each bound given.

type Sort

type Sort struct {
	Ref  string
	Desc bool
}

Sort orders rows by a ref, which cannot be a list.

type Source

type Source interface {
	// Descriptor is the message the source gives.
	Descriptor() protoreflect.MessageDescriptor
	// Indexed names the singular text fields where narrows by.
	Indexed() []string
	// Load gives the messages whose fields equal where's values, text ignoring case: all of them for an empty where.
	Load(ctx context.Context, where map[string]string) ([]proto.Message, error)
}

Source gives the messages of a collection.

func FromStore

func FromStore(r store.Reader, m proto.Message) (Source, error)

FromStore is the source of the entities of m's type in the store: where narrows by their text columns, the *_id fields and the unique ones, in SQL. Entities not migrated at start (store.ErrUnmigrated) make a source each load of which fails with that error, as each use of them does: the other collections read, and djinn up starts (Q42).

func Timed

func Timed(r store.Reader, src Source, now func() time.Time) Source

Timed gives the tasks of src with their times, which the store does not keep: running, waiting_gate, paused and waiting_before_start, as the task list computes them from their runs and gate waits as of now (plan.ReadTimes), an azima's summing its parts'. A task that never started has none but waiting_before_start: null, never 0. Each comes with the length of its first prompt (plan.PromptLengths). Loads asked at the same time with the same where share one read: the Statistics tab asks a dozen at once, and the store reads on one connection.

type Table

type Table struct {
	Columns []Column
	// Rows hold a value per column, nil when absent.
	Rows [][]any
	// Total counts the rows before the limit: the groups when aggregated.
	Total int
}

Table is a query's answer.

func (*Table) Arrow

func (t *Table) Arrow() ([]byte, error)

Arrow writes t as an Arrow IPC stream of one record batch: a field per column, named by its ref, of the type its column has (a list of them for a list, of names for a list of enums), each holding its Meta. An absent value is null, never 0.

func (*Table) WriteCSV

func (t *Table) WriteCSV(w io.Writer) error

WriteCSV writes t as CSV: a header of refs, then a line per row. An absent value is an empty cell; an enum is its value's name without its prefix, in lower case (running); a time is RFC 3339 in UTC; a duration is Go's without its trailing zero units (1h30m, 1h); a list joins its values with ", "; a bin is its range (< 10s, 10s to 1m, >= 1h).

func (*Table) WriteText

func (t *Table) WriteText(w io.Writer) error

WriteText writes t aligned, a line per row under a line of refs, then how many rows it holds. A value is written as in WriteCSV.

type Text

type Text struct {
	Ref        string
	Contains   string
	BeginsWith string
}

Text holds when Ref's text contains Contains, or begins with BeginsWith, ignoring case: one of the two.

type Type

type Type int

Type is the type of a column, taken from the descriptor.

const (
	TypeString Type = iota + 1
	TypeEnum
	TypeInt
	TypeFloat
	TypeBool
	TypeTime
	TypeDuration
)

The types of a column. A value is nil when absent, or else a string (TypeString, and TypeEnum by its value's name), an int64, a float64, a bool, a time.Time in UTC or a time.Duration.

func (Type) String

func (t Type) String() string

Jump to

Keyboard shortcuts

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